@descope/web-component 4.7.1 → 4.7.3

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.
@@ -1,2 +1,2 @@
1
- import{__classPrivateFieldGet as t,__awaiter as e,__classPrivateFieldSet as i}from"tslib";import{compose as s}from"@descope/sdk-helpers";import{staticResourcesMixin as r}from"@descope/sdk-mixins/static-resources-mixin";import{themeMixin as o}from"@descope/sdk-mixins/theme-mixin";import{injectStyleMixin as n}from"@descope/sdk-mixins/inject-style-mixin";import{telemetryMixin as a}from"@descope/sdk-mixins/telemetry-mixin";import{createSdk as u,getSessionToken as l}from"@descope/web-js-sdk";import{ELEMENTS_TO_IGNORE_ENTER_KEY_ON as d}from"../constants/index.js";import{handleUrlParams as c,clearRunIdsFromUrl as h,camelCase as f,getRunIdsFromUrl as g,getContentUrl as p,fetchContent as m,withRetry as v}from"../helpers/helpers.js";import b from"../helpers/state.js";import"@descope/escape-markdown";import"../helpers/webauthn.js";import{setCustomStorage as w}from"../helpers/storage.js";import{transformFlowInputFormData as k,extractNestedAttribute as y}from"../helpers/flowInputs.js";import{formMountMixin as C}from"../mixins/formMountMixin.js";import{componentConditionsMixin as x}from"../mixins/componentConditionsMixin.js";import{duplicateFlowWarningMixin as A}from"../mixins/duplicateFlowWarningMixin.js";import{passwordManagerMixin as j}from"../mixins/passwordManagerMixin.js";import{emailVerificationMixin as I}from"../mixins/emailVerificationMixin.js";import{validationTrackingMixin as E}from"../mixins/validationTrackingMixin.js";import{CONFIG_FILENAME as M,PREV_VER_ASSETS_FOLDER as S}from"../constants/content.js";import{FETCH_EXCEPTION_ERROR_CODE as L}from"../constants/general.js";var U,O,W,P,D,N,T,F,K,R,V,z,J,B,H,q,$,Q,G,X,Y,Z,_,tt,et,it;const st=s(o,r,C,x,A,j,I,n,a,E)(HTMLElement);class rt extends st{static get observedAttributes(){return["project-id","flow-id","base-url","tenant","locale","debug","storage-prefix","preview","redirect-url","auto-focus","store-last-authenticated-user","refresh-cookie-name","keep-last-authenticated-user-after-logout","validate-on-blur","send-session-token","style-id"]}constructor(s){super(),U.add(this),this.sdkVersion="4.7.1",W.set(this,!1),P.set(this,void 0),this.flowStatus="initial",this.loggerWrapper={error:(e,i="")=>{this.logger.error(e,i,new Error),t(this,U,"m",it).call(this,e,i)},warn:(t,e="")=>{this.logger.warn(t,e)},info:(t,e="",i={})=>{this.logger.info(t,e,i)},debug:(t,e="")=>{this.logger.debug(t,e)}},D.set(this,new b),N.set(this,new b),T.set(this,{}),this.getComponentsContext=()=>t(this,T,"f"),this.nextRequestStatus=new b({isLoading:!1}),F.set(this,void 0),K.set(this,{popstate:t(this,U,"m",B).bind(this),componentsContext:t(this,U,"m",X).bind(this)}),R.set(this,void 0),this.getConfig=()=>e(this,void 0,void 0,(function*(){return(yield this.config)||{isMissingConfig:!0}})),Y.set(this,void 0),Z.set(this,void 0),i(this,R,s,"f"),t(this,U,"m",z).call(this)}get client(){try{return JSON.parse(this.getAttribute("client"))||{}}catch(t){return{}}}get redirectUrl(){return this.getAttribute("redirect-url")||void 0}get debug(){return"true"===this.getAttribute("debug")}get locale(){return this.getAttribute("locale")||void 0}get autoFocus(){var t;const e=null!==(t=this.getAttribute("auto-focus"))&&void 0!==t?t:"true";return"skipFirstScreen"===e?e:"true"===e}get validateOnBlur(){return"true"===this.getAttribute("validate-on-blur")}get storeLastAuthenticatedUser(){var t;return"true"===(null!==(t=this.getAttribute("store-last-authenticated-user"))&&void 0!==t?t:"true")}get refreshCookieName(){return this.getAttribute("refresh-cookie-name")||""}get keepLastAuthenticatedUserAfterLogout(){return"true"===this.getAttribute("keep-last-authenticated-user-after-logout")}get storagePrefix(){return this.getAttribute("storage-prefix")||""}get sendSessionToken(){return"true"===this.getAttribute("send-session-token")}get preview(){return!!this.getAttribute("preview")}get formConfig(){return k(this.form)}get form(){return this.getAttribute("form")}get formConfigValues(){return y(this.formConfig,"value")}get outboundAppId(){return this.getAttribute("outbound-app-id")}get outboundAppScopes(){try{const t=JSON.parse(this.getAttribute("outbound-app-scopes"));return t||null}catch(t){return null}}get popupOrigin(){return this.getAttribute("popup-origin")}get customStorage(){return t(this,P,"f")}set customStorage(t){if(t&&"function"!=typeof t.getItem)throw new Error("Custom storage must have a getItem method");if(t&&"function"!=typeof t.setItem)throw new Error("Custom storage must have a setItem method");if(t&&"function"!=typeof t.removeItem)throw new Error("Custom storage must have a removeItem method");i(this,P,t,"f"),w(t)}get lazyStart(){return"true"===this.getAttribute("lazy-start")}start(){var e;null===(e=t(this,Z,"f"))||void 0===e||e.call(this),i(this,Y,Promise.resolve(),"f")}get isRestartOnError(){return"true"===this.getAttribute("restart-on-error")}getExecutionContext(){return e(this,void 0,void 0,(function*(){const t=yield this.getConfig();return"executionContext"in t?t.executionContext:void 0}))}getProjectConfig(){return e(this,void 0,void 0,(function*(){const t=yield this.getConfig();return"projectConfig"in t?t.projectConfig:void 0}))}getFlowConfig(){return e(this,void 0,void 0,(function*(){var t,e;const i=yield this.getProjectConfig(),s=(null===(t=null==i?void 0:i.flows)||void 0===t?void 0:t[this.flowId])||{};return null!==(e=s.version)&&void 0!==e||(s.version=0),s}))}getTargetLocales(){return e(this,void 0,void 0,(function*(){const t=yield this.getFlowConfig();return((null==t?void 0:t.targetLocales)||[]).map((t=>t.toLowerCase()))}))}handleKeyPress(){this.logger.debug("Enable key press handler"),this.rootElement.onkeydown=t=>{var e,i,s;const r=!!(null===(e=this.shadowRoot.activeElement)||void 0===e?void 0:e.getAttribute("href")),o=d.includes(null!==(s=null===(i=this.shadowRoot.activeElement)||void 0===i?void 0:i.localName)&&void 0!==s?s:"");if("Enter"!==t.key||r||o)return;t.preventDefault();const n=this.rootElement.querySelectorAll("descope-button");if(1===n.length&&"false"!==n[0].getAttribute("auto-submit"))return void n[0].click();const a=Array.from(n).filter((t=>"true"===t.getAttribute("auto-submit")));if(1===a.length)return void a[0].click();const u=Array.from(n).filter((t=>"button"===t.getAttribute("data-type")));if(1===u.length)"false"!==u[0].getAttribute("auto-submit")&&u[0].click();else if(0===u.length){const t=Array.from(n).filter((t=>"sso"===t.getAttribute("data-type")));1===t.length&&"false"!==t[0].getAttribute("auto-submit")&&t[0].click()}}}disableKeyPressHandler(){this.logger.debug("Disable key press handler"),this.rootElement.onkeydown=null}getComponentsVersion(){return e(this,void 0,void 0,(function*(){var t;const e=yield this.getConfig(),i="projectConfig"in e?null===(t=e.projectConfig)||void 0===t?void 0:t.componentsVersion:{};return i||(this.logger.error("Did not get components version, using latest version"),"latest")}))}init(){const s=Object.create(null,{init:{get:()=>super.init}});return e(this,void 0,void 0,(function*(){var e;if(this.flowStatus="loading",["ready","error","success"].forEach((t=>this.addEventListener(t,(()=>{this.flowStatus=t})))),yield null===(e=s.init)||void 0===e?void 0:e.call(this),t(this,N,"f").subscribe(t(this,U,"m",et).bind(this)),t(this,N,"f").update({isDebug:this.debug}),t(this,U,"m",J).call(this),yield t(this,U,"m",Q).call(this))return void this.loggerWrapper.error("This SDK version does not support your flows version","Make sure to upgrade your flows to the latest version or use an older SDK version");const r=yield this.getConfig();if("isMissingConfig"in r&&r.isMissingConfig)return void this.loggerWrapper.error("Cannot get config file","Make sure that your projectId & flowId are correct");const{executionId:o,stepId:n,token:a,code:u,isPopup:l,exchangeError:d,redirectAuthCallbackUrl:h,redirectAuthBackupCallbackUri:f,redirectAuthCodeChallenge:g,redirectAuthInitiator:p,ssoQueryParams:m}=c(this.flowId,this.projectId,this.loggerWrapper);window.addEventListener("popstate",t(this,K,"f").popstate),window.addEventListener("components-context",t(this,K,"f").componentsContext),t(this,D,"f").subscribe(t(this,U,"m",$).bind(this)),t(this,D,"f").update(Object.assign({projectId:this.projectId,flowId:this.flowId,baseUrl:this.baseUrl,tenant:this.tenantId,redirectUrl:this.redirectUrl,locale:this.locale,stepId:n,executionId:o,token:a,code:u,isPopup:l,exchangeError:d,redirectAuthCallbackUrl:h,redirectAuthBackupCallbackUri:f,redirectAuthCodeChallenge:g,redirectAuthInitiator:p},m)),i(this,W,!0,"f")}))}disconnectedCallback(){var e;t(this,D,"f").unsubscribeAll(),t(this,N,"f").unsubscribeAll(),t(this,U,"m",tt).call(this),window.removeEventListener("popstate",t(this,K,"f").popstate),window.removeEventListener("components-context",t(this,K,"f").componentsContext),null===(e=super.disconnectedCallback)||void 0===e||e.call(this)}attributeChangedCallback(e,i,s){var r;if(null===(r=super.attributeChangedCallback)||void 0===r||r.call(this,e,i,s),this.shadowRoot.isConnected&&t(this,W,"f")&&i!==s&&O.observedAttributes.includes(e)){t(this,U,"m",J).call(this);const r=null===i;t(this,D,"f").update((({stepId:t,executionId:i})=>{let o=t,n=i;return r||(n=null,o=null,h()),{[f(e)]:s,stepId:o,executionId:n}})),t(this,N,"f").update({isDebug:this.debug})}}}O=rt,W=new WeakMap,P=new WeakMap,D=new WeakMap,N=new WeakMap,T=new WeakMap,F=new WeakMap,K=new WeakMap,R=new WeakMap,Y=new WeakMap,Z=new WeakMap,U=new WeakSet,V=function(){this.injectStyle("\n :host {\n\t\t\twidth: 100%;\n display: block;\n\t\t}\n\n\t\t#root {\n\t\t\theight: 100%;\n display: flex;\n flex-direction: column;\n\t\t}\n\n #content-root {\n all: initial;\n transition: opacity 200ms ease-in-out;\n }\n\n\t\t#root[data-theme] {\n\t\t\tbackground-color: transparent;\n\t\t}\n\n\t\t.fade-out {\n\t\t\topacity: 0.1!important;\n\t\t}\n\n .hidden {\n display: none;\n }\n ")},z=function(){t(this,U,"m",V).call(this),this.slotElement=document.createElement("slot"),this.slotElement.classList.add("hidden"),this.rootElement.appendChild(this.slotElement)},J=function(){const t=["base-url","tenant","locale","debug","redirect-url","auto-focus","store-last-authenticated-user","refresh-cookie-name","keep-last-authenticated-user-after-logout","preview","storage-prefix","form","client","validate-on-blur","send-session-token","style-id","outbound-app-id","outbound-app-scopes","theme-override"];O.observedAttributes.forEach((e=>{if(!t.includes(e)&&!this[f(e)])throw Error(`${e} cannot be empty`)}))},B=function(){const{stepId:e,executionId:i}=g(this.flowId);i&&t(this,D,"f").update({stepId:e,executionId:i})},H=function(i,s){u&&"function"==typeof u||this.logger.error("SDK was not loaded properly",u,JSON.stringify(u));const r=Object.assign(Object.assign({persistTokens:!0,preview:this.preview,storagePrefix:this.storagePrefix,storeLastAuthenticatedUser:this.storeLastAuthenticatedUser,keepLastAuthenticatedUserAfterLogout:this.keepLastAuthenticatedUserAfterLogout,refreshCookieName:this.refreshCookieName},O.sdkConfigOverrides),{projectId:i,baseUrl:s});t(this,P,"f")&&(r.customStorage=t(this,P,"f")),this.sdk=u(r);const o={start:1,next:7};["start","next"].forEach((i=>{const s=this.sdk.flow[i],r=v(s,1e3,3);this.sdk.flow[i]=(...s)=>e(this,void 0,void 0,(function*(){const e=[...s],n=o[i],a=t(this,U,"m",q).call(this,e[n]);void 0!==a&&(e[n]=a);try{return yield r(...e)}catch(t){return this.logger.error(`Error in sdk flow ${i} function`,t),{error:{errorCode:L,errorDescription:t.toString()}}}}))}));const n=this.sdk.flow.start;this.sdk.flow.start=(...i)=>e(this,void 0,void 0,(function*(){return yield t(this,U,"m",_).call(this),n.apply(this.sdk.flow,i)}))},q=function(t){if(!this.sendSessionToken)return t;const e=null==l?void 0:l(this.storagePrefix);return e?Object.assign(Object.assign({},null!=t?t:{}),{sessionJwt:e}):t},$=function(i,s,r){return e(this,void 0,void 0,(function*(){const{projectId:e,baseUrl:s}=i;if(r("projectId")||r("baseUrl")){if(!e)return;t(this,U,"m",H).call(this,e,s)}t(this,R,"f").call(this,i)}))},Q=function(){return e(this,void 0,void 0,(function*(){const e=yield this.getConfig();return"isMissingConfig"in e&&e.isMissingConfig&&(yield t(this,U,"m",G).call(this))}))},G=function(){return e(this,void 0,void 0,(function*(){const t=p({projectId:this.projectId,filename:M,assetsFolder:S,baseUrl:this.baseStaticUrl});try{return yield m(t,"json"),!0}catch(t){return!1}}))},X=function(e){i(this,T,Object.assign(Object.assign({},t(this,T,"f")),e.detail),"f")},_=function(){return this.lazyStart?(t(this,Y,"f")||i(this,Y,new Promise((t=>{i(this,Z,t,"f")})),"f"),t(this,Y,"f")):Promise.resolve()},tt=function(){var e;null===(e=t(this,F,"f"))||void 0===e||e.remove(),i(this,F,null,"f")},et=function(s){return e(this,arguments,void 0,(function*({isDebug:e}){e?(i(this,F,document.createElement("descope-debugger"),"f"),Object.assign(t(this,F,"f").style,{position:"fixed",top:"0",right:"0",height:"100vh",width:"100vw",pointerEvents:"none",zIndex:99999}),yield import("../debugger-wc.js"),document.body.appendChild(t(this,F,"f"))):t(this,U,"m",tt).call(this)}))},it=function(e,i){var s;e&&this.debug&&(null===(s=t(this,F,"f"))||void 0===s||s.updateData({title:e,description:i}))},rt.sdkConfigOverrides={baseHeaders:{"x-descope-sdk-name":"web-component","x-descope-sdk-version":"4.7.1"}};export{rt as default};
1
+ import{__classPrivateFieldGet as t,__awaiter as e,__classPrivateFieldSet as i}from"tslib";import{compose as s}from"@descope/sdk-helpers";import{staticResourcesMixin as r}from"@descope/sdk-mixins/static-resources-mixin";import{themeMixin as o}from"@descope/sdk-mixins/theme-mixin";import{injectStyleMixin as n}from"@descope/sdk-mixins/inject-style-mixin";import{telemetryMixin as a}from"@descope/sdk-mixins/telemetry-mixin";import{createSdk as u,getSessionToken as l}from"@descope/web-js-sdk";import{ELEMENTS_TO_IGNORE_ENTER_KEY_ON as d}from"../constants/index.js";import{handleUrlParams as h,clearRunIdsFromUrl as c,camelCase as f,getRunIdsFromUrl as g,getContentUrl as p,fetchContent as m,withRetry as v}from"../helpers/helpers.js";import b from"../helpers/state.js";import"@descope/escape-markdown";import"../helpers/webauthn.js";import{setCustomStorage as w}from"../helpers/storage.js";import{transformFlowInputFormData as k,extractNestedAttribute as y}from"../helpers/flowInputs.js";import{formMountMixin as C}from"../mixins/formMountMixin.js";import{componentConditionsMixin as x}from"../mixins/componentConditionsMixin.js";import{duplicateFlowWarningMixin as A}from"../mixins/duplicateFlowWarningMixin.js";import{passwordManagerMixin as j}from"../mixins/passwordManagerMixin.js";import{emailVerificationMixin as I}from"../mixins/emailVerificationMixin.js";import{validationTrackingMixin as E}from"../mixins/validationTrackingMixin.js";import{CONFIG_FILENAME as M,PREV_VER_ASSETS_FOLDER as S}from"../constants/content.js";import{FETCH_EXCEPTION_ERROR_CODE as L}from"../constants/general.js";var U,O,W,P,D,N,T,F,K,R,V,z,J,B,H,Q,q,$,G,X,Y,Z,_,tt,et,it,st;const rt=s(o,r,C,x,A,j,I,n,a,E)(HTMLElement);class ot extends rt{static get observedAttributes(){return["project-id","flow-id","base-url","tenant","locale","debug","storage-prefix","preview","redirect-url","auto-focus","store-last-authenticated-user","refresh-cookie-name","keep-last-authenticated-user-after-logout","validate-on-blur","send-session-token","style-id"]}get adoptedSsoQueryParams(){return t(this,D,"f")}constructor(s){super(),U.add(this),this.sdkVersion="4.7.3",W.set(this,!1),P.set(this,void 0),D.set(this,null),this.flowStatus="initial",this.loggerWrapper={error:(e,i="")=>{this.logger.error(e,i,new Error),t(this,U,"m",st).call(this,e,i)},warn:(t,e="")=>{this.logger.warn(t,e)},info:(t,e="",i={})=>{this.logger.info(t,e,i)},debug:(t,e="")=>{this.logger.debug(t,e)}},N.set(this,new b),T.set(this,new b),F.set(this,{}),this.getComponentsContext=()=>t(this,F,"f"),this.nextRequestStatus=new b({isLoading:!1}),K.set(this,void 0),R.set(this,{popstate:t(this,U,"m",H).bind(this),componentsContext:t(this,U,"m",Y).bind(this)}),V.set(this,void 0),this.getConfig=()=>e(this,void 0,void 0,(function*(){return(yield this.config)||{isMissingConfig:!0}})),Z.set(this,void 0),_.set(this,void 0),i(this,V,s,"f"),t(this,U,"m",J).call(this)}get client(){try{return JSON.parse(this.getAttribute("client"))||{}}catch(t){return{}}}get redirectUrl(){return this.getAttribute("redirect-url")||void 0}get debug(){return"true"===this.getAttribute("debug")}get locale(){return this.getAttribute("locale")||void 0}get autoFocus(){var t;const e=null!==(t=this.getAttribute("auto-focus"))&&void 0!==t?t:"true";return"skipFirstScreen"===e?e:"true"===e}get validateOnBlur(){return"true"===this.getAttribute("validate-on-blur")}get storeLastAuthenticatedUser(){var t;return"true"===(null!==(t=this.getAttribute("store-last-authenticated-user"))&&void 0!==t?t:"true")}get refreshCookieName(){return this.getAttribute("refresh-cookie-name")||""}get keepLastAuthenticatedUserAfterLogout(){return"true"===this.getAttribute("keep-last-authenticated-user-after-logout")}get storagePrefix(){return this.getAttribute("storage-prefix")||""}get sendSessionToken(){return"true"===this.getAttribute("send-session-token")}get preview(){return!!this.getAttribute("preview")}get formConfig(){return k(this.form)}get form(){return this.getAttribute("form")}get formConfigValues(){return y(this.formConfig,"value")}get outboundAppId(){return this.getAttribute("outbound-app-id")}get outboundAppScopes(){try{const t=JSON.parse(this.getAttribute("outbound-app-scopes"));return t||null}catch(t){return null}}get popupOrigin(){return this.getAttribute("popup-origin")}get customStorage(){return t(this,P,"f")}set customStorage(t){if(t&&"function"!=typeof t.getItem)throw new Error("Custom storage must have a getItem method");if(t&&"function"!=typeof t.setItem)throw new Error("Custom storage must have a setItem method");if(t&&"function"!=typeof t.removeItem)throw new Error("Custom storage must have a removeItem method");i(this,P,t,"f"),w(t)}get lazyStart(){return"true"===this.getAttribute("lazy-start")}start(){var e;null===(e=t(this,_,"f"))||void 0===e||e.call(this),i(this,Z,Promise.resolve(),"f")}get isRestartOnError(){return"true"===this.getAttribute("restart-on-error")}getExecutionContext(){return e(this,void 0,void 0,(function*(){const t=yield this.getConfig();return"executionContext"in t?t.executionContext:void 0}))}getProjectConfig(){return e(this,void 0,void 0,(function*(){const t=yield this.getConfig();return"projectConfig"in t?t.projectConfig:void 0}))}getFlowConfig(){return e(this,void 0,void 0,(function*(){var t,e;const i=yield this.getProjectConfig(),s=(null===(t=null==i?void 0:i.flows)||void 0===t?void 0:t[this.flowId])||{};return null!==(e=s.version)&&void 0!==e||(s.version=0),s}))}getTargetLocales(){return e(this,void 0,void 0,(function*(){const t=yield this.getFlowConfig();return((null==t?void 0:t.targetLocales)||[]).map((t=>t.toLowerCase()))}))}handleKeyPress(){this.logger.debug("Enable key press handler"),this.rootElement.onkeydown=t=>{var e,i,s;const r=!!(null===(e=this.shadowRoot.activeElement)||void 0===e?void 0:e.getAttribute("href")),o=d.includes(null!==(s=null===(i=this.shadowRoot.activeElement)||void 0===i?void 0:i.localName)&&void 0!==s?s:"");if("Enter"!==t.key||r||o)return;t.preventDefault();const n=this.rootElement.querySelectorAll("descope-button");if(1===n.length&&"false"!==n[0].getAttribute("auto-submit"))return void n[0].click();const a=Array.from(n).filter((t=>"true"===t.getAttribute("auto-submit")));if(1===a.length)return void a[0].click();const u=Array.from(n).filter((t=>"button"===t.getAttribute("data-type")));if(1===u.length)"false"!==u[0].getAttribute("auto-submit")&&u[0].click();else if(0===u.length){const t=Array.from(n).filter((t=>"sso"===t.getAttribute("data-type")));1===t.length&&"false"!==t[0].getAttribute("auto-submit")&&t[0].click()}}}disableKeyPressHandler(){this.logger.debug("Disable key press handler"),this.rootElement.onkeydown=null}getComponentsVersion(){return e(this,void 0,void 0,(function*(){var t;const e=yield this.getConfig(),i="projectConfig"in e?null===(t=e.projectConfig)||void 0===t?void 0:t.componentsVersion:{};return i||(this.logger.error("Did not get components version, using latest version"),"latest")}))}init(){const s=Object.create(null,{init:{get:()=>super.init}});return e(this,void 0,void 0,(function*(){var e;if(this.flowStatus="loading",["ready","error","success"].forEach((t=>this.addEventListener(t,(()=>{this.flowStatus=t})))),yield null===(e=s.init)||void 0===e?void 0:e.call(this),t(this,T,"f").subscribe(t(this,U,"m",it).bind(this)),t(this,T,"f").update({isDebug:this.debug}),t(this,U,"m",B).call(this),yield t(this,U,"m",G).call(this))return void this.loggerWrapper.error("This SDK version does not support your flows version","Make sure to upgrade your flows to the latest version or use an older SDK version");const r=yield this.getConfig();if("isMissingConfig"in r&&r.isMissingConfig)return void this.loggerWrapper.error("Cannot get config file","Make sure that your projectId & flowId are correct");const{executionId:o,stepId:n,token:a,code:u,isPopup:l,exchangeError:d,redirectAuthCallbackUrl:c,redirectAuthBackupCallbackUri:f,redirectAuthCodeChallenge:g,redirectAuthInitiator:p,ssoQueryParams:m,adoptedSsoQueryParams:v}=h(this.flowId,this.projectId,this.loggerWrapper);i(this,D,null!=v?v:null,"f"),window.addEventListener("popstate",t(this,R,"f").popstate),window.addEventListener("components-context",t(this,R,"f").componentsContext),t(this,N,"f").subscribe(t(this,U,"m",$).bind(this)),t(this,N,"f").update(Object.assign({projectId:this.projectId,flowId:this.flowId,baseUrl:this.baseUrl,tenant:this.tenantId,redirectUrl:this.redirectUrl,locale:this.locale,stepId:n,executionId:o,token:a,code:u,isPopup:l,exchangeError:d,redirectAuthCallbackUrl:c,redirectAuthBackupCallbackUri:f,redirectAuthCodeChallenge:g,redirectAuthInitiator:p},m)),i(this,W,!0,"f")}))}disconnectedCallback(){var e;t(this,N,"f").unsubscribeAll(),t(this,T,"f").unsubscribeAll(),t(this,U,"m",et).call(this),window.removeEventListener("popstate",t(this,R,"f").popstate),window.removeEventListener("components-context",t(this,R,"f").componentsContext),null===(e=super.disconnectedCallback)||void 0===e||e.call(this)}attributeChangedCallback(e,i,s){var r;if(null===(r=super.attributeChangedCallback)||void 0===r||r.call(this,e,i,s),this.shadowRoot.isConnected&&t(this,W,"f")&&i!==s&&O.observedAttributes.includes(e)){t(this,U,"m",B).call(this);const r=null===i;t(this,N,"f").update((({stepId:t,executionId:i})=>{let o=t,n=i;return r||(n=null,o=null,c()),{[f(e)]:s,stepId:o,executionId:n}})),t(this,T,"f").update({isDebug:this.debug})}}}O=ot,W=new WeakMap,P=new WeakMap,D=new WeakMap,N=new WeakMap,T=new WeakMap,F=new WeakMap,K=new WeakMap,R=new WeakMap,V=new WeakMap,Z=new WeakMap,_=new WeakMap,U=new WeakSet,z=function(){this.injectStyle("\n :host {\n\t\t\twidth: 100%;\n display: block;\n\t\t}\n\n\t\t#root {\n\t\t\theight: 100%;\n display: flex;\n flex-direction: column;\n\t\t}\n\n #content-root {\n all: initial;\n transition: opacity 200ms ease-in-out;\n }\n\n\t\t#root[data-theme] {\n\t\t\tbackground-color: transparent;\n\t\t}\n\n\t\t.fade-out {\n\t\t\topacity: 0.1!important;\n\t\t}\n\n .hidden {\n display: none;\n }\n ")},J=function(){t(this,U,"m",z).call(this),this.slotElement=document.createElement("slot"),this.slotElement.classList.add("hidden"),this.rootElement.appendChild(this.slotElement)},B=function(){const t=["base-url","tenant","locale","debug","redirect-url","auto-focus","store-last-authenticated-user","refresh-cookie-name","keep-last-authenticated-user-after-logout","preview","storage-prefix","form","client","validate-on-blur","send-session-token","style-id","outbound-app-id","outbound-app-scopes","theme-override"];O.observedAttributes.forEach((e=>{if(!t.includes(e)&&!this[f(e)])throw Error(`${e} cannot be empty`)}))},H=function(){const{stepId:e,executionId:i}=g(this.flowId);i&&t(this,N,"f").update({stepId:e,executionId:i})},Q=function(i,s){u&&"function"==typeof u||this.logger.error("SDK was not loaded properly",u,JSON.stringify(u));const r=Object.assign(Object.assign({persistTokens:!0,preview:this.preview,storagePrefix:this.storagePrefix,storeLastAuthenticatedUser:this.storeLastAuthenticatedUser,keepLastAuthenticatedUserAfterLogout:this.keepLastAuthenticatedUserAfterLogout,refreshCookieName:this.refreshCookieName},O.sdkConfigOverrides),{projectId:i,baseUrl:s});t(this,P,"f")&&(r.customStorage=t(this,P,"f")),this.sdk=u(r);const o={start:1,next:7};["start","next"].forEach((i=>{const s=this.sdk.flow[i],r=v(s,1e3,3);this.sdk.flow[i]=(...s)=>e(this,void 0,void 0,(function*(){const e=[...s],n=o[i],a=t(this,U,"m",q).call(this,e[n]);void 0!==a&&(e[n]=a);try{return yield r(...e)}catch(t){return this.logger.error(`Error in sdk flow ${i} function`,t),{error:{errorCode:L,errorDescription:t.toString()}}}}))}));const n=this.sdk.flow.start;this.sdk.flow.start=(...i)=>e(this,void 0,void 0,(function*(){return yield t(this,U,"m",tt).call(this),n.apply(this.sdk.flow,i)}))},q=function(t){if(!this.sendSessionToken)return t;const e=null==l?void 0:l(this.storagePrefix);return e?Object.assign(Object.assign({},null!=t?t:{}),{sessionJwt:e}):t},$=function(i,s,r){return e(this,void 0,void 0,(function*(){const{projectId:e,baseUrl:s}=i;if(r("projectId")||r("baseUrl")){if(!e)return;t(this,U,"m",Q).call(this,e,s)}t(this,V,"f").call(this,i)}))},G=function(){return e(this,void 0,void 0,(function*(){const e=yield this.getConfig();return"isMissingConfig"in e&&e.isMissingConfig&&(yield t(this,U,"m",X).call(this))}))},X=function(){return e(this,void 0,void 0,(function*(){const t=p({projectId:this.projectId,filename:M,assetsFolder:S,baseUrl:this.baseStaticUrl});try{return yield m(t,"json"),!0}catch(t){return!1}}))},Y=function(e){i(this,F,Object.assign(Object.assign({},t(this,F,"f")),e.detail),"f")},tt=function(){return this.lazyStart?(t(this,Z,"f")||i(this,Z,new Promise((t=>{i(this,_,t,"f")})),"f"),t(this,Z,"f")):Promise.resolve()},et=function(){var e;null===(e=t(this,K,"f"))||void 0===e||e.remove(),i(this,K,null,"f")},it=function(s){return e(this,arguments,void 0,(function*({isDebug:e}){e?(i(this,K,document.createElement("descope-debugger"),"f"),Object.assign(t(this,K,"f").style,{position:"fixed",top:"0",right:"0",height:"100vh",width:"100vw",pointerEvents:"none",zIndex:99999}),yield import("../debugger-wc.js"),document.body.appendChild(t(this,K,"f"))):t(this,U,"m",et).call(this)}))},st=function(e,i){var s;e&&this.debug&&(null===(s=t(this,K,"f"))||void 0===s||s.updateData({title:e,description:i}))},ot.sdkConfigOverrides={baseHeaders:{"x-descope-sdk-name":"web-component","x-descope-sdk-version":"4.7.3"}};export{ot as default};
2
2
  //# sourceMappingURL=BaseDescopeWc.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"BaseDescopeWc.js","sources":["../../../src/lib/descope-wc/BaseDescopeWc.ts"],"sourcesContent":["import { compose } from '@descope/sdk-helpers';\n// eslint-disable-next-line import/no-duplicates\nimport { staticResourcesMixin } from '@descope/sdk-mixins/static-resources-mixin';\n// eslint-disable-next-line import/no-duplicates\nimport { themeMixin } from '@descope/sdk-mixins/theme-mixin';\n// eslint-disable-next-line import/no-duplicates\nimport { injectStyleMixin } from '@descope/sdk-mixins/inject-style-mixin';\n// eslint-disable-next-line import/no-duplicates\nimport { telemetryMixin } from '@descope/sdk-mixins/telemetry-mixin';\nimport { createSdk, getSessionToken } from '@descope/web-js-sdk';\nimport type { FlowNextOptions, FlowStartOptions } from '@descope/web-js-sdk';\nimport {\n CONFIG_FILENAME,\n ELEMENTS_TO_IGNORE_ENTER_KEY_ON,\n FETCH_EXCEPTION_ERROR_CODE,\n PREV_VER_ASSETS_FOLDER,\n} from '../constants';\nimport {\n camelCase,\n clearRunIdsFromUrl,\n fetchContent,\n getContentUrl,\n getRunIdsFromUrl,\n handleUrlParams,\n State,\n withRetry,\n} from '../helpers';\nimport {\n extractNestedAttribute,\n transformFlowInputFormData,\n} from '../helpers/flowInputs';\nimport { setCustomStorage } from '../helpers/storage';\nimport { IsChanged } from '../helpers/state';\nimport {\n formMountMixin,\n componentConditionsMixin,\n duplicateFlowWarningMixin,\n passwordManagerMixin,\n emailVerificationMixin,\n validationTrackingMixin,\n} from '../mixins';\nimport {\n AutoFocusOptions,\n CustomStorage,\n DebuggerMessage,\n DebugState,\n DescopeUI,\n FlowConfig,\n FlowState,\n FlowStateUpdateFn,\n FlowStatus,\n ProjectConfiguration,\n SdkConfig,\n} from '../types';\n\n// this is replaced in build time\ndeclare const BUILD_VERSION: string;\n\nconst BaseClass = compose(\n themeMixin,\n staticResourcesMixin,\n formMountMixin,\n componentConditionsMixin,\n duplicateFlowWarningMixin,\n passwordManagerMixin,\n emailVerificationMixin,\n injectStyleMixin,\n telemetryMixin,\n validationTrackingMixin,\n)(HTMLElement);\n\n// this base class is responsible for WC initialization\nclass BaseDescopeWc extends BaseClass {\n static get observedAttributes() {\n return [\n 'project-id',\n 'flow-id',\n 'base-url',\n 'tenant',\n 'locale',\n 'debug',\n 'storage-prefix',\n 'preview',\n 'redirect-url',\n 'auto-focus',\n 'store-last-authenticated-user',\n 'refresh-cookie-name',\n 'keep-last-authenticated-user-after-logout',\n 'validate-on-blur',\n 'send-session-token',\n 'style-id',\n ];\n }\n\n sdkVersion = BUILD_VERSION;\n\n // this is a way for extending the sdk config from outside\n static sdkConfigOverrides: Partial<SdkConfig> = {\n baseHeaders: {\n 'x-descope-sdk-name': 'web-component',\n 'x-descope-sdk-version': BUILD_VERSION,\n },\n };\n\n #init = false;\n\n #customStorage: CustomStorage | undefined;\n\n flowStatus: FlowStatus = 'initial';\n\n loggerWrapper = {\n error: (message: string, description = '') => {\n this.logger.error(message, description, new Error());\n this.#updateDebuggerMessages(message, description);\n },\n warn: (message: string, description = '') => {\n this.logger.warn(message, description);\n },\n info: (message: string, description = '', state: any = {}) => {\n this.logger.info(message, description, state);\n },\n debug: (message: string, description = '') => {\n this.logger.debug(message, description);\n },\n };\n\n #flowState = new State<FlowState>();\n\n #debugState = new State<DebugState>();\n\n #componentsContext = {};\n\n getComponentsContext = () => this.#componentsContext;\n\n nextRequestStatus = new State<{ isLoading: boolean }>({ isLoading: false });\n\n rootElement: HTMLDivElement;\n\n contentRootElement: HTMLDivElement;\n\n slotElement: HTMLSlotElement;\n\n #debuggerEle: HTMLElement & {\n updateData: (data: DebuggerMessage | DebuggerMessage[]) => void;\n };\n\n #eventsCbRefs = {\n popstate: this.#syncStateIdFromUrl.bind(this),\n componentsContext: this.#handleComponentsContext.bind(this),\n };\n\n sdk: ReturnType<typeof createSdk>;\n\n #updateExecState: FlowStateUpdateFn;\n\n descopeUI: Promise<DescopeUI>;\n\n constructor(updateExecState: FlowStateUpdateFn) {\n super();\n this.#updateExecState = updateExecState;\n\n this.#initShadowDom();\n }\n\n #loadInitStyle() {\n this.injectStyle(`\n :host {\n\t\t\twidth: 100%;\n display: block;\n\t\t}\n\n\t\t#root {\n\t\t\theight: 100%;\n display: flex;\n flex-direction: column;\n\t\t}\n\n #content-root {\n all: initial;\n transition: opacity 200ms ease-in-out;\n }\n\n\t\t#root[data-theme] {\n\t\t\tbackground-color: transparent;\n\t\t}\n\n\t\t.fade-out {\n\t\t\topacity: 0.1!important;\n\t\t}\n\n .hidden {\n display: none;\n }\n `);\n }\n\n #initShadowDom() {\n this.#loadInitStyle();\n this.slotElement = document.createElement('slot');\n this.slotElement.classList.add('hidden');\n this.rootElement.appendChild(this.slotElement);\n }\n\n get client() {\n try {\n return (JSON.parse(this.getAttribute('client')) || {}) as Record<\n string,\n any\n >;\n } catch (e) {\n return {};\n }\n }\n\n get redirectUrl() {\n return this.getAttribute('redirect-url') || undefined;\n }\n\n get debug() {\n return this.getAttribute('debug') === 'true';\n }\n\n get locale() {\n return this.getAttribute('locale') || undefined;\n }\n\n get autoFocus(): AutoFocusOptions {\n const res = this.getAttribute('auto-focus') ?? 'true';\n if (res === 'skipFirstScreen') {\n return res;\n }\n return res === 'true';\n }\n\n get validateOnBlur() {\n return this.getAttribute('validate-on-blur') === 'true';\n }\n\n get storeLastAuthenticatedUser() {\n const res = this.getAttribute('store-last-authenticated-user') ?? 'true';\n return res === 'true';\n }\n\n get refreshCookieName() {\n return this.getAttribute('refresh-cookie-name') || '';\n }\n\n get keepLastAuthenticatedUserAfterLogout() {\n const res = this.getAttribute('keep-last-authenticated-user-after-logout');\n return res === 'true';\n }\n\n get storagePrefix() {\n return this.getAttribute('storage-prefix') || '';\n }\n\n get sendSessionToken() {\n return this.getAttribute('send-session-token') === 'true';\n }\n\n get preview() {\n return !!this.getAttribute('preview');\n }\n\n get formConfig() {\n return transformFlowInputFormData(this.form);\n }\n\n get form() {\n return this.getAttribute('form');\n }\n\n get formConfigValues() {\n return extractNestedAttribute(this.formConfig, 'value');\n }\n\n get outboundAppId() {\n return this.getAttribute('outbound-app-id');\n }\n\n get outboundAppScopes() {\n try {\n const scopes = JSON.parse(this.getAttribute('outbound-app-scopes'));\n if (!scopes) return null;\n return scopes;\n } catch (err) {\n return null;\n }\n }\n\n get popupOrigin(): string | null {\n return this.getAttribute('popup-origin');\n }\n\n // grouped getter/setter for customStorage\n get customStorage(): CustomStorage | undefined {\n return this.#customStorage;\n }\n\n set customStorage(storage: CustomStorage | undefined) {\n if (storage && typeof storage.getItem !== 'function') {\n throw new Error('Custom storage must have a getItem method');\n }\n if (storage && typeof storage.setItem !== 'function') {\n throw new Error('Custom storage must have a setItem method');\n }\n if (storage && typeof storage.removeItem !== 'function') {\n throw new Error('Custom storage must have a removeItem method');\n }\n this.#customStorage = storage;\n setCustomStorage(storage);\n }\n\n #validateAttrs() {\n const optionalAttributes = [\n 'base-url',\n 'tenant',\n 'locale',\n 'debug',\n 'redirect-url',\n 'auto-focus',\n 'store-last-authenticated-user',\n 'refresh-cookie-name',\n 'keep-last-authenticated-user-after-logout',\n 'preview',\n 'storage-prefix',\n 'form',\n 'client',\n 'validate-on-blur',\n 'send-session-token',\n 'style-id',\n 'outbound-app-id',\n 'outbound-app-scopes',\n 'theme-override',\n ];\n\n BaseDescopeWc.observedAttributes.forEach((attr: string) => {\n if (!optionalAttributes.includes(attr) && !this[camelCase(attr)])\n throw Error(`${attr} cannot be empty`);\n });\n }\n\n #syncStateIdFromUrl() {\n const { stepId, executionId } = getRunIdsFromUrl(this.flowId);\n // A url without run ids has no step to go to. This happens when routers\n // (e.g. single-spa) fire popstate for our own url cleanup, and resetting\n // here would restart the running flow\n if (!executionId) return;\n this.#flowState.update({ stepId, executionId });\n }\n\n #createSdk(projectId: string, baseUrl: string) {\n if (!createSdk || typeof createSdk !== 'function') {\n this.logger.error(\n 'SDK was not loaded properly',\n createSdk,\n JSON.stringify(createSdk),\n );\n }\n const config: any = {\n // Use persist tokens options in order to add existing tokens in outgoing requests (if they exists)\n persistTokens: true,\n preview: this.preview,\n storagePrefix: this.storagePrefix,\n storeLastAuthenticatedUser: this.storeLastAuthenticatedUser,\n keepLastAuthenticatedUserAfterLogout:\n this.keepLastAuthenticatedUserAfterLogout,\n refreshCookieName: this.refreshCookieName,\n ...BaseDescopeWc.sdkConfigOverrides,\n projectId,\n baseUrl,\n };\n if (this.#customStorage) {\n config.customStorage = this.#customStorage;\n }\n\n this.sdk = createSdk(config);\n\n // Position of the `options` argument in core-js-sdk's flow calls:\n // flow.start(flowId, options, conditionInteractionId, interactionId, componentsVersion, flowVersions, input, isCustomScreen)\n // flow.next(executionId, stepId, interactionId, version, componentsVersion, input, isCustomScreen, options)\n // We rely on these positions staying fixed - core-js-sdk keeps them stable\n // for backwards compatibility, and new params are only appended at the end\n const flowOptionsArgIdx = { start: 1, next: 7 };\n\n // we are wrapping the next & start function so we can indicate the request status\n ['start', 'next'].forEach((key) => {\n const origFn = this.sdk.flow[key];\n const fnWithRetry = withRetry(origFn, 1000, 3);\n\n this.sdk.flow[key] = async (...args: Parameters<typeof origFn>) => {\n const callArgs = [...args] as Parameters<typeof origFn>;\n const optionsIdx = flowOptionsArgIdx[key];\n const options = this.#injectSessionJwt(callArgs[optionsIdx]);\n if (options !== undefined) {\n callArgs[optionsIdx] = options;\n }\n try {\n const resp = await fnWithRetry(...callArgs);\n return resp;\n } catch (e) {\n this.logger.error(`Error in sdk flow ${key} function`, e);\n // return a generic error object in case of an error\n return {\n error: {\n errorCode: FETCH_EXCEPTION_ERROR_CODE,\n errorDescription: e.toString(),\n },\n };\n }\n };\n });\n\n // While `lazy-start` is set, hold every flow start call until start() is\n // called. Wrapping the sdk fn holds all call sites at once, and sits outside\n // the wrapper above so the session JWT is read when the call is really sent.\n const startFn = this.sdk.flow.start;\n this.sdk.flow.start = async (\n ...args: Parameters<typeof startFn>\n ): ReturnType<typeof startFn> => {\n await this.#waitForStart();\n\n return startFn.apply(this.sdk.flow, args);\n };\n }\n\n // adds the current session JWT to a flow request options (opt-in via the\n // send-session-token attribute), so the flow can read its validated claims\n // through the sessionJwtClaims context key. Accepts only the flow start/next\n // options types and preserves the given type on return. The token is read\n // via the standalone helper - the wrapping SDKs (e.g. react-sdk) override\n // the inner sdk with persistTokens: false, so the instance getter is absent\n #injectSessionJwt<T extends FlowStartOptions | FlowNextOptions>(\n options?: T,\n ): T | undefined {\n if (!this.sendSessionToken) return options;\n const sessionToken = getSessionToken?.(this.storagePrefix);\n if (!sessionToken) return options;\n return { ...(options ?? {}), sessionJwt: sessionToken } as T;\n }\n\n async #onFlowChange(\n currentState: FlowState,\n _prevState: FlowState,\n isChanged: IsChanged<FlowState>,\n ) {\n const { projectId, baseUrl } = currentState;\n\n const shouldCreateSdkInstance =\n isChanged('projectId') || isChanged('baseUrl');\n\n if (shouldCreateSdkInstance) {\n if (!projectId) return;\n // Initialize the sdk when got a new project id\n this.#createSdk(projectId, baseUrl);\n }\n\n // update runtime state\n this.#updateExecState(currentState);\n }\n\n async #getIsFlowsVersionMismatch() {\n const config = await this.getConfig();\n\n return (\n 'isMissingConfig' in config &&\n config.isMissingConfig &&\n (await this.#isPrevVerConfig())\n );\n }\n\n // we are not using fetchStaticResource here\n // because we do not want to use the fallbacks mechanism\n async #isPrevVerConfig() {\n const prevVerConfigUrl = getContentUrl({\n projectId: this.projectId,\n filename: CONFIG_FILENAME,\n assetsFolder: PREV_VER_ASSETS_FOLDER,\n baseUrl: this.baseStaticUrl,\n });\n try {\n await fetchContent(prevVerConfigUrl, 'json');\n return true;\n } catch (e) {\n return false;\n }\n }\n\n getConfig = async () => (await this.config) || { isMissingConfig: true };\n\n #handleComponentsContext(e: CustomEvent) {\n this.#componentsContext = { ...this.#componentsContext, ...e.detail };\n }\n\n // Holds the flow's start call, so a host can preload a flow (config,\n // components, first screen) without creating a flow execution - e.g. a modal\n // that builds its flow ahead of being opened. `start()` is then the only way\n // that flow starts.\n get lazyStart() {\n return this.getAttribute('lazy-start') === 'true';\n }\n\n #startGate: Promise<void> | undefined;\n\n #releaseStartGate: (() => void) | undefined;\n\n // resolves immediately unless `lazy-start` is set, in which case it waits for\n // start()\n #waitForStart(): Promise<void> {\n if (!this.lazyStart) return Promise.resolve();\n\n if (!this.#startGate) {\n this.#startGate = new Promise((resolve) => {\n this.#releaseStartGate = resolve;\n });\n }\n\n return this.#startGate;\n }\n\n // Start a flow rendered with `lazy-start`. Safe to call before the flow\n // reached the held start call - it then goes through on arrival. The gate is\n // latched open rather than re-armed, so a flow restart (e.g. restart-on-error)\n // is not left waiting for another call.\n start() {\n this.#releaseStartGate?.();\n this.#startGate = Promise.resolve();\n }\n\n get isRestartOnError() {\n return this.getAttribute('restart-on-error') === 'true';\n }\n\n async getExecutionContext() {\n const config = await this.getConfig();\n return 'executionContext' in config ? config.executionContext : undefined;\n }\n\n #disableDebugger() {\n this.#debuggerEle?.remove();\n this.#debuggerEle = null;\n }\n\n async #handleDebugMode({ isDebug }) {\n if (isDebug) {\n this.#debuggerEle = document.createElement(\n 'descope-debugger',\n ) as HTMLElement & {\n updateData: (data: DebuggerMessage | DebuggerMessage[]) => void;\n };\n\n Object.assign(this.#debuggerEle.style, {\n position: 'fixed',\n top: '0',\n right: '0',\n height: '100vh',\n width: '100vw',\n pointerEvents: 'none',\n zIndex: 99999,\n });\n\n // we are importing the debugger dynamically so we won't load it when it's not needed\n await import('../debugger-wc');\n\n document.body.appendChild(this.#debuggerEle);\n } else {\n this.#disableDebugger();\n }\n }\n\n #updateDebuggerMessages(title: string, description: string) {\n if (title && this.debug)\n this.#debuggerEle?.updateData({ title, description });\n }\n\n async getProjectConfig(): Promise<ProjectConfiguration> {\n const config = await this.getConfig();\n return 'projectConfig' in config ? config.projectConfig : undefined;\n }\n\n async getFlowConfig(): Promise<FlowConfig> {\n const projectConfig = await this.getProjectConfig();\n\n const flowConfig =\n projectConfig?.flows?.[this.flowId] || ({} as FlowConfig);\n flowConfig.version ??= 0;\n return flowConfig;\n }\n\n async getTargetLocales() {\n const flowConfig = await this.getFlowConfig();\n return (flowConfig?.targetLocales || []).map((locale: string) =>\n locale.toLowerCase(),\n );\n }\n\n handleKeyPress() {\n this.logger.debug('Enable key press handler');\n // we want to simulate submit when the user presses Enter\n this.rootElement.onkeydown = (e) => {\n // we do not want to submit the form if the focus is on a link element\n const isLinkEleFocused =\n !!this.shadowRoot.activeElement?.getAttribute('href');\n const isIgnoredElementFocused = ELEMENTS_TO_IGNORE_ENTER_KEY_ON.includes(\n this.shadowRoot.activeElement?.localName ?? '',\n );\n\n if (e.key !== 'Enter' || isLinkEleFocused || isIgnoredElementFocused)\n return;\n\n e.preventDefault();\n const buttons: NodeListOf<HTMLButtonElement> =\n this.rootElement.querySelectorAll('descope-button');\n\n // in case there is a single button on the page, click on it\n if (\n buttons.length === 1 &&\n buttons[0].getAttribute('auto-submit') !== 'false'\n ) {\n buttons[0].click();\n return;\n }\n\n const autoSubmitButtons = Array.from(buttons).filter(\n (button) => button.getAttribute('auto-submit') === 'true',\n );\n if (autoSubmitButtons.length === 1) {\n autoSubmitButtons[0].click();\n return;\n }\n\n const genericButtons = Array.from(buttons).filter(\n (button) => button.getAttribute('data-type') === 'button',\n );\n\n // in case there is a single \"generic\" button on the page, click on it\n if (genericButtons.length === 1) {\n if (genericButtons[0].getAttribute('auto-submit') !== 'false') {\n genericButtons[0].click();\n }\n } else if (genericButtons.length === 0) {\n const ssoButtons = Array.from(buttons).filter(\n (button) => button.getAttribute('data-type') === 'sso',\n );\n\n // in case there is a single \"sso\" button on the page, click on it\n if (ssoButtons.length === 1) {\n if (ssoButtons[0].getAttribute('auto-submit') !== 'false') {\n ssoButtons[0].click();\n }\n }\n }\n };\n }\n\n disableKeyPressHandler() {\n this.logger.debug('Disable key press handler');\n this.rootElement.onkeydown = null;\n }\n\n async getComponentsVersion() {\n const config = await this.getConfig();\n const version =\n 'projectConfig' in config ? config.projectConfig?.componentsVersion : {};\n\n if (version) return version;\n\n this.logger.error('Did not get components version, using latest version');\n\n return 'latest';\n }\n\n static descopeUI: any;\n\n async init() {\n this.flowStatus = 'loading';\n ['ready', 'error', 'success'].forEach((status: FlowStatus) =>\n this.addEventListener(status, () => {\n this.flowStatus = status;\n }),\n );\n\n await super.init?.();\n this.#debugState.subscribe(this.#handleDebugMode.bind(this));\n this.#debugState.update({ isDebug: this.debug });\n\n this.#validateAttrs();\n\n if (await this.#getIsFlowsVersionMismatch()) {\n this.loggerWrapper.error(\n 'This SDK version does not support your flows version',\n 'Make sure to upgrade your flows to the latest version or use an older SDK version',\n );\n\n return;\n }\n\n const config = await this.getConfig();\n if ('isMissingConfig' in config && config.isMissingConfig) {\n this.loggerWrapper.error(\n 'Cannot get config file',\n 'Make sure that your projectId & flowId are correct',\n );\n\n return;\n }\n\n const {\n executionId,\n stepId,\n token,\n code,\n isPopup,\n exchangeError,\n redirectAuthCallbackUrl,\n redirectAuthBackupCallbackUri,\n redirectAuthCodeChallenge,\n redirectAuthInitiator,\n ssoQueryParams,\n } = handleUrlParams(this.flowId, this.projectId, this.loggerWrapper);\n\n // we want to update the state when user clicks on back in the browser\n window.addEventListener('popstate', this.#eventsCbRefs.popstate);\n\n // adding event to listen to events coming from components (e.g. recaptcha risk token) that want to add data to the context\n // this data will be sent to the server on the next request\n window.addEventListener(\n 'components-context',\n this.#eventsCbRefs.componentsContext,\n );\n\n this.#flowState.subscribe(this.#onFlowChange.bind(this));\n\n this.#flowState.update({\n projectId: this.projectId,\n flowId: this.flowId,\n baseUrl: this.baseUrl,\n tenant: this.tenantId,\n redirectUrl: this.redirectUrl,\n locale: this.locale,\n stepId,\n executionId,\n token,\n code,\n isPopup,\n exchangeError,\n redirectAuthCallbackUrl,\n redirectAuthBackupCallbackUri,\n redirectAuthCodeChallenge,\n redirectAuthInitiator,\n ...ssoQueryParams,\n });\n\n this.#init = true;\n }\n\n disconnectedCallback() {\n this.#flowState.unsubscribeAll();\n this.#debugState.unsubscribeAll();\n this.#disableDebugger();\n window.removeEventListener('popstate', this.#eventsCbRefs.popstate);\n window.removeEventListener(\n 'components-context',\n this.#eventsCbRefs.componentsContext,\n );\n // Forward to the composed mixin chain so each mixin's\n // disconnectedCallback (e.g. componentConditionsMixin) gets to clean up.\n // Without this, mixin disconnectedCallbacks are dead code.\n super.disconnectedCallback?.();\n }\n\n attributeChangedCallback(\n attrName: string,\n oldValue: string,\n newValue: string,\n ) {\n // Forward to the composed mixin chain first so other mixins always receive\n // the callback, regardless of the early return below.\n super.attributeChangedCallback?.(attrName, oldValue, newValue);\n\n if (!this.shadowRoot.isConnected || !this.#init) return;\n\n if (\n oldValue !== newValue &&\n BaseDescopeWc.observedAttributes.includes(attrName)\n ) {\n this.#validateAttrs();\n\n const isInitialRun = oldValue === null;\n\n this.#flowState.update(({ stepId, executionId }) => {\n let newStepId = stepId;\n let newExecutionId = executionId;\n\n // If not initial run and we got a new project/flow, we want to restart the step\n if (!isInitialRun) {\n newExecutionId = null;\n newStepId = null;\n clearRunIdsFromUrl();\n }\n\n return {\n [camelCase(attrName)]: newValue,\n stepId: newStepId,\n executionId: newExecutionId,\n };\n });\n\n this.#debugState.update({ isDebug: this.debug });\n }\n }\n}\n\nexport default BaseDescopeWc;\n"],"names":["BaseClass","compose","themeMixin","staticResourcesMixin","formMountMixin","componentConditionsMixin","duplicateFlowWarningMixin","passwordManagerMixin","emailVerificationMixin","injectStyleMixin","telemetryMixin","validationTrackingMixin","HTMLElement","BaseDescopeWc","observedAttributes","constructor","updateExecState","super","this","sdkVersion","_BaseDescopeWc_init","set","_BaseDescopeWc_customStorage","flowStatus","loggerWrapper","error","message","description","logger","Error","__classPrivateFieldGet","call","warn","info","state","debug","_BaseDescopeWc_flowState","State","_BaseDescopeWc_debugState","_BaseDescopeWc_componentsContext","getComponentsContext","nextRequestStatus","isLoading","_BaseDescopeWc_debuggerEle","_BaseDescopeWc_eventsCbRefs","popstate","_BaseDescopeWc_instances","_BaseDescopeWc_syncStateIdFromUrl","bind","componentsContext","_BaseDescopeWc_handleComponentsContext","_BaseDescopeWc_updateExecState","getConfig","config","isMissingConfig","_BaseDescopeWc_startGate","_BaseDescopeWc_releaseStartGate","__classPrivateFieldSet","_BaseDescopeWc_initShadowDom","client","JSON","parse","getAttribute","e","redirectUrl","undefined","locale","autoFocus","res","_b","validateOnBlur","storeLastAuthenticatedUser","refreshCookieName","keepLastAuthenticatedUserAfterLogout","storagePrefix","sendSessionToken","preview","formConfig","transformFlowInputFormData","form","formConfigValues","extractNestedAttribute","outboundAppId","outboundAppScopes","scopes","err","popupOrigin","customStorage","storage","getItem","setItem","removeItem","setCustomStorage","lazyStart","start","Promise","resolve","isRestartOnError","getExecutionContext","executionContext","getProjectConfig","projectConfig","getFlowConfig","flowConfig","flows","flowId","_c","version","getTargetLocales","targetLocales","map","toLowerCase","handleKeyPress","rootElement","onkeydown","isLinkEleFocused","shadowRoot","activeElement","isIgnoredElementFocused","ELEMENTS_TO_IGNORE_ENTER_KEY_ON","includes","localName","_d","key","preventDefault","buttons","querySelectorAll","length","click","autoSubmitButtons","Array","from","filter","button","genericButtons","ssoButtons","disableKeyPressHandler","getComponentsVersion","componentsVersion","init","forEach","status","addEventListener","_super","subscribe","_BaseDescopeWc_handleDebugMode","update","isDebug","_BaseDescopeWc_validateAttrs","_BaseDescopeWc_getIsFlowsVersionMismatch","executionId","stepId","token","code","isPopup","exchangeError","redirectAuthCallbackUrl","redirectAuthBackupCallbackUri","redirectAuthCodeChallenge","redirectAuthInitiator","ssoQueryParams","handleUrlParams","projectId","window","_BaseDescopeWc_onFlowChange","Object","assign","baseUrl","tenant","tenantId","disconnectedCallback","unsubscribeAll","_BaseDescopeWc_disableDebugger","removeEventListener","attributeChangedCallback","attrName","oldValue","newValue","isConnected","_a","isInitialRun","newStepId","newExecutionId","clearRunIdsFromUrl","camelCase","injectStyle","_BaseDescopeWc_loadInitStyle","slotElement","document","createElement","classList","add","appendChild","optionalAttributes","attr","getRunIdsFromUrl","_BaseDescopeWc_createSdk","createSdk","stringify","persistTokens","sdkConfigOverrides","sdk","flowOptionsArgIdx","next","origFn","flow","fnWithRetry","withRetry","args","__awaiter","callArgs","optionsIdx","options","_BaseDescopeWc_injectSessionJwt","errorCode","FETCH_EXCEPTION_ERROR_CODE","errorDescription","toString","startFn","_BaseDescopeWc_waitForStart","apply","sessionToken","getSessionToken","sessionJwt","currentState","_prevState","isChanged","_BaseDescopeWc_isPrevVerConfig","prevVerConfigUrl","getContentUrl","filename","CONFIG_FILENAME","assetsFolder","PREV_VER_ASSETS_FOLDER","baseStaticUrl","fetchContent","detail","remove","arguments","style","position","top","right","height","width","pointerEvents","zIndex","import","body","_BaseDescopeWc_updateDebuggerMessages","title","updateData","baseHeaders"],"mappings":"unDA0DA,MAAMA,GAAYC,EAChBC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EAVgBV,CAWhBW,aAGF,MAAMC,WAAsBb,GAC1B,6BAAWc,GACT,MAAO,CACL,aACA,UACA,WACA,SACA,SACA,QACA,iBACA,UACA,eACA,aACA,gCACA,sBACA,4CACA,mBACA,qBACA,WAEJ,CAiEA,WAAAC,CAAYC,GACVC,oBAhEFC,KAAAC,WAAa,QAUbC,EAAAC,IAAAH,MAAQ,GAERI,EAAAD,IAAAH,UAAA,GAEAA,KAAAK,WAAyB,UAEzBL,KAAAM,cAAgB,CACdC,MAAO,CAACC,EAAiBC,EAAc,MACrCT,KAAKU,OAAOH,MAAMC,EAASC,EAAa,IAAIE,OAC5CC,EAAAZ,eAA4Ba,KAA5Bb,KAA6BQ,EAASC,EAAY,EAEpDK,KAAM,CAACN,EAAiBC,EAAc,MACpCT,KAAKU,OAAOI,KAAKN,EAASC,EAAY,EAExCM,KAAM,CAACP,EAAiBC,EAAc,GAAIO,EAAa,CAAA,KACrDhB,KAAKU,OAAOK,KAAKP,EAASC,EAAaO,EAAM,EAE/CC,MAAO,CAACT,EAAiBC,EAAc,MACrCT,KAAKU,OAAOO,MAAMT,EAASC,EAAY,GAI3CS,EAAAf,IAAAH,KAAa,IAAImB,GAEjBC,EAAAjB,IAAAH,KAAc,IAAImB,GAElBE,EAAAlB,IAAAH,KAAqB,IAErBA,KAAAsB,qBAAuB,IAAMV,EAAAZ,YAE7BA,KAAAuB,kBAAoB,IAAIJ,EAA8B,CAAEK,WAAW,IAQnEC,EAAAtB,IAAAH,UAAA,GAIA0B,EAAAvB,IAAAH,KAAgB,CACd2B,SAAUf,EAAAZ,KAAI4B,EAAA,IAAAC,GAAqBC,KAAK9B,MACxC+B,kBAAmBnB,EAAAZ,KAA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ACrCC,SAAU,QACVC,IAAK,IACLC,MAAO,IACPC,OAAQ,QACRC,MAAO,QACPC,cAAe,OACfC,OAAQ,cAIJC,OAAO,qBAEb3D,SAAS4D,KAAKxD,YAAYlK,EAAAZ,KAAIyB,EAAA,OAE9Bb,EAAAZ,KAAI4B,EAAA,IAAA8H,IAAiB7I,KAArBb,KAEJ,GAEwB,EAAAuO,GAAA,SAAAC,EAAe/N,SACjC+N,GAASxO,KAAKiB,QACC,QAAjBkC,EAAAvC,EAAAZ,KAAIyB,EAAA,YAAa,IAAA0B,GAAAA,EAAEsL,WAAW,CAAED,QAAO/N,gBAC3C,EA5dOd,GAAA2L,mBAAyC,CAC9CoD,YAAa,CACX,qBAAsB,gBACtB,wBAAyB"}
1
+ {"version":3,"file":"BaseDescopeWc.js","sources":["../../../src/lib/descope-wc/BaseDescopeWc.ts"],"sourcesContent":["import { compose } from '@descope/sdk-helpers';\n// eslint-disable-next-line import/no-duplicates\nimport { staticResourcesMixin } from '@descope/sdk-mixins/static-resources-mixin';\n// eslint-disable-next-line import/no-duplicates\nimport { themeMixin } from '@descope/sdk-mixins/theme-mixin';\n// eslint-disable-next-line import/no-duplicates\nimport { injectStyleMixin } from '@descope/sdk-mixins/inject-style-mixin';\n// eslint-disable-next-line import/no-duplicates\nimport { telemetryMixin } from '@descope/sdk-mixins/telemetry-mixin';\nimport { createSdk, getSessionToken } from '@descope/web-js-sdk';\nimport type { FlowNextOptions, FlowStartOptions } from '@descope/web-js-sdk';\nimport {\n CONFIG_FILENAME,\n ELEMENTS_TO_IGNORE_ENTER_KEY_ON,\n FETCH_EXCEPTION_ERROR_CODE,\n PREV_VER_ASSETS_FOLDER,\n} from '../constants';\nimport {\n camelCase,\n clearRunIdsFromUrl,\n fetchContent,\n getContentUrl,\n getRunIdsFromUrl,\n handleUrlParams,\n State,\n withRetry,\n} from '../helpers';\nimport {\n extractNestedAttribute,\n transformFlowInputFormData,\n} from '../helpers/flowInputs';\nimport { setCustomStorage } from '../helpers/storage';\nimport { IsChanged } from '../helpers/state';\nimport {\n formMountMixin,\n componentConditionsMixin,\n duplicateFlowWarningMixin,\n passwordManagerMixin,\n emailVerificationMixin,\n validationTrackingMixin,\n} from '../mixins';\nimport {\n AutoFocusOptions,\n CustomStorage,\n DebuggerMessage,\n DebugState,\n DescopeUI,\n FlowConfig,\n FlowState,\n FlowStateUpdateFn,\n FlowStatus,\n ProjectConfiguration,\n SdkConfig,\n SSOQueryParams,\n} from '../types';\n\n// this is replaced in build time\ndeclare const BUILD_VERSION: string;\n\nconst BaseClass = compose(\n themeMixin,\n staticResourcesMixin,\n formMountMixin,\n componentConditionsMixin,\n duplicateFlowWarningMixin,\n passwordManagerMixin,\n emailVerificationMixin,\n injectStyleMixin,\n telemetryMixin,\n validationTrackingMixin,\n)(HTMLElement);\n\n// this base class is responsible for WC initialization\nclass BaseDescopeWc extends BaseClass {\n static get observedAttributes() {\n return [\n 'project-id',\n 'flow-id',\n 'base-url',\n 'tenant',\n 'locale',\n 'debug',\n 'storage-prefix',\n 'preview',\n 'redirect-url',\n 'auto-focus',\n 'store-last-authenticated-user',\n 'refresh-cookie-name',\n 'keep-last-authenticated-user-after-logout',\n 'validate-on-blur',\n 'send-session-token',\n 'style-id',\n ];\n }\n\n sdkVersion = BUILD_VERSION;\n\n // this is a way for extending the sdk config from outside\n static sdkConfigOverrides: Partial<SdkConfig> = {\n baseHeaders: {\n 'x-descope-sdk-name': 'web-component',\n 'x-descope-sdk-version': BUILD_VERSION,\n },\n };\n\n #init = false;\n\n #customStorage: CustomStorage | undefined;\n\n // The OIDC context this page copied from the run its URL continues (see\n // handleUrlParams). Kept out of flow state, so this page renders and calls\n // `next` exactly as before. Only a flow restart reads it.\n #adoptedSsoQueryParams: Partial<SSOQueryParams> | null = null;\n\n protected get adoptedSsoQueryParams() {\n return this.#adoptedSsoQueryParams;\n }\n\n flowStatus: FlowStatus = 'initial';\n\n loggerWrapper = {\n error: (message: string, description = '') => {\n this.logger.error(message, description, new Error());\n this.#updateDebuggerMessages(message, description);\n },\n warn: (message: string, description = '') => {\n this.logger.warn(message, description);\n },\n info: (message: string, description = '', state: any = {}) => {\n this.logger.info(message, description, state);\n },\n debug: (message: string, description = '') => {\n this.logger.debug(message, description);\n },\n };\n\n #flowState = new State<FlowState>();\n\n #debugState = new State<DebugState>();\n\n #componentsContext = {};\n\n getComponentsContext = () => this.#componentsContext;\n\n nextRequestStatus = new State<{ isLoading: boolean }>({ isLoading: false });\n\n rootElement: HTMLDivElement;\n\n contentRootElement: HTMLDivElement;\n\n slotElement: HTMLSlotElement;\n\n #debuggerEle: HTMLElement & {\n updateData: (data: DebuggerMessage | DebuggerMessage[]) => void;\n };\n\n #eventsCbRefs = {\n popstate: this.#syncStateIdFromUrl.bind(this),\n componentsContext: this.#handleComponentsContext.bind(this),\n };\n\n sdk: ReturnType<typeof createSdk>;\n\n #updateExecState: FlowStateUpdateFn;\n\n descopeUI: Promise<DescopeUI>;\n\n constructor(updateExecState: FlowStateUpdateFn) {\n super();\n this.#updateExecState = updateExecState;\n\n this.#initShadowDom();\n }\n\n #loadInitStyle() {\n this.injectStyle(`\n :host {\n\t\t\twidth: 100%;\n display: block;\n\t\t}\n\n\t\t#root {\n\t\t\theight: 100%;\n display: flex;\n flex-direction: column;\n\t\t}\n\n #content-root {\n all: initial;\n transition: opacity 200ms ease-in-out;\n }\n\n\t\t#root[data-theme] {\n\t\t\tbackground-color: transparent;\n\t\t}\n\n\t\t.fade-out {\n\t\t\topacity: 0.1!important;\n\t\t}\n\n .hidden {\n display: none;\n }\n `);\n }\n\n #initShadowDom() {\n this.#loadInitStyle();\n this.slotElement = document.createElement('slot');\n this.slotElement.classList.add('hidden');\n this.rootElement.appendChild(this.slotElement);\n }\n\n get client() {\n try {\n return (JSON.parse(this.getAttribute('client')) || {}) as Record<\n string,\n any\n >;\n } catch (e) {\n return {};\n }\n }\n\n get redirectUrl() {\n return this.getAttribute('redirect-url') || undefined;\n }\n\n get debug() {\n return this.getAttribute('debug') === 'true';\n }\n\n get locale() {\n return this.getAttribute('locale') || undefined;\n }\n\n get autoFocus(): AutoFocusOptions {\n const res = this.getAttribute('auto-focus') ?? 'true';\n if (res === 'skipFirstScreen') {\n return res;\n }\n return res === 'true';\n }\n\n get validateOnBlur() {\n return this.getAttribute('validate-on-blur') === 'true';\n }\n\n get storeLastAuthenticatedUser() {\n const res = this.getAttribute('store-last-authenticated-user') ?? 'true';\n return res === 'true';\n }\n\n get refreshCookieName() {\n return this.getAttribute('refresh-cookie-name') || '';\n }\n\n get keepLastAuthenticatedUserAfterLogout() {\n const res = this.getAttribute('keep-last-authenticated-user-after-logout');\n return res === 'true';\n }\n\n get storagePrefix() {\n return this.getAttribute('storage-prefix') || '';\n }\n\n get sendSessionToken() {\n return this.getAttribute('send-session-token') === 'true';\n }\n\n get preview() {\n return !!this.getAttribute('preview');\n }\n\n get formConfig() {\n return transformFlowInputFormData(this.form);\n }\n\n get form() {\n return this.getAttribute('form');\n }\n\n get formConfigValues() {\n return extractNestedAttribute(this.formConfig, 'value');\n }\n\n get outboundAppId() {\n return this.getAttribute('outbound-app-id');\n }\n\n get outboundAppScopes() {\n try {\n const scopes = JSON.parse(this.getAttribute('outbound-app-scopes'));\n if (!scopes) return null;\n return scopes;\n } catch (err) {\n return null;\n }\n }\n\n get popupOrigin(): string | null {\n return this.getAttribute('popup-origin');\n }\n\n // grouped getter/setter for customStorage\n get customStorage(): CustomStorage | undefined {\n return this.#customStorage;\n }\n\n set customStorage(storage: CustomStorage | undefined) {\n if (storage && typeof storage.getItem !== 'function') {\n throw new Error('Custom storage must have a getItem method');\n }\n if (storage && typeof storage.setItem !== 'function') {\n throw new Error('Custom storage must have a setItem method');\n }\n if (storage && typeof storage.removeItem !== 'function') {\n throw new Error('Custom storage must have a removeItem method');\n }\n this.#customStorage = storage;\n setCustomStorage(storage);\n }\n\n #validateAttrs() {\n const optionalAttributes = [\n 'base-url',\n 'tenant',\n 'locale',\n 'debug',\n 'redirect-url',\n 'auto-focus',\n 'store-last-authenticated-user',\n 'refresh-cookie-name',\n 'keep-last-authenticated-user-after-logout',\n 'preview',\n 'storage-prefix',\n 'form',\n 'client',\n 'validate-on-blur',\n 'send-session-token',\n 'style-id',\n 'outbound-app-id',\n 'outbound-app-scopes',\n 'theme-override',\n ];\n\n BaseDescopeWc.observedAttributes.forEach((attr: string) => {\n if (!optionalAttributes.includes(attr) && !this[camelCase(attr)])\n throw Error(`${attr} cannot be empty`);\n });\n }\n\n #syncStateIdFromUrl() {\n const { stepId, executionId } = getRunIdsFromUrl(this.flowId);\n // A url without run ids has no step to go to. This happens when routers\n // (e.g. single-spa) fire popstate for our own url cleanup, and resetting\n // here would restart the running flow\n if (!executionId) return;\n this.#flowState.update({ stepId, executionId });\n }\n\n #createSdk(projectId: string, baseUrl: string) {\n if (!createSdk || typeof createSdk !== 'function') {\n this.logger.error(\n 'SDK was not loaded properly',\n createSdk,\n JSON.stringify(createSdk),\n );\n }\n const config: any = {\n // Use persist tokens options in order to add existing tokens in outgoing requests (if they exists)\n persistTokens: true,\n preview: this.preview,\n storagePrefix: this.storagePrefix,\n storeLastAuthenticatedUser: this.storeLastAuthenticatedUser,\n keepLastAuthenticatedUserAfterLogout:\n this.keepLastAuthenticatedUserAfterLogout,\n refreshCookieName: this.refreshCookieName,\n ...BaseDescopeWc.sdkConfigOverrides,\n projectId,\n baseUrl,\n };\n if (this.#customStorage) {\n config.customStorage = this.#customStorage;\n }\n\n this.sdk = createSdk(config);\n\n // Position of the `options` argument in core-js-sdk's flow calls:\n // flow.start(flowId, options, conditionInteractionId, interactionId, componentsVersion, flowVersions, input, isCustomScreen)\n // flow.next(executionId, stepId, interactionId, version, componentsVersion, input, isCustomScreen, options)\n // We rely on these positions staying fixed - core-js-sdk keeps them stable\n // for backwards compatibility, and new params are only appended at the end\n const flowOptionsArgIdx = { start: 1, next: 7 };\n\n // we are wrapping the next & start function so we can indicate the request status\n ['start', 'next'].forEach((key) => {\n const origFn = this.sdk.flow[key];\n const fnWithRetry = withRetry(origFn, 1000, 3);\n\n this.sdk.flow[key] = async (...args: Parameters<typeof origFn>) => {\n const callArgs = [...args] as Parameters<typeof origFn>;\n const optionsIdx = flowOptionsArgIdx[key];\n const options = this.#injectSessionJwt(callArgs[optionsIdx]);\n if (options !== undefined) {\n callArgs[optionsIdx] = options;\n }\n try {\n const resp = await fnWithRetry(...callArgs);\n return resp;\n } catch (e) {\n this.logger.error(`Error in sdk flow ${key} function`, e);\n // return a generic error object in case of an error\n return {\n error: {\n errorCode: FETCH_EXCEPTION_ERROR_CODE,\n errorDescription: e.toString(),\n },\n };\n }\n };\n });\n\n // While `lazy-start` is set, hold every flow start call until start() is\n // called. Wrapping the sdk fn holds all call sites at once, and sits outside\n // the wrapper above so the session JWT is read when the call is really sent.\n const startFn = this.sdk.flow.start;\n this.sdk.flow.start = async (\n ...args: Parameters<typeof startFn>\n ): ReturnType<typeof startFn> => {\n await this.#waitForStart();\n\n return startFn.apply(this.sdk.flow, args);\n };\n }\n\n // adds the current session JWT to a flow request options (opt-in via the\n // send-session-token attribute), so the flow can read its validated claims\n // through the sessionJwtClaims context key. Accepts only the flow start/next\n // options types and preserves the given type on return. The token is read\n // via the standalone helper - the wrapping SDKs (e.g. react-sdk) override\n // the inner sdk with persistTokens: false, so the instance getter is absent\n #injectSessionJwt<T extends FlowStartOptions | FlowNextOptions>(\n options?: T,\n ): T | undefined {\n if (!this.sendSessionToken) return options;\n const sessionToken = getSessionToken?.(this.storagePrefix);\n if (!sessionToken) return options;\n return { ...(options ?? {}), sessionJwt: sessionToken } as T;\n }\n\n async #onFlowChange(\n currentState: FlowState,\n _prevState: FlowState,\n isChanged: IsChanged<FlowState>,\n ) {\n const { projectId, baseUrl } = currentState;\n\n const shouldCreateSdkInstance =\n isChanged('projectId') || isChanged('baseUrl');\n\n if (shouldCreateSdkInstance) {\n if (!projectId) return;\n // Initialize the sdk when got a new project id\n this.#createSdk(projectId, baseUrl);\n }\n\n // update runtime state\n this.#updateExecState(currentState);\n }\n\n async #getIsFlowsVersionMismatch() {\n const config = await this.getConfig();\n\n return (\n 'isMissingConfig' in config &&\n config.isMissingConfig &&\n (await this.#isPrevVerConfig())\n );\n }\n\n // we are not using fetchStaticResource here\n // because we do not want to use the fallbacks mechanism\n async #isPrevVerConfig() {\n const prevVerConfigUrl = getContentUrl({\n projectId: this.projectId,\n filename: CONFIG_FILENAME,\n assetsFolder: PREV_VER_ASSETS_FOLDER,\n baseUrl: this.baseStaticUrl,\n });\n try {\n await fetchContent(prevVerConfigUrl, 'json');\n return true;\n } catch (e) {\n return false;\n }\n }\n\n getConfig = async () => (await this.config) || { isMissingConfig: true };\n\n #handleComponentsContext(e: CustomEvent) {\n this.#componentsContext = { ...this.#componentsContext, ...e.detail };\n }\n\n // Holds the flow's start call, so a host can preload a flow (config,\n // components, first screen) without creating a flow execution - e.g. a modal\n // that builds its flow ahead of being opened. `start()` is then the only way\n // that flow starts.\n get lazyStart() {\n return this.getAttribute('lazy-start') === 'true';\n }\n\n #startGate: Promise<void> | undefined;\n\n #releaseStartGate: (() => void) | undefined;\n\n // resolves immediately unless `lazy-start` is set, in which case it waits for\n // start()\n #waitForStart(): Promise<void> {\n if (!this.lazyStart) return Promise.resolve();\n\n if (!this.#startGate) {\n this.#startGate = new Promise((resolve) => {\n this.#releaseStartGate = resolve;\n });\n }\n\n return this.#startGate;\n }\n\n // Start a flow rendered with `lazy-start`. Safe to call before the flow\n // reached the held start call - it then goes through on arrival. The gate is\n // latched open rather than re-armed, so a flow restart (e.g. restart-on-error)\n // is not left waiting for another call.\n start() {\n this.#releaseStartGate?.();\n this.#startGate = Promise.resolve();\n }\n\n get isRestartOnError() {\n return this.getAttribute('restart-on-error') === 'true';\n }\n\n async getExecutionContext() {\n const config = await this.getConfig();\n return 'executionContext' in config ? config.executionContext : undefined;\n }\n\n #disableDebugger() {\n this.#debuggerEle?.remove();\n this.#debuggerEle = null;\n }\n\n async #handleDebugMode({ isDebug }) {\n if (isDebug) {\n this.#debuggerEle = document.createElement(\n 'descope-debugger',\n ) as HTMLElement & {\n updateData: (data: DebuggerMessage | DebuggerMessage[]) => void;\n };\n\n Object.assign(this.#debuggerEle.style, {\n position: 'fixed',\n top: '0',\n right: '0',\n height: '100vh',\n width: '100vw',\n pointerEvents: 'none',\n zIndex: 99999,\n });\n\n // we are importing the debugger dynamically so we won't load it when it's not needed\n await import('../debugger-wc');\n\n document.body.appendChild(this.#debuggerEle);\n } else {\n this.#disableDebugger();\n }\n }\n\n #updateDebuggerMessages(title: string, description: string) {\n if (title && this.debug)\n this.#debuggerEle?.updateData({ title, description });\n }\n\n async getProjectConfig(): Promise<ProjectConfiguration> {\n const config = await this.getConfig();\n return 'projectConfig' in config ? config.projectConfig : undefined;\n }\n\n async getFlowConfig(): Promise<FlowConfig> {\n const projectConfig = await this.getProjectConfig();\n\n const flowConfig =\n projectConfig?.flows?.[this.flowId] || ({} as FlowConfig);\n flowConfig.version ??= 0;\n return flowConfig;\n }\n\n async getTargetLocales() {\n const flowConfig = await this.getFlowConfig();\n return (flowConfig?.targetLocales || []).map((locale: string) =>\n locale.toLowerCase(),\n );\n }\n\n handleKeyPress() {\n this.logger.debug('Enable key press handler');\n // we want to simulate submit when the user presses Enter\n this.rootElement.onkeydown = (e) => {\n // we do not want to submit the form if the focus is on a link element\n const isLinkEleFocused =\n !!this.shadowRoot.activeElement?.getAttribute('href');\n const isIgnoredElementFocused = ELEMENTS_TO_IGNORE_ENTER_KEY_ON.includes(\n this.shadowRoot.activeElement?.localName ?? '',\n );\n\n if (e.key !== 'Enter' || isLinkEleFocused || isIgnoredElementFocused)\n return;\n\n e.preventDefault();\n const buttons: NodeListOf<HTMLButtonElement> =\n this.rootElement.querySelectorAll('descope-button');\n\n // in case there is a single button on the page, click on it\n if (\n buttons.length === 1 &&\n buttons[0].getAttribute('auto-submit') !== 'false'\n ) {\n buttons[0].click();\n return;\n }\n\n const autoSubmitButtons = Array.from(buttons).filter(\n (button) => button.getAttribute('auto-submit') === 'true',\n );\n if (autoSubmitButtons.length === 1) {\n autoSubmitButtons[0].click();\n return;\n }\n\n const genericButtons = Array.from(buttons).filter(\n (button) => button.getAttribute('data-type') === 'button',\n );\n\n // in case there is a single \"generic\" button on the page, click on it\n if (genericButtons.length === 1) {\n if (genericButtons[0].getAttribute('auto-submit') !== 'false') {\n genericButtons[0].click();\n }\n } else if (genericButtons.length === 0) {\n const ssoButtons = Array.from(buttons).filter(\n (button) => button.getAttribute('data-type') === 'sso',\n );\n\n // in case there is a single \"sso\" button on the page, click on it\n if (ssoButtons.length === 1) {\n if (ssoButtons[0].getAttribute('auto-submit') !== 'false') {\n ssoButtons[0].click();\n }\n }\n }\n };\n }\n\n disableKeyPressHandler() {\n this.logger.debug('Disable key press handler');\n this.rootElement.onkeydown = null;\n }\n\n async getComponentsVersion() {\n const config = await this.getConfig();\n const version =\n 'projectConfig' in config ? config.projectConfig?.componentsVersion : {};\n\n if (version) return version;\n\n this.logger.error('Did not get components version, using latest version');\n\n return 'latest';\n }\n\n static descopeUI: any;\n\n async init() {\n this.flowStatus = 'loading';\n ['ready', 'error', 'success'].forEach((status: FlowStatus) =>\n this.addEventListener(status, () => {\n this.flowStatus = status;\n }),\n );\n\n await super.init?.();\n this.#debugState.subscribe(this.#handleDebugMode.bind(this));\n this.#debugState.update({ isDebug: this.debug });\n\n this.#validateAttrs();\n\n if (await this.#getIsFlowsVersionMismatch()) {\n this.loggerWrapper.error(\n 'This SDK version does not support your flows version',\n 'Make sure to upgrade your flows to the latest version or use an older SDK version',\n );\n\n return;\n }\n\n const config = await this.getConfig();\n if ('isMissingConfig' in config && config.isMissingConfig) {\n this.loggerWrapper.error(\n 'Cannot get config file',\n 'Make sure that your projectId & flowId are correct',\n );\n\n return;\n }\n\n const {\n executionId,\n stepId,\n token,\n code,\n isPopup,\n exchangeError,\n redirectAuthCallbackUrl,\n redirectAuthBackupCallbackUri,\n redirectAuthCodeChallenge,\n redirectAuthInitiator,\n ssoQueryParams,\n adoptedSsoQueryParams,\n } = handleUrlParams(this.flowId, this.projectId, this.loggerWrapper);\n this.#adoptedSsoQueryParams = adoptedSsoQueryParams ?? null;\n\n // we want to update the state when user clicks on back in the browser\n window.addEventListener('popstate', this.#eventsCbRefs.popstate);\n\n // adding event to listen to events coming from components (e.g. recaptcha risk token) that want to add data to the context\n // this data will be sent to the server on the next request\n window.addEventListener(\n 'components-context',\n this.#eventsCbRefs.componentsContext,\n );\n\n this.#flowState.subscribe(this.#onFlowChange.bind(this));\n\n this.#flowState.update({\n projectId: this.projectId,\n flowId: this.flowId,\n baseUrl: this.baseUrl,\n tenant: this.tenantId,\n redirectUrl: this.redirectUrl,\n locale: this.locale,\n stepId,\n executionId,\n token,\n code,\n isPopup,\n exchangeError,\n redirectAuthCallbackUrl,\n redirectAuthBackupCallbackUri,\n redirectAuthCodeChallenge,\n redirectAuthInitiator,\n ...ssoQueryParams,\n });\n\n this.#init = true;\n }\n\n disconnectedCallback() {\n this.#flowState.unsubscribeAll();\n this.#debugState.unsubscribeAll();\n this.#disableDebugger();\n window.removeEventListener('popstate', this.#eventsCbRefs.popstate);\n window.removeEventListener(\n 'components-context',\n this.#eventsCbRefs.componentsContext,\n );\n // Forward to the composed mixin chain so each mixin's\n // disconnectedCallback (e.g. componentConditionsMixin) gets to clean up.\n // Without this, mixin disconnectedCallbacks are dead code.\n super.disconnectedCallback?.();\n }\n\n attributeChangedCallback(\n attrName: string,\n oldValue: string,\n newValue: string,\n ) {\n // Forward to the composed mixin chain first so other mixins always receive\n // the callback, regardless of the early return below.\n super.attributeChangedCallback?.(attrName, oldValue, newValue);\n\n if (!this.shadowRoot.isConnected || !this.#init) return;\n\n if (\n oldValue !== newValue &&\n BaseDescopeWc.observedAttributes.includes(attrName)\n ) {\n this.#validateAttrs();\n\n const isInitialRun = oldValue === null;\n\n this.#flowState.update(({ stepId, executionId }) => {\n let newStepId = stepId;\n let newExecutionId = executionId;\n\n // If not initial run and we got a new project/flow, we want to restart the step\n if (!isInitialRun) {\n newExecutionId = null;\n newStepId = null;\n clearRunIdsFromUrl();\n }\n\n return {\n [camelCase(attrName)]: newValue,\n stepId: newStepId,\n executionId: newExecutionId,\n };\n });\n\n this.#debugState.update({ isDebug: this.debug });\n }\n }\n}\n\nexport default BaseDescopeWc;\n"],"names":["BaseClass","compose","themeMixin","staticResourcesMixin","formMountMixin","componentConditionsMixin","duplicateFlowWarningMixin","passwordManagerMixin","emailVerificationMixin","injectStyleMixin","telemetryMixin","validationTrackingMixin","HTMLElement","BaseDescopeWc","observedAttributes","adoptedSsoQueryParams","__classPrivateFieldGet","this","_BaseDescopeWc_adoptedSsoQueryParams","constructor","updateExecState","super","sdkVersion","_BaseDescopeWc_init","set","_BaseDescopeWc_customStorage","flowStatus","loggerWrapper","error","message","description","logger","Error","call","warn","info","state","debug","_BaseDescopeWc_flowState","State","_BaseDescopeWc_debugState","_BaseDescopeWc_componentsContext","getComponentsContext","nextRequestStatus","isLoading","_BaseDescopeWc_debuggerEle","_BaseDescopeWc_eventsCbRefs","popstate","_BaseDescopeWc_instances","_BaseDescopeWc_syncStateIdFromUrl","bind","componentsContext","_BaseDescopeWc_handleComponentsContext","_BaseDescopeWc_updateExecState","getConfig","config","isMissingConfig","_BaseDescopeWc_startGate","_BaseDescopeWc_releaseStartGate","__classPrivateFieldSet","_BaseDescopeWc_initShadowDom","client","JSON","parse","getAttribute","e","redirectUrl","undefined","locale","autoFocus","res","_b","validateOnBlur","storeLastAuthenticatedUser","refreshCookieName","keepLastAuthenticatedUserAfterLogout","storagePrefix","sendSessionToken","preview","formConfig","transformFlowInputFormData","form","formConfigValues","extractNestedAttribute","outboundAppId","outboundAppScopes","scopes","err","popupOrigin","customStorage","storage","getItem","setItem","removeItem","setCustomStorage","lazyStart","start","Promise","resolve","isRestartOnError","getExecutionContext","executionContext","getProjectConfig","projectConfig","getFlowConfig","flowConfig","flows","flowId","_c","version","getTargetLocales","targetLocales","map","toLowerCase","handleKeyPress","rootElement","onkeydown","isLinkEleFocused","shadowRoot","activeElement","isIgnoredElementFocused","ELEMENTS_TO_IGNORE_ENTER_KEY_ON","includes","localName","_d","key","preventDefault","buttons","querySelectorAll","length","click","autoSubmitButtons","Array","from","filter","button","genericButtons","ssoButtons","disableKeyPressHandler","getComponentsVersion","componentsVersion","init","forEach","status","addEventListener","_super","subscribe","_BaseDescopeWc_handleDebugMode","update","isDebug","_BaseDescopeWc_validateAttrs","_BaseDescopeWc_getIsFlowsVersionMismatch","executionId","stepId","token","code","isPopup","exchangeError","redirectAuthCallbackUrl","redirectAuthBackupCallbackUri","redirectAuthCodeChallenge","redirectAuthInitiator","ssoQueryParams","handleUrlParams","projectId","window","_BaseDescopeWc_onFlowChange","Object","assign","baseUrl","tenant","tenantId","disconnectedCallback","unsubscribeAll","_BaseDescopeWc_disableDebugger","removeEventListener","attributeChangedCallback","attrName","oldValue","newValue","isConnected","_a","isInitialRun","newStepId","newExecutionId","clearRunIdsFromUrl","camelCase","injectStyle","_BaseDescopeWc_loadInitStyle","slotElement","document","createElement","classList","add","appendChild","optionalAttributes","attr","getRunIdsFromUrl","_BaseDescopeWc_createSdk","createSdk","stringify","persistTokens","sdkConfigOverrides","sdk","flowOptionsArgIdx","next","origFn","flow","fnWithRetry","withRetry","args","__awaiter","callArgs","optionsIdx","options","_BaseDescopeWc_injectSessionJwt","errorCode","FETCH_EXCEPTION_ERROR_CODE","errorDescription","toString","startFn","_BaseDescopeWc_waitForStart","apply","sessionToken","getSessionToken","sessionJwt","currentState","_prevState","isChanged","_BaseDescopeWc_isPrevVerConfig","prevVerConfigUrl","getContentUrl","filename","CONFIG_FILENAME","assetsFolder","PREV_VER_ASSETS_FOLDER","baseStaticUrl","fetchContent","detail","remove","arguments","style","position","top","right","height","width","pointerEvents","zIndex","import","body","_BaseDescopeWc_updateDebuggerMessages","title","updateData","baseHeaders"],"mappings":"0nDA2DA,MAAMA,GAAYC,EAChBC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EAVgBV,CAWhBW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OAAQ,QACRC,MAAO,QACPC,cAAe,OACfC,OAAQ,cAIJC,OAAO,qBAEb3D,SAAS4D,KAAKxD,YAAYlL,EAAAC,KAAI4B,EAAA,OAE9B7B,EAAAC,KAAI+B,EAAA,IAAA8H,IAAiB7I,KAArBhB,KAEJ,GAEwB,EAAA0O,GAAA,SAAAC,EAAe9N,SACjC8N,GAAS3O,KAAKoB,QACC,QAAjBkC,EAAAvD,EAAAC,KAAI4B,EAAA,YAAa,IAAA0B,GAAAA,EAAEsL,WAAW,CAAED,QAAO9N,gBAC3C,EAreOjB,GAAA6L,mBAAyC,CAC9CoD,YAAa,CACX,qBAAsB,gBACtB,wBAAyB"}
@@ -1,2 +1,2 @@
1
- import{__classPrivateFieldGet as e,__classPrivateFieldSet as t,__awaiter as i,__rest as s}from"tslib";import{getUserLocale as o}from"@descope/sdk-helpers";import{ensureFingerprintIds as n,clearFingerprintData as r}from"@descope/web-js-sdk";import{RESPONSE_ACTIONS as l,CUSTOM_INTERACTIONS as a,URL_CODE_PARAM_NAME as d,URL_ERR_PARAM_NAME as c,URL_TOKEN_PARAM_NAME as p,URL_RUN_IDS_PARAM_NAME as h,SDK_SCRIPTS_LOAD_TIMEOUT as u,DESCOPE_ATTRIBUTE_EXCLUDE_FIELD as g,ELEMENT_TYPE_ATTRIBUTE as v,WEBAUTHN_TIMEOUT as m,DESCOPE_ATTRIBUTE_OPT_IN_LAST_USED as f,DESCOPE_LAST_AUTH_BADGE_COMPONENT as b,DESCOPE_ATTRIBUTE_EXCLUDE_NEXT_BUTTON as w}from"../constants/index.js";import{timeoutPromise as S,withMemCache as y,leadingDebounce as I,showFirstScreenOnExecutionInit as k,injectSamlIdpForm as R,injectWsFedIdpForm as W,openCenteredPopup as C,getAnimationDirection as x,getScriptResultPath as E,transformScreenInputs as O,handleReportValidityOnBlur as A,handleAutoFocus as j,getElementDescopeAttributes as T,submitForm as U,transformStepStateForCustomScreen as L,clearPreviousExternalInputs as P,getTrustedPopupOpenerOrigin as F}from"../helpers/helpers.js";import N from"../helpers/state.js";import{disableWebauthnButtons as $,updateTemplateFromScreenState as V,setComponentsAutoDetectByGeo as M,setComponentsAutoDetectByLocale as q,setTOTPVariable as D,setNOTPVariable as B,setCssVars as _,updateScreenFromScreenState as K,replaceElementMessage as H}from"../helpers/templates.js";import{isConditionalLoginSupported as G}from"../helpers/webauthn.js";import{clearSsoQueryParams as J}from"../helpers/oidcSession.js";import{getABTestingKey as z}from"../helpers/abTestingKey.js";import{calculateConditions as Q,calculateCondition as X}from"../helpers/conditions.js";import{setLastAuth as Y,getInFlightLastUsedPerScreen as Z,clearInFlightLastAuth as ee,getLastAuth as te,updateLastUsedPerScreen as ie}from"../helpers/lastAuth.js";import{isHiddenByCondition as se}from"../helpers/realtime-conditions/applier.js";import oe from"./BaseDescopeWc.js";import{FETCH_EXCEPTION_ERROR_CODE as ne,FLOW_TIMED_OUT_ERROR_CODE as re,POLLING_STATUS_NOT_FOUND_ERROR_CODE as le,NONCE_VALIDATION_ERROR_CODE as ae,FETCH_ERROR_RESPONSE_ERROR_CODE as de,FLOW_REQUESTED_IS_IN_OLD_VERSION_ERROR_CODE as ce}from"../constants/general.js";var pe,he,ue,ge,ve,me,fe,be,we,Se,ye,Ie,ke,Re,We,Ce,xe,Ee,Oe,Ae,je,Te,Ue,Le,Pe,Fe,Ne,$e,Ve,Me,qe,De,Be,_e,Ke,He,Ge,Je,ze,Qe,Xe,Ye,Ze,et,tt,it;const st="__descope_webauthn_timed_out__";class ot extends oe{static set sdkConfigOverrides(e){oe.sdkConfigOverrides=e}static get sdkConfigOverrides(){return oe.sdkConfigOverrides}constructor(){const s=new N({deferredRedirect:!1,deferredPolling:!1});super(s.update.bind(s)),pe.add(this),this.stepState=new N({}),he.set(this,void 0),ue.set(this,null),ge.set(this,null),ve.set(this,{visibilitychange:e(this,pe,"m",me).bind(this)}),this.bridgeVersion=ot.bridgeVersion,fe.set(this,void 0),this.nativeCallbacks={},We.set(this,!1),this.handleRedirect=e=>{window.location.assign(e)},Ee.set(this,(t=>{t&&this.clearEmailVerification();const i=()=>{this.contentRootElement.classList.toggle("hidden",t),this.slotElement.classList.toggle("hidden",!t),t&&(this.contentRootElement.innerHTML="")};t&&this.contentRootElement.hasChildNodes()?e(this,pe,"m",Oe).call(this,i):i()})),Ae.set(this,((s,o,n,r,d=!1)=>{const c=[re,le,ae];if(this.flowState.current.action===l.poll){if(e(this,Te,"f").call(this)&&document.hidden)return this.logger.debug("polling - Deferring polling until in foreground"),void this.flowState.update({deferredPolling:!0});this.logger.debug("polling - Scheduling polling request");const l=Date.now(),p=d?500:2e3;t(this,he,setTimeout((()=>i(this,void 0,void 0,(function*(){var t,i;this.logger.debug("polling - Calling next");const h=this.sdk.flow.next(s,o,a.polling,n,r,{}),u=document.hidden&&!d&&Date.now()-l>p+500;let g;u&&this.logger.debug("polling - The polling seems to be throttled");try{const e=u?1e3:6e3;g=yield S(e,h)}catch(t){return this.logger.warn(`polling - The ${u?"throttled fetch":"fetch"} call timed out or was aborted`),void e(this,Ae,"f").call(this,s,o,n,r,u)}if((null===(t=null==g?void 0:g.error)||void 0===t?void 0:t.errorCode)===ne)return this.logger.debug("polling - Got a generic error due to exception in fetch call"),void e(this,Ae,"f").call(this,s,o,n,r);this.logger.debug("polling - Got a response"),(null==g?void 0:g.error)&&this.logger.debug("polling - Response has an error",JSON.stringify(g.error,null,4)),(null===(i=null==g?void 0:g.error)||void 0===i?void 0:i.errorCode)&&c.includes(g.error.errorCode)?this.logger.debug("polling - Stopping polling due to error"):e(this,Ae,"f").call(this,s,o,n,r),e(this,Ue,"f").call(this,g)}))),p),"f")}})),je.set(this,(()=>{clearTimeout(e(this,he,"f")),t(this,he,null,"f")})),Te.set(this,(()=>!!window.descopeBridge||/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent))),Ue.set(this,(i=>{var s,o,n,r,a,d,c,p,h,u,g,v,m;if(!(null==i?void 0:i.ok)){const t=null===(s=null==i?void 0:i.response)||void 0===s?void 0:s.url,l=`${null===(o=null==i?void 0:i.response)||void 0===o?void 0:o.status} - ${null===(n=null==i?void 0:i.response)||void 0===n?void 0:n.statusText}`;e(this,pe,"m",tt).call(this,"error",(null==i?void 0:i.error)||{errorCode:de,errorDescription:l,errorMessage:t}),this.loggerWrapper.error((null===(r=null==i?void 0:i.error)||void 0===r?void 0:r.errorDescription)||t,(null===(a=null==i?void 0:i.error)||void 0===a?void 0:a.errorMessage)||l);const c=null===(d=null==i?void 0:i.error)||void 0===d?void 0:d.errorCode;return void(c!==ce&&c!==re&&c!==ae||!this.isRestartOnError||e(this,pe,"m",Re).call(this))}null===(p=null===(c=i.data)||void 0===c?void 0:c.runnerLogs)||void 0===p||p.forEach((e=>{const{level:t,title:i,log:s}=e;t&&this.loggerWrapper[t]?this.loggerWrapper[t](i,s):this.loggerWrapper.info(i,s)}));const f=null===(g=null===(u=null===(h=i.data)||void 0===h?void 0:h.screen)||void 0===u?void 0:u.state)||void 0===g?void 0:g.errorText;(null===(v=i.data)||void 0===v?void 0:v.error)?this.loggerWrapper.error(`[${i.data.error.code}]: ${i.data.error.description}`,`${f?`${f} - `:""}${i.data.error.message}`):f&&this.loggerWrapper.error(f);const{status:b,authInfo:w,lastAuth:S,action:y,openInNewTabUrl:I}=i.data;if(y!==l.poll&&e(this,je,"f").call(this),"completed"===b){this.storeLastAuthenticatedUser&&Y(Object.assign(Object.assign({},S),{lastUsedPerScreen:Z()})),ee(this.loggerWrapper);const t=Object.assign({},w);return i.data.output&&Object.keys(i.data.output).length>0&&(t.flowOutput=i.data.output),this.setValidationTrackingExecution(i.data.executionId),J(this.projectId,this.flowId),void e(this,pe,"m",tt).call(this,"success",t)}this.storeLastAuthenticatedUser&&Y(S,!0),I&&window.open(I,"_blank");const{executionId:k,stepId:R,stepName:W,screen:C,redirect:x,webauthn:E,error:O,samlIdpResponse:A,wsFedIdpResponse:j,nativeResponse:T}=i.data,U=Date.now();y!==l.poll?(this.loggerWrapper.info(`Step "${W||`#${R}`}" is ${b}`,"",{screen:C,status:b,stepId:R,stepName:W,action:y,error:O}),(null===(m=C.state)||void 0===m?void 0:m.clientScripts)&&t(this,ge,this.loadSdkScripts(C.state.clientScripts),"f"),this.flowState.update({stepId:R,stepName:W,executionId:k,action:y,redirectTo:null==x?void 0:x.url,redirectIsPopup:null==x?void 0:x.isPopup,screenId:null==C?void 0:C.id,screenState:null==C?void 0:C.state,webauthnTransactionId:null==E?void 0:E.transactionId,webauthnOptions:null==E?void 0:E.options,samlIdpResponseUrl:null==A?void 0:A.url,samlIdpResponseSamlResponse:null==A?void 0:A.samlResponse,samlIdpResponseRelayState:null==A?void 0:A.relayState,wsFedIdpResponseUrl:null==j?void 0:j.url,wsFedIdpResponseWresult:null==j?void 0:j.wresult,wsFedIdpResponseWctx:null==j?void 0:j.wctx,nativeResponseType:null==T?void 0:T.type,nativePayload:null==T?void 0:T.payload,reqTimestamp:U})):this.flowState.update({action:y,reqTimestamp:U})})),Le.set(this,y((()=>i(this,void 0,void 0,(function*(){var e;try{const t=yield this.sdk.webauthn.signIn.start("",window.location.origin);return t.ok||this.loggerWrapper.warn("Webauthn start failed",null===(e=null==t?void 0:t.error)||void 0===e?void 0:e.errorMessage),t.data}catch(e){this.loggerWrapper.warn("Webauthn start failed",e.message)}}))))),$e.set(this,void 0),Ve.set(this,void 0),Ke.set(this,null),ze.set(this,I(((t,s,o)=>i(this,void 0,void 0,(function*(){var i;if("true"!==t.getAttribute("loading")&&"true"!==t.getAttribute("disabled")){if("true"===t.getAttribute("formnovalidate")||e(this,pe,"m",Be).call(this)){const n=null==t?void 0:t.getAttribute("id");e(this,pe,"m",Ye).call(this,t,n,o);const r=e(this,pe,"m",He).call(this,t);try{const o=yield e(this,pe,"m",_e).call(this),r=T(t);this.nextRequestStatus.update({isLoading:!0});const l=yield this.emailVerificationToken(t),a=Object.assign(Object.assign(Object.assign(Object.assign({},r),o),{origin:e(this,pe,"a",De)}),l&&{evpToken:l}),d=yield s(n,a);this.nextRequestStatus.update({isLoading:!1}),this.captureLastSubmittedLoginId(o,null===(i=null==d?void 0:d.data)||void 0===i?void 0:i.executionId),this.storeCredentials(o)}catch(e){throw r(),e}}}else this.loggerWrapper.debug("Submit already in flight, ignoring")}))))),this.flowState=s,this.setValidationTrackingSender(((e,t)=>i(this,[e,t],void 0,(function*({executionId:e,events:t},{keepalive:i}){const s=yield this.sdk.flow.event(e,t,i);return{ok:s.ok,retryable:s.code>=500||429===s.code}}))))}nativeResume(t,i){var s,o,n,r,l,a;const u=JSON.parse(i);if("oauthWeb"===t||"sso"===t){let e,{exchangeCode:t}=u;if(!t){const i=new URL(u.url);t=null===(s=i.searchParams)||void 0===s?void 0:s.get(d),e=(null===(o=i.searchParams)||void 0===o?void 0:o.get(c))||void 0}null===(r=(n=this.nativeCallbacks).complete)||void 0===r||r.call(n,{exchangeCode:t,exchangeError:e,idpInitiated:!0})}else if("magicLink"===t){const t=new URL(u.url),i=t.searchParams.get(p),s=t.searchParams.get(h).split("_").pop();e(this,je,"f").call(this),this.flowState.update({token:i,stepId:s,action:void 0})}else if("beforeScreen"===t){const{screenResolve:e}=this.nativeCallbacks;this.nativeCallbacks.screenResolve=null;const{override:t}=u;t||(this.nativeCallbacks.screenNext=null),null==e||e(t)}else if("resumeScreen"===t){const{interactionId:e,form:t}=u,{screenNext:i}=this.nativeCallbacks;this.nativeCallbacks.screenNext=null,null==i||i(e,t)}else null===(a=(l=this.nativeCallbacks).complete)||void 0===a||a.call(l,u)}loadSdkScriptsModules(){const e=this.shadowRoot.querySelectorAll("div[data-script-id]");return Array.from(e).map((e=>e.moduleRes)).filter((e=>!!e))}loadSdkScripts(e){if(!(null==e?void 0:e.length))return null;const t=(e,t)=>i=>{this.dispatchEvent(new CustomEvent("components-context",{detail:{[E(e.id,e.resultKey)]:i},bubbles:!0,composed:!0})),t(e.id)};this.loggerWrapper.debug(`Preparing to load scripts: ${e.map((e=>e.id)).join(", ")}`);const s=Promise.all(null==e?void 0:e.map((e=>i(this,void 0,void 0,(function*(){var i,s,o;const n=this.shadowRoot.querySelector(`[data-script-id="${e.id}"]`);if(n){this.loggerWrapper.debug("Script already loaded",e.id);const{moduleRes:t}=n;return null===(i=null==t?void 0:t.start)||void 0===i||i.call(t),t}(null===(s=globalThis.descope)||void 0===s?void 0:s[e.id])||(yield this.injectNpmLib("@descope/flow-scripts","1.0.21",`dist/${e.id}.js`));const r=null===(o=globalThis.descope)||void 0===o?void 0:o[e.id];return new Promise(((i,s)=>{try{const s=r(e.initArgs,{baseUrl:this.baseUrl,ref:this},t(e,i),this.loggerWrapper);if(s){const t=document.createElement("div");t.setAttribute("data-script-id",e.id),t.moduleRes=s,this.shadowRoot.appendChild(t);const o=this.nextRequestStatus.subscribe((()=>{var i;this.loggerWrapper.debug("Stopping script",e.id),(null===(i=s.stop)||void 0===i?void 0:i.call(s))&&(this.nextRequestStatus.unsubscribe(o),this.loggerWrapper.debug("Removing script",e.id),this.shadowRoot.removeChild(t))}));"function"==typeof s.present&&i(e.id)}}catch(e){s(e)}}))})))));let o;const n=new Promise((e=>{o=setTimeout((()=>{this.loggerWrapper.warn("SDK scripts loading timeout"),e(!0)}),u)}));return Promise.race([s,n]).finally((()=>clearTimeout(o)))}get isDismissScreenErrorOnInput(){return"true"===this.getAttribute("dismiss-screen-error-on-input")}init(){var e,i;if(!window.descopeBridge)return this._init();this.lazyInit=this._init,t(this,fe,null===(i=null===(e=null===window||void 0===window?void 0:window.descopeBridge)||void 0===e?void 0:e.registerFlow)||void 0===i?void 0:i.call(e,this),"f")}_init(){const t=Object.create(null,{init:{get:()=>super.init}});return i(this,void 0,void 0,(function*(){var i,s;this.shadowRoot.isConnected&&(null===(i=this.flowState)||void 0===i||i.subscribe(this.onFlowChange.bind(this)),e(this,pe,"m",Ie).call(this),window.addEventListener("visibilitychange",e(this,ve,"f").visibilitychange)),yield null===(s=t.init)||void 0===s?void 0:s.call(this)}))}disconnectedCallback(){var i,s,o;super.disconnectedCallback(),this.teardownValidationTracking(),e(this,fe,"f")&&(null===(s=null===(i=window.descopeBridge)||void 0===i?void 0:i.unregisterFlow)||void 0===s||s.call(i,e(this,fe,"f")),t(this,fe,void 0,"f")),this.flowState.unsubscribeAll(),this.stepState.unsubscribeAll(),e(this,je,"f").call(this),null===(o=e(this,ue,"f"))||void 0===o||o.abort(),t(this,ue,null,"f"),this.clearEmailVerification(),window.removeEventListener("visibilitychange",e(this,ve,"f").visibilitychange)}getHtmlFilenameWithLocale(e,t){return i(this,void 0,void 0,(function*(){let i;const s=o(e),n=yield this.getTargetLocales();return n.includes(s.locale)?i=`${t}-${s.locale}.html`:n.includes(s.fallback)&&(i=`${t}-${s.fallback}.html`),i}))}getPageContent(e,t){return i(this,void 0,void 0,(function*(){if(t)try{const{body:e}=yield this.fetchStaticResource(t,"text");return e}catch(i){this.loggerWrapper.error(`Failed to fetch flow page from ${t}. Fallback to url ${e}`,i)}try{const{body:t}=yield this.fetchStaticResource(e,"text");return t}catch(e){this.loggerWrapper.error("Failed to fetch flow page",e.message)}return null}))}onFlowChange(d,c,p){return i(this,void 0,void 0,(function*(){var h,u;const{projectId:g,flowId:v,tenant:m,stepId:f,executionId:b,action:w,screenId:S,screenState:y,redirectTo:I,redirectIsPopup:E,redirectUrl:A,token:j,code:T,isPopup:L,exchangeError:P,webauthnTransactionId:F,webauthnOptions:N,redirectAuthCodeChallenge:$,redirectAuthCallbackUrl:V,redirectAuthBackupCallbackUri:M,redirectAuthInitiator:q,locale:D,samlIdpResponseUrl:B,samlIdpResponseSamlResponse:_,samlIdpResponseRelayState:K,wsFedIdpResponseUrl:H,wsFedIdpResponseWresult:G,wsFedIdpResponseWctx:J,nativeResponseType:Y,nativePayload:Z,reqTimestamp:ie}=d,se=s(d,["projectId","flowId","tenant","stepId","executionId","action","screenId","screenState","redirectTo","redirectIsPopup","redirectUrl","token","code","isPopup","exchangeError","webauthnTransactionId","webauthnOptions","redirectAuthCodeChallenge","redirectAuthCallbackUrl","redirectAuthBackupCallbackUri","redirectAuthInitiator","locale","samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState","wsFedIdpResponseUrl","wsFedIdpResponseWresult","wsFedIdpResponseWctx","nativeResponseType","nativePayload","reqTimestamp"]);let oe,ne,re;const le=z(),{outboundAppId:ae,outboundAppScopes:de}=this,ce=this.sdk.getLastUserLoginId();p("flowId")&&this.setValidationTrackingEnabled(!1);const he=yield this.getFlowConfig();e(this,pe,"m",Me).call(this,he,b,p);const ve=yield this.getProjectConfig(),me=Object.entries(ve.flows||{}).reduce(((e,[t,i])=>(e[t]=i.version,e)),{}),fe=V&&$?{callbackUrl:V,codeChallenge:$,backupCallbackUri:M}:void 0,be=this.nativeOptions?{platform:this.nativeOptions.platform,bridgeVersion:this.nativeOptions.bridgeVersion,oauthProvider:this.nativeOptions.oauthProvider,oauthRedirect:this.nativeOptions.oauthRedirect,magicLinkRedirect:this.nativeOptions.magicLinkRedirect,ssoRedirect:this.nativeOptions.ssoRedirect,externalAuthRedirect:this.nativeOptions.externalAuthRedirect}:void 0;let we={};if(!b){ee(this.loggerWrapper);const i=[...he.clientScripts||[],...he.sdkScripts||[]];if(he.conditions){let e=[];({startScreenId:oe,conditionInteractionId:re,startScreenName:ne,clientScripts:e,componentsConfig:we}=Q({loginId:ce,code:T,token:j,abTestingKey:le,lastAuth:te(ce,this.loggerWrapper)},he.conditions)),i.push(...e||[])}else he.condition?({startScreenId:oe,startScreenName:ne,conditionInteractionId:re}=X(he.condition,{loginId:ce,code:T,token:j,abTestingKey:le,lastAuth:te(ce,this.loggerWrapper)})):(ne=he.startScreenName,oe=he.startScreenId);if(t(this,$e,oe,"f"),t(this,Ve,ne,"f"),t(this,ge,this.loadSdkScripts(i),"f"),he.fingerprintEnabled&&he.fingerprintKey?yield n(he.fingerprintKey,this.baseUrl):r(),!k(oe,se)){const t=yield this.sdk.flow.start(v,Object.assign(Object.assign(Object.assign(Object.assign({tenant:m,redirectAuth:fe},se),{client:this.client}),A&&{redirectUrl:A}),{lastAuth:te(ce,this.loggerWrapper),abTestingKey:le,locale:o(D).locale,nativeOptions:be,outboundAppId:ae,outboundAppScopes:de}),re,"",ve.componentsVersion,me,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({origin:e(this,pe,"a",De)},this.formConfigValues),T?{exchangeCode:T,idpInitiated:!0}:{}),se.descopeIdpInitiated&&{idpInitiated:!0}),j?{token:j}:{}),se.oidcLoginHint?{externalId:se.oidcLoginHint}:{}));return e(this,Ue,"f").call(this,t),void("completed"!==(null===(h=null==t?void 0:t.data)||void 0===h?void 0:h.status)&&this.flowState.update({code:void 0,token:void 0}))}}if(this.loggerWrapper.debug("Before popup postmessage send",JSON.stringify({isPopup:L,code:T,exchangeError:P,isCodeChanged:p("code"),isExchangeErrorChanged:p("exchangeError")})),L&&(p("code")&&T||p("exchangeError")&&P))return void e(this,pe,"m",it).call(this,b,T,P);if(b&&(p("token")&&j||p("code")&&T||p("exchangeError")&&P)){const t=yield this.sdk.flow.next(b,f,a.submit,he.version,ve.componentsVersion,{token:j,exchangeCode:T,exchangeError:P,origin:e(this,pe,"a",De)});return e(this,Ue,"f").call(this,t),void this.flowState.update({token:void 0,code:void 0,exchangeError:void 0})}if(w===l.loadForm&&B&&["samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState"].some((e=>p(e)))){if(!_)return void this.loggerWrapper.error("Did not get saml idp params data to load");R(B,_,K||"",U)}if(w===l.loadForm&&H&&["wsFedIdpResponseUrl","wsFedIdpResponseWresult","wsFedIdpResponseWctx"].some((e=>p(e)))){if(!G)return void this.loggerWrapper.error("Did not get wsfed idp params data to load");W(H,G,J||"",U)}if(w===l.redirect&&(p("redirectTo")||p("deferredRedirect"))){if(!I)return void this.loggerWrapper.error("Did not get redirect url");if("no-op"===I)return;if("android"===q&&document.hidden)return void this.flowState.update({deferredRedirect:!0});if(this.loggerWrapper.debug(`Redirect is popup ${E}`),E){this.loggerWrapper.debug("Opening redirect in popup");const t=C(I,"?",598,700),i=this.shouldUsePopupPostMessage();i&&(t.name=`descope-wc|${window.location.origin}`),this.loggerWrapper.debug("Popup communication method: "+(i?"postMessage":"BroadcastChannel"));let s=!1;const o=e=>{this.loggerWrapper.debug("Received popup message",JSON.stringify(e.data));const t=i?this.popupOrigin:window.location.origin;if(e.origin!==t)return void this.loggerWrapper.debug(`Ignoring message from unexpected origin. received: "${e.origin}", expected: "${t}"`);const{action:o,data:n}=e.data||{};"code"===o&&(s=!0,this.flowState.update({code:n.code,exchangeError:n.exchangeError}))};let n;this.loggerWrapper.debug("Starting popup closed detection");const r=setInterval((()=>{t.closed&&(this.loggerWrapper.debug("Popup closed, dispatching popupclosed event"),clearInterval(r),e(this,pe,"m",tt).call(this,"popupclosed",{abandoned:!s}),this.loggerWrapper.debug("Cleaning up popup listeners"),null==n||n())}),1e3);if(i)window.addEventListener("message",o),n=()=>{this.loggerWrapper.debug("Cleaning up popup postMessage listener"),window.removeEventListener("message",o)};else{this.loggerWrapper.debug("Creating broadcast channel");const e=new BroadcastChannel(b);e.onmessage=o,n=()=>{this.loggerWrapper.debug("Closing channel"),e.close()}}}else this.handleRedirect(I),this.flowState.update({redirectTo:"no-op"}),e(this,pe,"m",tt).call(this,"popupclosed",{});return}if(w===l.webauthnCreate||w===l.webauthnGet){if(!F||!N)return void this.loggerWrapper.error("Did not get webauthn transaction id or options");null===(u=e(this,ue,"f"))||void 0===u||u.abort(),t(this,ue,null,"f");const i=yield e(this,pe,"m",xe).call(this,w,N),s=yield this.sdk.flow.next(b,f,a.submit,he.version,ve.componentsVersion,Object.assign({transactionId:F},i));e(this,Ue,"f").call(this,s)}if(w===l.nativeBridge)return this.nativeCallbacks.complete=t=>i(this,void 0,void 0,(function*(){const i=yield this.sdk.flow.next(b,f,a.submit,he.version,ve.componentsVersion,t);e(this,Ue,"f").call(this,i)})),e(this,pe,"m",Se).call(this,Y,Z),void setTimeout((()=>{this.dispatchEvent(new Event("popupclosed"))}),500);if((p("action")||p("deferredPolling"))&&e(this,Ae,"f").call(this,b,f,he.version,ve.componentsVersion),!S&&!oe)return void this.loggerWrapper.warn("No screen was found to show");const ye=oe||S,Ie=yield this.getHtmlFilenameWithLocale(D,ye),{oidcLoginHint:ke,oidcPrompt:Re,oidcErrorRedirectUri:We,oidcResource:Ee,samlIdpUsername:Oe}=se,je={direction:x(f,c.stepId),screenState:Object.assign(Object.assign({},y),{form:Object.assign(Object.assign({},this.formConfigValues),null==y?void 0:y.form),lastAuth:{loginId:ce,name:this.sdk.getLastUserDisplayName()||ce},componentsConfig:Object.assign(Object.assign(Object.assign({},he.componentsConfig),we),null==y?void 0:y.componentsConfig)}),htmlFilename:`${ye}.html`,htmlLocaleFilename:Ie,screenId:ye,stepName:d.stepName||ne,samlIdpUsername:Oe,oidcLoginHint:ke,oidcPrompt:Re,oidcErrorRedirectUri:We,oidcResource:Ee,action:w,locale:o(D).locale},Te=te(ce,this.loggerWrapper);k(oe,se)?je.next=(t,s)=>i(this,void 0,void 0,(function*(){const i=(null==he?void 0:he.clientScripts)||[];yield e(this,pe,"m",Qe).call(this,i);const n=yield this.sdk.flow.start(v,Object.assign(Object.assign(Object.assign(Object.assign({tenant:m,redirectAuth:fe},se),{lastAuth:Te,preview:this.preview,abTestingKey:le,client:this.client}),A&&{redirectUrl:A}),{locale:o(D).locale,nativeOptions:be,outboundAppId:ae,outboundAppScopes:de}),re,t,ve.componentsVersion,me,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({origin:e(this,pe,"a",De)},this.formConfigValues),this.getComponentsContext()),O(s)),T&&{exchangeCode:T,idpInitiated:!0}),se.descopeIdpInitiated&&{idpInitiated:!0}),j&&{token:j}),je.next.isCustomScreen);return e(this,Ue,"f").call(this,n),n})):(p("projectId")||p("baseUrl")||p("executionId")||p("stepId"))&&(je.next=(t,s)=>i(this,void 0,void 0,(function*(){const i=(null==y?void 0:y.clientScripts)||[];yield e(this,pe,"m",Qe).call(this,i);const o=yield this.sdk.flow.next(b,f,t,he.version,ve.componentsVersion,Object.assign(Object.assign({origin:e(this,pe,"a",De)},this.getComponentsContext()),O(s)),je.next.isCustomScreen);return e(this,Ue,"f").call(this,o),o}))),this.loggerWrapper.debug("Got a screen with id",je.screenId),yield e(this,pe,"m",Ce).call(this,je),this.stepState.update(je)}))}onStepChange(t,s){return i(this,void 0,void 0,(function*(){var o,n,r;const{htmlFilename:l,htmlLocaleFilename:d,direction:c,next:p,screenState:h,screenId:u}=t;this.loggerWrapper.debug("Rendering a flow screen"),this.clearEmailVerification(),this.updateScreenUser(null==h?void 0:h.user);const g=document.createElement("template");g.innerHTML=yield this.getPageContent(l,d);const m=g.content.cloneNode(!0),f=this.loadDescopeUiComponents(g);this.sdk.webauthn.helpers.isSupported()?yield e(this,pe,"m",Fe).call(this,m,p):$(m),!t.samlIdpUsername||(null===(o=h.form)||void 0===o?void 0:o.loginId)||(null===(n=h.form)||void 0===n?void 0:n.email)||(h.form||(h.form={}),h.form.loginId=t.samlIdpUsername,h.form.email=t.samlIdpUsername),V(m,h,this.formConfig,this.loggerWrapper),this.applyComponentsState(m,null==h?void 0:h.componentsState),this.startEmailVerification(m);const{geo:b}=null!==(r=yield this.getExecutionContext())&&void 0!==r?r:{};M(m,b),q(m,t.locale);const w=()=>i(this,void 0,void 0,(function*(){var i,o;yield f;const n=this.contentRootElement;D(n,null===(i=null==h?void 0:h.totp)||void 0===i?void 0:i.image),B(n,null===(o=null==h?void 0:h.notp)||void 0===o?void 0:o.image),_(n,m,h.cssVars,this.loggerWrapper),n.replaceChildren(m);const r=!s.htmlFilename;setTimeout((()=>{e(this,pe,"m",Ge).call(this),this.updateUsernameAnchor(),this.validateOnBlur&&A(n,(t=>this.trackValidationErrors([t],e(this,pe,"a",qe)))),K(n,h),this.initRealtimeConditions(n,h),e(this,pe,"m",Ne).call(this,{isFirstScreen:r,isCustomScreen:!1,stepName:t.stepName}),j(n,this.autoFocus,r),e(this,pe,"m",Ze).call(this,u)})),e(this,pe,"m",et).call(this,p,u);n.querySelector(`[${v}="polling"]`)&&p(a.polling,{})}));c?e(this,pe,"m",Oe).call(this,w):w()}))}getInputs(){return Array.from(this.shadowRoot.querySelectorAll(`*:not(slot)[name]:not([${g}])`))}shouldUsePopupPostMessage(){if(!this.popupOrigin)return!1;try{new URL(this.popupOrigin)}catch(e){return!1}return!0}}he=new WeakMap,ue=new WeakMap,ge=new WeakMap,ve=new WeakMap,fe=new WeakMap,We=new WeakMap,Ee=new WeakMap,Ae=new WeakMap,je=new WeakMap,Te=new WeakMap,Ue=new WeakMap,Le=new WeakMap,$e=new WeakMap,Ve=new WeakMap,Ke=new WeakMap,ze=new WeakMap,pe=new WeakSet,me=function(){document.hidden||setTimeout((()=>{this.flowState.update({deferredRedirect:!1,deferredPolling:!1})}),300)},be=function(t,s,o){return i(this,void 0,void 0,(function*(){var i;return(null===(i=this.nativeOptions)||void 0===i?void 0:i.bridgeVersion)>=2&&new Promise((i=>{this.nativeCallbacks.screenNext=o,this.nativeCallbacks.screenResolve=i,e(this,pe,"m",Se).call(this,"beforeScreen",{screen:t,context:s})}))}))},we=function(t){var i;(null===(i=this.nativeOptions)||void 0===i?void 0:i.bridgeVersion)>=2&&e(this,pe,"m",Se).call(this,"afterScreen",{screen:t})},Se=function(t,i){e(this,pe,"m",tt).call(this,"bridge",{type:t,payload:i})},ye=function({errorText:e,errorType:t}){const i=()=>{var i;let s=e;try{s=(null===(i=this.errorTransformer)||void 0===i?void 0:i.call(this,{text:e,type:t}))||e}catch(e){this.loggerWrapper.error("Error transforming error message",e.message)}H(this.contentRootElement,"error-message",s)};this.addEventListener("screen-updated",i,{once:!0}),i()},Ie=function(){var t,i,o,n;null===(t=this.stepState)||void 0===t||t.subscribe(this.onStepChange.bind(this),(e=>{var t=e.screenState,i=void 0===t?{}:t,{errorText:o,errorType:n}=i,r=s(i,["errorText","errorType"]),l=s(e,["screenState"]);return Object.assign(Object.assign({},l),{screenState:r})})),null===(i=this.stepState)||void 0===i||i.subscribe(e(this,pe,"m",ye).bind(this),(e=>{var t,i;return{errorText:null===(t=null==e?void 0:e.screenState)||void 0===t?void 0:t.errorText,errorType:null===(i=null==e?void 0:e.screenState)||void 0===i?void 0:i.errorType}}),{forceUpdate:!0}),null===(o=this.stepState)||void 0===o||o.subscribe(e(this,pe,"m",ke).bind(this),(e=>{var t,i;return{errorText:null===(t=null==e?void 0:e.screenState)||void 0===t?void 0:t.errorText,errorType:null===(i=null==e?void 0:e.screenState)||void 0===i?void 0:i.errorType}}),{forceUpdate:!0}),null===(n=this.flowState)||void 0===n||n.subscribe((({screenId:e,executionId:t})=>{var i;try{this.updateTelemetryContext({screenId:e,executionId:t})}catch(e){null===(i=this.logger)||void 0===i||i.error("Error updating telemetry screenId:",e)}}),(e=>({screenId:e.screenId,executionId:e.executionId})))},ke=function({errorText:e,errorType:t}){(t||e)&&(this.contentRootElement.querySelectorAll('descope-passcode[data-auto-submit="true"]').forEach((e=>{e.shadowRoot.querySelectorAll("descope-text-field[data-id]").forEach((e=>{e.value=""}))})),j(this.contentRootElement,this.autoFocus,!1))},Re=function(){return i(this,void 0,void 0,(function*(){this.loggerWrapper.debug("Trying to restart the flow");const e=yield this.getComponentsVersion();this.reset();e===(yield this.getComponentsVersion())?(this.loggerWrapper.debug("Components version was not changed, restarting flow"),this.flowState.update({stepId:null,executionId:null})):this.loggerWrapper.error("Components version mismatch, please reload the page")}))},Ce=function(o){return i(this,void 0,void 0,(function*(){var i;const n=Object.assign(Object.assign({},this.stepState.current),o),{next:r,stepName:l}=n,a=s(n,["next","stepName"]),d=L(a);let c=yield e(this,pe,"m",be).call(this,l,d,r);c||(c=Boolean(yield null===(i=this.onScreenUpdate)||void 0===i?void 0:i.call(this,l,d,r,this)));const p=!this.stepState.current.htmlFilename;if(e(this,Ee,"f").call(this,c),r&&(r.isCustomScreen=c),e(this,We,"f")!==c){const[i,s]=["flow","custom"].sort((()=>c?-1:1));this.loggerWrapper.debug(`Switching from ${s} screen to ${i} screen`),t(this,We,c,"f"),c?this.stepState.unsubscribeAll():e(this,pe,"m",Ie).call(this)}c?(this.loggerWrapper.debug("Showing a custom screen"),e(this,pe,"m",Ne).call(this,{isFirstScreen:p,isCustomScreen:c,stepName:o.stepName}),this.disableKeyPressHandler()):this.handleKeyPress(),this.stepState.forceUpdate=c}))},xe=function(e,t){return i(this,void 0,void 0,(function*(){const i=new AbortController;try{const s=e===l.webauthnCreate?this.sdk.webauthn.helpers.create(t,i):this.sdk.webauthn.helpers.get(t,i),o=yield S(m,s,st);return o!==st?{response:o}:(i.abort(),this.loggerWrapper.warn(`WebAuthn operation timed out after ${m}ms`),{failure:"AbortError",failureReason:"aborted",failureMessage:"Passkey operation timed out"})}catch(e){return"InvalidStateError"===e.name?this.loggerWrapper.warn("WebAuthn operation failed",e.message):"NotAllowedError"!==e.name&&this.loggerWrapper.error(e.message),{failure:e.name,failureReason:e.reason,failureMessage:e.message}}}))},Oe=function(e){this.contentRootElement.addEventListener("transitionend",(()=>{this.loggerWrapper.debug("page switch transition end"),this.contentRootElement.classList.remove("fade-out"),e()}),{once:!0}),this.loggerWrapper.debug("page switch transition start"),this.contentRootElement.classList.add("fade-out")},Pe=function(e){const t=e.getAttribute("name");if(!["email"].includes(t)){const i=`user-${t}`;e.setAttribute("name",i),e.addEventListener("input",(()=>{e.setAttribute("name",e.value?t:i)}))}},Fe=function(s,o){return i(this,void 0,void 0,(function*(){var n;null===(n=e(this,ue,"f"))||void 0===n||n.abort();const r=s.querySelector('*[autocomplete="webauthn"]');if(r&&(yield G())){const{options:s,transactionId:n}=(yield e(this,Le,"f").call(this))||{};s&&n&&(e(this,pe,"m",Pe).call(this,r),t(this,ue,new AbortController,"f"),this.sdk.webauthn.helpers.conditional(s,e(this,ue,"f")).then((e=>i(this,void 0,void 0,(function*(){o(r.id,{transactionId:n,response:e})})))).catch((e=>{"AbortError"!==e.name&&this.loggerWrapper.error("Conditional login failed",e.message)})))}}))},Ne=function({isFirstScreen:t,isCustomScreen:i,stepName:s}){t&&e(this,pe,"m",tt).call(this,"ready",{}),i||e(this,pe,"m",we).call(this,s),e(this,pe,"m",tt).call(this,"page-updated",{screenName:s}),e(this,pe,"m",tt).call(this,"screen-updated",{screenName:s})},Me=function(e,t,i){this.setValidationTrackingEnabled(!!e.clientValidationTrackingEnabled),t&&i("executionId")&&this.setValidationTrackingExecution(t)},qe=function(){var t,i,s,o,n,r,l;const a=null===(t=this.flowState)||void 0===t?void 0:t.current;return(null==a?void 0:a.executionId)?{executionId:a.executionId,screenId:a.screenId,screenName:(null===(l=null===(r=this.stepState)||void 0===r?void 0:r.current)||void 0===l?void 0:l.stepName)||a.stepName}:{executionId:void 0,screenId:null!==(i=e(this,$e,"f"))&&void 0!==i?i:null==a?void 0:a.screenId,screenName:null!==(s=e(this,Ve,"f"))&&void 0!==s?s:(null===(n=null===(o=this.stepState)||void 0===o?void 0:o.current)||void 0===n?void 0:n.stepName)||(null==a?void 0:a.stepName)}},De=function(){var e;return(null===(e=this.nativeOptions)||void 0===e?void 0:e.origin)||window.location.origin},Be=function(){let t=!0;const i=[];return Array.from(this.shadowRoot.querySelectorAll("*[name]")).reverse().forEach((e=>{var s,o,n;"slot"===e.localName||se(e,this.contentRootElement)||(null===(s=e.reportValidity)||void 0===s||s.call(e),e.validity&&!e.validity.valid&&i.push(e),t&&(t=null===(n=null===(o=e.checkValidity)||void 0===o?void 0:o.call(e))||void 0===n||n))})),i.length&&this.trackValidationErrors(i,e(this,pe,"a",qe)),t},_e=function(){return i(this,void 0,void 0,(function*(){const e=this.getInputs();return(yield Promise.all(e.map((e=>i(this,void 0,void 0,(function*(){return{name:e.getAttribute("name"),value:e.value}})))))).reduce(((e,t)=>Object.assign(Object.assign({},e),{[t.name]:t.value})),{})}))},He=function(s){var o,n;const r=Array.from(this.contentRootElement.querySelectorAll(':not([disabled]), [disabled="false"]')).filter((e=>e!==s)),l=(null===(n=null===(o=this.flowState.current)||void 0===o?void 0:o.screenState)||void 0===n?void 0:n.clientScripts)||[];s.setAttribute("loading","true"),r.forEach((e=>e.setAttribute("disabled","true")));const a=()=>{s.removeAttribute("loading"),r.forEach((e=>{e.removeAttribute("disabled")}))},d=e=>i(this,void 0,void 0,(function*(){var s;this.loggerWrapper.debug("Restoring components state"),this.removeEventListener("popupclosed",d);if(!0===(null===(s=null==e?void 0:e.detail)||void 0===s?void 0:s.abandoned)&&l.length)return t(this,ge,(()=>i(this,void 0,void 0,(function*(){try{yield this.loadSdkScripts(l)}catch(e){this.loggerWrapper.warn("Failed to refresh client scripts on popup close",null==e?void 0:e.message)}})))(),"f"),void a();a();const o=yield this.getFlowConfig(),n=[...o.clientScripts||[],...o.sdkScripts||[]];this.loadSdkScripts(n)})),c=()=>{var i;window.removeEventListener("pageshow",e(this,Ke,"f")),t(this,Ke,(e=>{e.persisted&&(this.logger.debug("Page was loaded from cache, restoring components state"),d())}),"f"),window.addEventListener("pageshow",e(this,Ke,"f"),{once:!0});const s=null===(i=this.stepState)||void 0===i?void 0:i.subscribe(((e,t)=>{e===t&&d(),this.removeEventListener("popupclosed",d),this.stepState.unsubscribe(s)}),(e=>e.screenId),{forceUpdate:!0})},p=this.nextRequestStatus.subscribe((({isLoading:e})=>{e?this.addEventListener("popupclosed",d,{once:!0}):(this.nextRequestStatus.unsubscribe(p),"success"===this.flowStatus?(this.removeEventListener("popupclosed",d),a()):c())}));return a},Ge=function(){P();this.contentRootElement.querySelectorAll('[external-input="true"]').forEach((t=>e(this,pe,"m",Je).call(this,t)))},Je=function(e){if(!e)return;e.querySelectorAll("input").forEach((t=>{const i=t.getAttribute("slot"),s=`input-${e.id}-${i}`,o=document.createElement("slot");o.setAttribute("name",s),o.setAttribute("slot",i),e.appendChild(o),t.setAttribute("slot",s),this.appendChild(t)}))},Qe=function(t){return i(this,void 0,void 0,(function*(){if(e(this,ge,"f")){this.loggerWrapper.debug("Waiting for sdk scripts to load");const t=Date.now();yield e(this,ge,"f"),this.loggerWrapper.debug("Sdk scripts loaded for",(Date.now()-t).toString())}const i=this.loadSdkScriptsModules(),s=t.map((e=>e.id));for(const e of i)if(s.includes(e.id))try{if("function"==typeof e.present){(yield e.present())||this.loggerWrapper.debug(`Sdk script ${e.id} was cancelled`)}}catch(t){this.loggerWrapper.error(`Failed to present ${e.id} script module`,t.message)}const o=[];for(const e of i)"function"==typeof e.refresh&&o.push(e.refresh());if(o.length>0)try{yield S(u,Promise.all(o),null)}catch(e){this.loggerWrapper.error("Failed to refresh script module",e.message)}}))},Xe=function(t,i){this.contentRootElement.querySelectorAll('descope-passcode[data-auto-submit="true"]').forEach((s=>{s.addEventListener("input",(()=>{var o;(null===(o=s.checkValidity)||void 0===o?void 0:o.call(s))&&e(this,ze,"f").call(this,s,t,i)}))}))},Ye=function(e,t,i){t&&i&&"true"===e.getAttribute(f)&&ie(i,t,this.loggerWrapper)},Ze=function(e){var t;const i=this.sdk.getLastUserLoginId(),s=null===(t=te(i,this.loggerWrapper).lastUsedPerScreen)||void 0===t?void 0:t[e];if(!s)return;const o=this.contentRootElement.querySelector(b),n=this.contentRootElement.querySelector(`#${CSS.escape(s)}`);o&&n&&(n.replaceWith(o),o.appendChild(n))},et=function(t,i){this.contentRootElement.querySelectorAll(`descope-button:not([${w}]), [data-type="button"]:not([${w}]`).forEach((s=>{s.onclick=()=>{e(this,ze,"f").call(this,s,t,i)}})),e(this,pe,"m",Xe).call(this,t,i),this.isDismissScreenErrorOnInput&&this.contentRootElement.querySelectorAll(`*[name]:not([${g}])`).forEach((e=>{e.addEventListener("input",(()=>{this.stepState.update((e=>Object.assign(Object.assign({},e),{screenState:Object.assign(Object.assign({},e.screenState),{errorText:"",errorType:""})})))}))}))},tt=function(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t}))},it=function(e,t,i){var s;const[o,n]=(null===(s=window.name)||void 0===s?void 0:s.split("|"))||[],r="descope-wc"===o&&!!n,l=r?F(n):void 0;r&&!l&&this.loggerWrapper.warn("Popup opener origin is not approved for this project, add it to the approved domains to send the OAuth result to it",n);const a={data:{code:t,exchangeError:i},action:"code"};if(l){this.loggerWrapper.debug("Using postMessage fallback to notify opener in origin",l);try{window.opener.postMessage(a,l)}catch(e){this.loggerWrapper.error("Failed to send postMessage fallback (likely COOP isolation)",null==e?void 0:e.message)}}else{this.loggerWrapper.debug("Creating popup channel",e);const t=new BroadcastChannel(e);t.postMessage(a),t.close()}try{window.close()}catch(e){}},ot.bridgeVersion=3;export{ot as default};
1
+ import{__classPrivateFieldGet as e,__classPrivateFieldSet as t,__awaiter as i,__rest as s}from"tslib";import{getUserLocale as o}from"@descope/sdk-helpers";import{ensureFingerprintIds as n,clearFingerprintData as r}from"@descope/web-js-sdk";import{RESPONSE_ACTIONS as l,CUSTOM_INTERACTIONS as a,URL_CODE_PARAM_NAME as d,URL_ERR_PARAM_NAME as c,URL_TOKEN_PARAM_NAME as p,URL_RUN_IDS_PARAM_NAME as h,SDK_SCRIPTS_LOAD_TIMEOUT as u,DESCOPE_ATTRIBUTE_EXCLUDE_FIELD as g,ELEMENT_TYPE_ATTRIBUTE as v,WEBAUTHN_TIMEOUT as m,DESCOPE_ATTRIBUTE_OPT_IN_LAST_USED as f,DESCOPE_LAST_AUTH_BADGE_COMPONENT as b,DESCOPE_ATTRIBUTE_EXCLUDE_NEXT_BUTTON as w}from"../constants/index.js";import{timeoutPromise as S,withMemCache as y,leadingDebounce as I,getIdFromExecId as k,showFirstScreenOnExecutionInit as R,injectSamlIdpForm as W,injectWsFedIdpForm as C,openCenteredPopup as x,getAnimationDirection as E,transformScreenInputs as O,handleReportValidityOnBlur as A,handleAutoFocus as j,getScriptResultPath as T,getElementDescopeAttributes as P,submitForm as U,transformStepStateForCustomScreen as L,clearPreviousExternalInputs as F,getTrustedPopupOpenerOrigin as $}from"../helpers/helpers.js";import N from"../helpers/state.js";import{disableWebauthnButtons as V,updateTemplateFromScreenState as M,setComponentsAutoDetectByGeo as q,setComponentsAutoDetectByLocale as D,setTOTPVariable as B,setNOTPVariable as _,setCssVars as K,updateScreenFromScreenState as H,replaceElementMessage as G}from"../helpers/templates.js";import{isConditionalLoginSupported as J}from"../helpers/webauthn.js";import{clearSsoQueryParams as Q,linkRunToSsoContext as z,pickSsoQueryParams as X,clearSsoContextOnAppRedirect as Y}from"../helpers/oidcSession.js";import{getABTestingKey as Z}from"../helpers/abTestingKey.js";import{calculateConditions as ee,calculateCondition as te}from"../helpers/conditions.js";import{setLastAuth as ie,getInFlightLastUsedPerScreen as se,clearInFlightLastAuth as oe,getLastAuth as ne,updateLastUsedPerScreen as re}from"../helpers/lastAuth.js";import{isHiddenByCondition as le}from"../helpers/realtime-conditions/applier.js";import ae from"./BaseDescopeWc.js";import{FETCH_EXCEPTION_ERROR_CODE as de,FLOW_TIMED_OUT_ERROR_CODE as ce,POLLING_STATUS_NOT_FOUND_ERROR_CODE as pe,NONCE_VALIDATION_ERROR_CODE as he,FETCH_ERROR_RESPONSE_ERROR_CODE as ue,FLOW_REQUESTED_IS_IN_OLD_VERSION_ERROR_CODE as ge}from"../constants/general.js";var ve,me,fe,be,we,Se,ye,Ie,ke,Re,We,Ce,xe,Ee,Oe,Ae,je,Te,Pe,Ue,Le,Fe,$e,Ne,Ve,Me,qe,De,Be,_e,Ke,He,Ge,Je,Qe,ze,Xe,Ye,Ze,et,tt,it,st,ot,nt,rt;const lt="__descope_webauthn_timed_out__";class at extends ae{static set sdkConfigOverrides(e){ae.sdkConfigOverrides=e}static get sdkConfigOverrides(){return ae.sdkConfigOverrides}constructor(){const s=new N({deferredRedirect:!1,deferredPolling:!1});super(s.update.bind(s)),ve.add(this),this.stepState=new N({}),me.set(this,void 0),fe.set(this,null),be.set(this,null),we.set(this,{visibilitychange:e(this,ve,"m",Se).bind(this)}),this.bridgeVersion=at.bridgeVersion,ye.set(this,void 0),this.nativeCallbacks={},Oe.set(this,!1),this.handleRedirect=e=>{window.location.assign(e)},Te.set(this,(t=>{t&&this.clearEmailVerification();const i=()=>{this.contentRootElement.classList.toggle("hidden",t),this.slotElement.classList.toggle("hidden",!t),t&&(this.contentRootElement.innerHTML="")};t&&this.contentRootElement.hasChildNodes()?e(this,ve,"m",Pe).call(this,i):i()})),Ue.set(this,((s,o,n,r,d=!1)=>{const c=[ce,pe,he];if(this.flowState.current.action===l.poll){if(e(this,Fe,"f").call(this)&&document.hidden)return this.logger.debug("polling - Deferring polling until in foreground"),void this.flowState.update({deferredPolling:!0});this.logger.debug("polling - Scheduling polling request");const l=Date.now(),p=d?500:2e3;t(this,me,setTimeout((()=>i(this,void 0,void 0,(function*(){var t,i;this.logger.debug("polling - Calling next");const h=this.sdk.flow.next(s,o,a.polling,n,r,{}),u=document.hidden&&!d&&Date.now()-l>p+500;let g;u&&this.logger.debug("polling - The polling seems to be throttled");try{const e=u?1e3:6e3;g=yield S(e,h)}catch(t){return this.logger.warn(`polling - The ${u?"throttled fetch":"fetch"} call timed out or was aborted`),void e(this,Ue,"f").call(this,s,o,n,r,u)}if((null===(t=null==g?void 0:g.error)||void 0===t?void 0:t.errorCode)===de)return this.logger.debug("polling - Got a generic error due to exception in fetch call"),void e(this,Ue,"f").call(this,s,o,n,r);this.logger.debug("polling - Got a response"),(null==g?void 0:g.error)&&this.logger.debug("polling - Response has an error",JSON.stringify(g.error,null,4)),(null===(i=null==g?void 0:g.error)||void 0===i?void 0:i.errorCode)&&c.includes(g.error.errorCode)?this.logger.debug("polling - Stopping polling due to error"):e(this,Ue,"f").call(this,s,o,n,r),e(this,$e,"f").call(this,g)}))),p),"f")}})),Le.set(this,(()=>{clearTimeout(e(this,me,"f")),t(this,me,null,"f")})),Fe.set(this,(()=>!!window.descopeBridge||/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent))),$e.set(this,(i=>{var s,o,n,r,a,d,c,p,h,u,g,v,m;if(!(null==i?void 0:i.ok)){const t=null===(s=null==i?void 0:i.response)||void 0===s?void 0:s.url,l=`${null===(o=null==i?void 0:i.response)||void 0===o?void 0:o.status} - ${null===(n=null==i?void 0:i.response)||void 0===n?void 0:n.statusText}`;e(this,ve,"m",nt).call(this,"error",(null==i?void 0:i.error)||{errorCode:ue,errorDescription:l,errorMessage:t}),this.loggerWrapper.error((null===(r=null==i?void 0:i.error)||void 0===r?void 0:r.errorDescription)||t,(null===(a=null==i?void 0:i.error)||void 0===a?void 0:a.errorMessage)||l);const c=null===(d=null==i?void 0:i.error)||void 0===d?void 0:d.errorCode;return void(c!==ge&&c!==ce&&c!==he||!this.isRestartOnError||e(this,ve,"m",Ee).call(this))}null===(p=null===(c=i.data)||void 0===c?void 0:c.runnerLogs)||void 0===p||p.forEach((e=>{const{level:t,title:i,log:s}=e;t&&this.loggerWrapper[t]?this.loggerWrapper[t](i,s):this.loggerWrapper.info(i,s)}));const f=null===(g=null===(u=null===(h=i.data)||void 0===h?void 0:h.screen)||void 0===u?void 0:u.state)||void 0===g?void 0:g.errorText;(null===(v=i.data)||void 0===v?void 0:v.error)?this.loggerWrapper.error(`[${i.data.error.code}]: ${i.data.error.description}`,`${f?`${f} - `:""}${i.data.error.message}`):f&&this.loggerWrapper.error(f);const{status:b,authInfo:w,lastAuth:S,action:y,openInNewTabUrl:I}=i.data;if(y!==l.poll&&e(this,Le,"f").call(this),"completed"===b){this.storeLastAuthenticatedUser&&ie(Object.assign(Object.assign({},S),{lastUsedPerScreen:se()})),oe(this.loggerWrapper);const t=Object.assign({},w);return i.data.output&&Object.keys(i.data.output).length>0&&(t.flowOutput=i.data.output),this.setValidationTrackingExecution(i.data.executionId),Q(this.projectId,this.flowId),void e(this,ve,"m",nt).call(this,"success",t)}this.storeLastAuthenticatedUser&&ie(S,!0),I&&window.open(I,"_blank");const{executionId:k,stepId:R,stepName:W,screen:C,redirect:x,webauthn:E,error:O,samlIdpResponse:A,wsFedIdpResponse:j,nativeResponse:T}=i.data,P=Date.now();y!==l.poll?(this.loggerWrapper.info(`Step "${W||`#${R}`}" is ${b}`,"",{screen:C,status:b,stepId:R,stepName:W,action:y,error:O}),(null===(m=C.state)||void 0===m?void 0:m.clientScripts)&&t(this,be,this.loadSdkScripts(C.state.clientScripts),"f"),this.flowState.update({stepId:R,stepName:W,executionId:k,action:y,redirectTo:null==x?void 0:x.url,redirectIsPopup:null==x?void 0:x.isPopup,screenId:null==C?void 0:C.id,screenState:null==C?void 0:C.state,webauthnTransactionId:null==E?void 0:E.transactionId,webauthnOptions:null==E?void 0:E.options,samlIdpResponseUrl:null==A?void 0:A.url,samlIdpResponseSamlResponse:null==A?void 0:A.samlResponse,samlIdpResponseRelayState:null==A?void 0:A.relayState,wsFedIdpResponseUrl:null==j?void 0:j.url,wsFedIdpResponseWresult:null==j?void 0:j.wresult,wsFedIdpResponseWctx:null==j?void 0:j.wctx,nativeResponseType:null==T?void 0:T.type,nativePayload:null==T?void 0:T.payload,reqTimestamp:P})):this.flowState.update({action:y,reqTimestamp:P})})),Ne.set(this,y((()=>i(this,void 0,void 0,(function*(){var e;try{const t=yield this.sdk.webauthn.signIn.start("",window.location.origin);return t.ok||this.loggerWrapper.warn("Webauthn start failed",null===(e=null==t?void 0:t.error)||void 0===e?void 0:e.errorMessage),t.data}catch(e){this.loggerWrapper.warn("Webauthn start failed",e.message)}}))))),De.set(this,void 0),Be.set(this,void 0),Qe.set(this,null),Ze.set(this,I(((t,s,o)=>i(this,void 0,void 0,(function*(){var i;if("true"!==t.getAttribute("loading")&&"true"!==t.getAttribute("disabled")){if("true"===t.getAttribute("formnovalidate")||e(this,ve,"m",Ge).call(this)){const n=null==t?void 0:t.getAttribute("id");e(this,ve,"m",it).call(this,t,n,o);const r=e(this,ve,"m",ze).call(this,t);try{const o=yield e(this,ve,"m",Je).call(this),r=P(t);this.nextRequestStatus.update({isLoading:!0});const l=yield this.emailVerificationToken(t),a=Object.assign(Object.assign(Object.assign(Object.assign({},r),o),{origin:e(this,ve,"a",He)}),l&&{evpToken:l}),d=yield s(n,a);this.nextRequestStatus.update({isLoading:!1}),this.captureLastSubmittedLoginId(o,null===(i=null==d?void 0:d.data)||void 0===i?void 0:i.executionId),this.storeCredentials(o)}catch(e){throw r(),e}}}else this.loggerWrapper.debug("Submit already in flight, ignoring")}))))),this.flowState=s,this.setValidationTrackingSender(((e,t)=>i(this,[e,t],void 0,(function*({executionId:e,events:t},{keepalive:i}){const s=yield this.sdk.flow.event(e,t,i);return{ok:s.ok,retryable:s.code>=500||429===s.code}}))))}nativeResume(t,i){var s,o,n,r,l,a;const u=JSON.parse(i);if("oauthWeb"===t||"sso"===t){let e,{exchangeCode:t}=u;if(!t){const i=new URL(u.url);t=null===(s=i.searchParams)||void 0===s?void 0:s.get(d),e=(null===(o=i.searchParams)||void 0===o?void 0:o.get(c))||void 0}null===(r=(n=this.nativeCallbacks).complete)||void 0===r||r.call(n,{exchangeCode:t,exchangeError:e,idpInitiated:!0})}else if("magicLink"===t){const t=new URL(u.url),i=t.searchParams.get(p),s=t.searchParams.get(h).split("_").pop();e(this,Le,"f").call(this),this.flowState.update({token:i,stepId:s,action:void 0})}else if("beforeScreen"===t){const{screenResolve:e}=this.nativeCallbacks;this.nativeCallbacks.screenResolve=null;const{override:t}=u;t||(this.nativeCallbacks.screenNext=null),null==e||e(t)}else if("resumeScreen"===t){const{interactionId:e,form:t}=u,{screenNext:i}=this.nativeCallbacks;this.nativeCallbacks.screenNext=null,null==i||i(e,t)}else null===(a=(l=this.nativeCallbacks).complete)||void 0===a||a.call(l,u)}loadSdkScriptsModules(){const e=this.shadowRoot.querySelectorAll("div[data-script-id]");return Array.from(e).map((e=>e.moduleRes)).filter((e=>!!e))}loadSdkScripts(e){if(!(null==e?void 0:e.length))return null;const t=(e,t)=>i=>{this.dispatchEvent(new CustomEvent("components-context",{detail:{[T(e.id,e.resultKey)]:i},bubbles:!0,composed:!0})),t(e.id)};this.loggerWrapper.debug(`Preparing to load scripts: ${e.map((e=>e.id)).join(", ")}`);const s=e=>i(this,void 0,void 0,(function*(){var i,s,o;const n=this.shadowRoot.querySelector(`[data-script-id="${e.id}"]`);if(n){this.loggerWrapper.debug("Script already loaded",e.id);const{moduleRes:t}=n;return null===(i=null==t?void 0:t.start)||void 0===i||i.call(t),t}(null===(s=globalThis.descope)||void 0===s?void 0:s[e.id])||(yield this.injectNpmLib("@descope/flow-scripts","1.0.22",`dist/${e.id}.js`));const r=null===(o=globalThis.descope)||void 0===o?void 0:o[e.id];return new Promise(((i,s)=>{try{const s=r(e.initArgs,{baseUrl:this.baseUrl,ref:this},t(e,i),this.loggerWrapper);if(s){const t=document.createElement("div");t.setAttribute("data-script-id",e.id),t.moduleRes=s,this.shadowRoot.appendChild(t);const o=this.nextRequestStatus.subscribe((()=>{var i;this.loggerWrapper.debug("Stopping script",e.id),(null===(i=s.stop)||void 0===i?void 0:i.call(s))&&(this.nextRequestStatus.unsubscribe(o),this.loggerWrapper.debug("Removing script",e.id),this.shadowRoot.removeChild(t))}));"function"==typeof s.present&&i(e.id)}}catch(e){s(e)}}))})),o=Promise.all((null!=e?e:[]).map((e=>s(e).catch((t=>(this.loggerWrapper.warn(`Sdk script ${e.id} failed to load, continuing without it`,null==t?void 0:t.message),null))))));let n;const r=new Promise((e=>{n=setTimeout((()=>{this.loggerWrapper.warn("SDK scripts loading timeout"),e(!0)}),u)}));return Promise.race([o,r]).finally((()=>clearTimeout(n))).catch((e=>(this.loggerWrapper.warn("Sdk scripts failed to load, continuing without them",null==e?void 0:e.message),null)))}get isDismissScreenErrorOnInput(){return"true"===this.getAttribute("dismiss-screen-error-on-input")}init(){var e,i;if(!window.descopeBridge)return this._init();this.lazyInit=this._init,t(this,ye,null===(i=null===(e=null===window||void 0===window?void 0:window.descopeBridge)||void 0===e?void 0:e.registerFlow)||void 0===i?void 0:i.call(e,this),"f")}_init(){const t=Object.create(null,{init:{get:()=>super.init}});return i(this,void 0,void 0,(function*(){var i,s;this.shadowRoot.isConnected&&(null===(i=this.flowState)||void 0===i||i.subscribe(this.onFlowChange.bind(this)),e(this,ve,"m",Ce).call(this),window.addEventListener("visibilitychange",e(this,we,"f").visibilitychange)),yield null===(s=t.init)||void 0===s?void 0:s.call(this)}))}disconnectedCallback(){var i,s,o;super.disconnectedCallback(),this.teardownValidationTracking(),e(this,ye,"f")&&(null===(s=null===(i=window.descopeBridge)||void 0===i?void 0:i.unregisterFlow)||void 0===s||s.call(i,e(this,ye,"f")),t(this,ye,void 0,"f")),this.flowState.unsubscribeAll(),this.stepState.unsubscribeAll(),e(this,Le,"f").call(this),null===(o=e(this,fe,"f"))||void 0===o||o.abort(),t(this,fe,null,"f"),this.clearEmailVerification(),window.removeEventListener("visibilitychange",e(this,we,"f").visibilitychange)}getHtmlFilenameWithLocale(e,t){return i(this,void 0,void 0,(function*(){let i;const s=o(e),n=yield this.getTargetLocales();return n.includes(s.locale)?i=`${t}-${s.locale}.html`:n.includes(s.fallback)&&(i=`${t}-${s.fallback}.html`),i}))}getPageContent(e,t){return i(this,void 0,void 0,(function*(){if(t)try{const{body:e}=yield this.fetchStaticResource(t,"text");return e}catch(i){this.loggerWrapper.error(`Failed to fetch flow page from ${t}. Fallback to url ${e}`,i)}try{const{body:t}=yield this.fetchStaticResource(e,"text");return t}catch(e){this.loggerWrapper.error("Failed to fetch flow page",e.message)}return null}))}onFlowChange(d,c,p){return i(this,void 0,void 0,(function*(){var h,u;const{projectId:g,flowId:v,tenant:m,stepId:f,executionId:b,action:w,screenId:S,screenState:y,redirectTo:I,redirectIsPopup:A,redirectUrl:j,token:T,code:P,isPopup:L,exchangeError:F,webauthnTransactionId:$,webauthnOptions:N,redirectAuthCodeChallenge:V,redirectAuthCallbackUrl:M,redirectAuthBackupCallbackUri:q,redirectAuthInitiator:D,locale:B,samlIdpResponseUrl:_,samlIdpResponseSamlResponse:K,samlIdpResponseRelayState:H,wsFedIdpResponseUrl:G,wsFedIdpResponseWresult:J,wsFedIdpResponseWctx:Q,nativeResponseType:ie,nativePayload:se,reqTimestamp:re}=d,le=s(d,["projectId","flowId","tenant","stepId","executionId","action","screenId","screenState","redirectTo","redirectIsPopup","redirectUrl","token","code","isPopup","exchangeError","webauthnTransactionId","webauthnOptions","redirectAuthCodeChallenge","redirectAuthCallbackUrl","redirectAuthBackupCallbackUri","redirectAuthInitiator","locale","samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState","wsFedIdpResponseUrl","wsFedIdpResponseWresult","wsFedIdpResponseWctx","nativeResponseType","nativePayload","reqTimestamp"]);let ae,de,ce;p("executionId")&&b&&z(k(b),X(le),g,v);const pe=Z(),{outboundAppId:he,outboundAppScopes:ue}=this,ge=this.sdk.getLastUserLoginId();p("flowId")&&this.setValidationTrackingEnabled(!1);const me=yield this.getFlowConfig();e(this,ve,"m",_e).call(this,me,b,p);const we=yield this.getProjectConfig(),Se=Object.entries(we.flows||{}).reduce(((e,[t,i])=>(e[t]=i.version,e)),{}),ye=M&&V?{callbackUrl:M,codeChallenge:V,backupCallbackUri:q}:void 0,Ie=this.nativeOptions?{platform:this.nativeOptions.platform,bridgeVersion:this.nativeOptions.bridgeVersion,oauthProvider:this.nativeOptions.oauthProvider,oauthRedirect:this.nativeOptions.oauthRedirect,magicLinkRedirect:this.nativeOptions.magicLinkRedirect,ssoRedirect:this.nativeOptions.ssoRedirect,externalAuthRedirect:this.nativeOptions.externalAuthRedirect}:void 0;let ke={};if(!b){oe(this.loggerWrapper);const i=[...me.clientScripts||[],...me.sdkScripts||[]];if(me.conditions){let e=[];({startScreenId:ae,conditionInteractionId:ce,startScreenName:de,clientScripts:e,componentsConfig:ke}=ee({loginId:ge,code:P,token:T,abTestingKey:pe,lastAuth:ne(ge,this.loggerWrapper)},me.conditions)),i.push(...e||[])}else me.condition?({startScreenId:ae,startScreenName:de,conditionInteractionId:ce}=te(me.condition,{loginId:ge,code:P,token:T,abTestingKey:pe,lastAuth:ne(ge,this.loggerWrapper)})):(de=me.startScreenName,ae=me.startScreenId);if(t(this,De,ae,"f"),t(this,Be,de,"f"),t(this,be,this.loadSdkScripts(i),"f"),me.fingerprintEnabled&&me.fingerprintKey?yield n(me.fingerprintKey,this.baseUrl):r(),!R(ae,le)){const t=yield this.sdk.flow.start(v,Object.assign(Object.assign(Object.assign(Object.assign({tenant:m,redirectAuth:ye},le),{client:this.client}),j&&{redirectUrl:j}),{lastAuth:ne(ge,this.loggerWrapper),abTestingKey:pe,locale:o(B).locale,nativeOptions:Ie,outboundAppId:he,outboundAppScopes:ue}),ce,"",we.componentsVersion,Se,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({origin:e(this,ve,"a",He)},this.formConfigValues),P?{exchangeCode:P,idpInitiated:!0}:{}),le.descopeIdpInitiated&&{idpInitiated:!0}),T?{token:T}:{}),le.oidcLoginHint?{externalId:le.oidcLoginHint}:{}));return e(this,$e,"f").call(this,t),void("completed"!==(null===(h=null==t?void 0:t.data)||void 0===h?void 0:h.status)&&this.flowState.update({code:void 0,token:void 0}))}}if(this.loggerWrapper.debug("Before popup postmessage send",JSON.stringify({isPopup:L,code:P,exchangeError:F,isCodeChanged:p("code"),isExchangeErrorChanged:p("exchangeError")})),L&&(p("code")&&P||p("exchangeError")&&F))return void e(this,ve,"m",rt).call(this,b,P,F);if(b&&(p("token")&&T||p("code")&&P||p("exchangeError")&&F)){const t=yield this.sdk.flow.next(b,f,a.submit,me.version,we.componentsVersion,{token:T,exchangeCode:P,exchangeError:F,origin:e(this,ve,"a",He)});return e(this,$e,"f").call(this,t),void this.flowState.update({token:void 0,code:void 0,exchangeError:void 0})}if(w===l.loadForm&&_&&["samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState"].some((e=>p(e)))){if(!K)return void this.loggerWrapper.error("Did not get saml idp params data to load");W(_,K,H||"",U)}if(w===l.loadForm&&G&&["wsFedIdpResponseUrl","wsFedIdpResponseWresult","wsFedIdpResponseWctx"].some((e=>p(e)))){if(!J)return void this.loggerWrapper.error("Did not get wsfed idp params data to load");C(G,J,Q||"",U)}if(w===l.redirect&&(p("redirectTo")||p("deferredRedirect"))){if(!I)return void this.loggerWrapper.error("Did not get redirect url");if("no-op"===I)return;if("android"===D&&document.hidden)return void this.flowState.update({deferredRedirect:!0});if(this.loggerWrapper.debug(`Redirect is popup ${A}`),A){this.loggerWrapper.debug("Opening redirect in popup");const t=x(I,"?",598,700),i=this.shouldUsePopupPostMessage();i&&(t.name=`descope-wc|${window.location.origin}`),this.loggerWrapper.debug("Popup communication method: "+(i?"postMessage":"BroadcastChannel"));let s=!1;const o=e=>{this.loggerWrapper.debug("Received popup message",JSON.stringify(e.data));const t=i?this.popupOrigin:window.location.origin;if(e.origin!==t)return void this.loggerWrapper.debug(`Ignoring message from unexpected origin. received: "${e.origin}", expected: "${t}"`);const{action:o,data:n}=e.data||{};"code"===o&&(s=!0,this.flowState.update({code:n.code,exchangeError:n.exchangeError}))};let n;this.loggerWrapper.debug("Starting popup closed detection");const r=setInterval((()=>{t.closed&&(this.loggerWrapper.debug("Popup closed, dispatching popupclosed event"),clearInterval(r),e(this,ve,"m",nt).call(this,"popupclosed",{abandoned:!s}),this.loggerWrapper.debug("Cleaning up popup listeners"),null==n||n())}),1e3);if(i)window.addEventListener("message",o),n=()=>{this.loggerWrapper.debug("Cleaning up popup postMessage listener"),window.removeEventListener("message",o)};else{this.loggerWrapper.debug("Creating broadcast channel");const e=new BroadcastChannel(b);e.onmessage=o,n=()=>{this.loggerWrapper.debug("Closing channel"),e.close()}}}else Y(I,k(b),Object.assign(Object.assign({},this.adoptedSsoQueryParams),X(le)),g,v),this.handleRedirect(I),this.flowState.update({redirectTo:"no-op"}),e(this,ve,"m",nt).call(this,"popupclosed",{});return}if(w===l.webauthnCreate||w===l.webauthnGet){if(!$||!N)return void this.loggerWrapper.error("Did not get webauthn transaction id or options");null===(u=e(this,fe,"f"))||void 0===u||u.abort(),t(this,fe,null,"f");const i=yield e(this,ve,"m",je).call(this,w,N),s=yield this.sdk.flow.next(b,f,a.submit,me.version,we.componentsVersion,Object.assign({transactionId:$},i));e(this,$e,"f").call(this,s)}if(w===l.nativeBridge)return this.nativeCallbacks.complete=t=>i(this,void 0,void 0,(function*(){const i=yield this.sdk.flow.next(b,f,a.submit,me.version,we.componentsVersion,t);e(this,$e,"f").call(this,i)})),e(this,ve,"m",Re).call(this,ie,se),void setTimeout((()=>{this.dispatchEvent(new Event("popupclosed"))}),500);if((p("action")||p("deferredPolling"))&&e(this,Ue,"f").call(this,b,f,me.version,we.componentsVersion),!S&&!ae)return void this.loggerWrapper.warn("No screen was found to show");const We=ae||S,Ce=yield this.getHtmlFilenameWithLocale(B,We),{oidcLoginHint:xe,oidcPrompt:Ee,oidcErrorRedirectUri:Oe,oidcResource:Te,samlIdpUsername:Pe}=le,Le={direction:E(f,c.stepId),screenState:Object.assign(Object.assign({},y),{form:Object.assign(Object.assign({},this.formConfigValues),null==y?void 0:y.form),lastAuth:{loginId:ge,name:this.sdk.getLastUserDisplayName()||ge},componentsConfig:Object.assign(Object.assign(Object.assign({},me.componentsConfig),ke),null==y?void 0:y.componentsConfig)}),htmlFilename:`${We}.html`,htmlLocaleFilename:Ce,screenId:We,stepName:d.stepName||de,samlIdpUsername:Pe,oidcLoginHint:xe,oidcPrompt:Ee,oidcErrorRedirectUri:Oe,oidcResource:Te,action:w,locale:o(B).locale},Fe=ne(ge,this.loggerWrapper);R(ae,le)?Le.next=(t,s)=>i(this,void 0,void 0,(function*(){const i=(null==me?void 0:me.clientScripts)||[];yield e(this,ve,"m",et).call(this,i);const n=yield this.sdk.flow.start(v,Object.assign(Object.assign(Object.assign(Object.assign({tenant:m,redirectAuth:ye},le),{lastAuth:Fe,preview:this.preview,abTestingKey:pe,client:this.client}),j&&{redirectUrl:j}),{locale:o(B).locale,nativeOptions:Ie,outboundAppId:he,outboundAppScopes:ue}),ce,t,we.componentsVersion,Se,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({origin:e(this,ve,"a",He)},this.formConfigValues),this.getComponentsContext()),O(s)),P&&{exchangeCode:P,idpInitiated:!0}),le.descopeIdpInitiated&&{idpInitiated:!0}),T&&{token:T}),Le.next.isCustomScreen);return e(this,$e,"f").call(this,n),n})):(p("projectId")||p("baseUrl")||p("executionId")||p("stepId"))&&(Le.next=(t,s)=>i(this,void 0,void 0,(function*(){const i=(null==y?void 0:y.clientScripts)||[];yield e(this,ve,"m",et).call(this,i);const o=yield this.sdk.flow.next(b,f,t,me.version,we.componentsVersion,Object.assign(Object.assign({origin:e(this,ve,"a",He)},this.getComponentsContext()),O(s)),Le.next.isCustomScreen);return e(this,$e,"f").call(this,o),o}))),this.loggerWrapper.debug("Got a screen with id",Le.screenId),yield e(this,ve,"m",Ae).call(this,Le),this.stepState.update(Le)}))}onStepChange(t,s){return i(this,void 0,void 0,(function*(){var o,n,r;const{htmlFilename:l,htmlLocaleFilename:d,direction:c,next:p,screenState:h,screenId:u}=t;this.loggerWrapper.debug("Rendering a flow screen"),this.clearEmailVerification(),this.updateScreenUser(null==h?void 0:h.user);const g=document.createElement("template");g.innerHTML=yield this.getPageContent(l,d);const m=g.content.cloneNode(!0),f=this.loadDescopeUiComponents(g);this.sdk.webauthn.helpers.isSupported()?yield e(this,ve,"m",Me).call(this,m,p):V(m),!t.samlIdpUsername||(null===(o=h.form)||void 0===o?void 0:o.loginId)||(null===(n=h.form)||void 0===n?void 0:n.email)||(h.form||(h.form={}),h.form.loginId=t.samlIdpUsername,h.form.email=t.samlIdpUsername),M(m,h,this.formConfig,this.loggerWrapper),this.applyComponentsState(m,null==h?void 0:h.componentsState),this.startEmailVerification(m);const{geo:b}=null!==(r=yield this.getExecutionContext())&&void 0!==r?r:{};q(m,b),D(m,t.locale);const w=()=>i(this,void 0,void 0,(function*(){var i,o;yield f;const n=this.contentRootElement;B(n,null===(i=null==h?void 0:h.totp)||void 0===i?void 0:i.image),_(n,null===(o=null==h?void 0:h.notp)||void 0===o?void 0:o.image),K(n,m,h.cssVars,this.loggerWrapper),n.replaceChildren(m);const r=!s.htmlFilename;setTimeout((()=>{e(this,ve,"m",Xe).call(this),this.updateUsernameAnchor(),this.validateOnBlur&&A(n,(t=>this.trackValidationErrors([t],e(this,ve,"a",Ke)))),H(n,h),this.initRealtimeConditions(n,h),e(this,ve,"m",qe).call(this,{isFirstScreen:r,isCustomScreen:!1,stepName:t.stepName}),j(n,this.autoFocus,r),e(this,ve,"m",st).call(this,u)})),e(this,ve,"m",ot).call(this,p,u);n.querySelector(`[${v}="polling"]`)&&p(a.polling,{})}));c?e(this,ve,"m",Pe).call(this,w):w()}))}getInputs(){return Array.from(this.shadowRoot.querySelectorAll(`*:not(slot)[name]:not([${g}])`))}shouldUsePopupPostMessage(){if(!this.popupOrigin)return!1;try{new URL(this.popupOrigin)}catch(e){return!1}return!0}}me=new WeakMap,fe=new WeakMap,be=new WeakMap,we=new WeakMap,ye=new WeakMap,Oe=new WeakMap,Te=new WeakMap,Ue=new WeakMap,Le=new WeakMap,Fe=new WeakMap,$e=new WeakMap,Ne=new WeakMap,De=new WeakMap,Be=new WeakMap,Qe=new WeakMap,Ze=new WeakMap,ve=new WeakSet,Se=function(){document.hidden||setTimeout((()=>{this.flowState.update({deferredRedirect:!1,deferredPolling:!1})}),300)},Ie=function(t,s,o){return i(this,void 0,void 0,(function*(){var i;return(null===(i=this.nativeOptions)||void 0===i?void 0:i.bridgeVersion)>=2&&new Promise((i=>{this.nativeCallbacks.screenNext=o,this.nativeCallbacks.screenResolve=i,e(this,ve,"m",Re).call(this,"beforeScreen",{screen:t,context:s})}))}))},ke=function(t){var i;(null===(i=this.nativeOptions)||void 0===i?void 0:i.bridgeVersion)>=2&&e(this,ve,"m",Re).call(this,"afterScreen",{screen:t})},Re=function(t,i){e(this,ve,"m",nt).call(this,"bridge",{type:t,payload:i})},We=function({errorText:e,errorType:t}){const i=()=>{var i;let s=e;try{s=(null===(i=this.errorTransformer)||void 0===i?void 0:i.call(this,{text:e,type:t}))||e}catch(e){this.loggerWrapper.error("Error transforming error message",e.message)}G(this.contentRootElement,"error-message",s)};this.addEventListener("screen-updated",i,{once:!0}),i()},Ce=function(){var t,i,o,n;null===(t=this.stepState)||void 0===t||t.subscribe(this.onStepChange.bind(this),(e=>{var t=e.screenState,i=void 0===t?{}:t,{errorText:o,errorType:n}=i,r=s(i,["errorText","errorType"]),l=s(e,["screenState"]);return Object.assign(Object.assign({},l),{screenState:r})})),null===(i=this.stepState)||void 0===i||i.subscribe(e(this,ve,"m",We).bind(this),(e=>{var t,i;return{errorText:null===(t=null==e?void 0:e.screenState)||void 0===t?void 0:t.errorText,errorType:null===(i=null==e?void 0:e.screenState)||void 0===i?void 0:i.errorType}}),{forceUpdate:!0}),null===(o=this.stepState)||void 0===o||o.subscribe(e(this,ve,"m",xe).bind(this),(e=>{var t,i;return{errorText:null===(t=null==e?void 0:e.screenState)||void 0===t?void 0:t.errorText,errorType:null===(i=null==e?void 0:e.screenState)||void 0===i?void 0:i.errorType}}),{forceUpdate:!0}),null===(n=this.flowState)||void 0===n||n.subscribe((({screenId:e,executionId:t})=>{var i;try{this.updateTelemetryContext({screenId:e,executionId:t})}catch(e){null===(i=this.logger)||void 0===i||i.error("Error updating telemetry screenId:",e)}}),(e=>({screenId:e.screenId,executionId:e.executionId})))},xe=function({errorText:e,errorType:t}){(t||e)&&(this.contentRootElement.querySelectorAll('descope-passcode[data-auto-submit="true"]').forEach((e=>{e.shadowRoot.querySelectorAll("descope-text-field[data-id]").forEach((e=>{e.value=""}))})),j(this.contentRootElement,this.autoFocus,!1))},Ee=function(){return i(this,void 0,void 0,(function*(){this.loggerWrapper.debug("Trying to restart the flow");const e=yield this.getComponentsVersion();this.reset();e===(yield this.getComponentsVersion())?(this.loggerWrapper.debug("Components version was not changed, restarting flow"),this.flowState.update(Object.assign({stepId:null,executionId:null},this.adoptedSsoQueryParams))):this.loggerWrapper.error("Components version mismatch, please reload the page")}))},Ae=function(o){return i(this,void 0,void 0,(function*(){var i;const n=Object.assign(Object.assign({},this.stepState.current),o),{next:r,stepName:l}=n,a=s(n,["next","stepName"]),d=L(a);let c=yield e(this,ve,"m",Ie).call(this,l,d,r);c||(c=Boolean(yield null===(i=this.onScreenUpdate)||void 0===i?void 0:i.call(this,l,d,r,this)));const p=!this.stepState.current.htmlFilename;if(e(this,Te,"f").call(this,c),r&&(r.isCustomScreen=c),e(this,Oe,"f")!==c){const[i,s]=["flow","custom"].sort((()=>c?-1:1));this.loggerWrapper.debug(`Switching from ${s} screen to ${i} screen`),t(this,Oe,c,"f"),c?this.stepState.unsubscribeAll():e(this,ve,"m",Ce).call(this)}c?(this.loggerWrapper.debug("Showing a custom screen"),e(this,ve,"m",qe).call(this,{isFirstScreen:p,isCustomScreen:c,stepName:o.stepName}),this.disableKeyPressHandler()):this.handleKeyPress(),this.stepState.forceUpdate=c}))},je=function(e,t){return i(this,void 0,void 0,(function*(){const i=new AbortController;try{const s=e===l.webauthnCreate?this.sdk.webauthn.helpers.create(t,i):this.sdk.webauthn.helpers.get(t,i),o=yield S(m,s,lt);return o!==lt?{response:o}:(i.abort(),this.loggerWrapper.warn(`WebAuthn operation timed out after ${m}ms`),{failure:"AbortError",failureReason:"aborted",failureMessage:"Passkey operation timed out"})}catch(e){return"InvalidStateError"===e.name?this.loggerWrapper.warn("WebAuthn operation failed",e.message):"NotAllowedError"!==e.name&&this.loggerWrapper.error(e.message),{failure:e.name,failureReason:e.reason,failureMessage:e.message}}}))},Pe=function(e){this.contentRootElement.addEventListener("transitionend",(()=>{this.loggerWrapper.debug("page switch transition end"),this.contentRootElement.classList.remove("fade-out"),e()}),{once:!0}),this.loggerWrapper.debug("page switch transition start"),this.contentRootElement.classList.add("fade-out")},Ve=function(e){const t=e.getAttribute("name");if(!["email"].includes(t)){const i=`user-${t}`;e.setAttribute("name",i),e.addEventListener("input",(()=>{e.setAttribute("name",e.value?t:i)}))}},Me=function(s,o){return i(this,void 0,void 0,(function*(){var n;null===(n=e(this,fe,"f"))||void 0===n||n.abort();const r=s.querySelector('*[autocomplete="webauthn"]');if(r&&(yield J())){const{options:s,transactionId:n}=(yield e(this,Ne,"f").call(this))||{};s&&n&&(e(this,ve,"m",Ve).call(this,r),t(this,fe,new AbortController,"f"),this.sdk.webauthn.helpers.conditional(s,e(this,fe,"f")).then((e=>i(this,void 0,void 0,(function*(){o(r.id,{transactionId:n,response:e})})))).catch((e=>{"AbortError"!==e.name&&this.loggerWrapper.error("Conditional login failed",e.message)})))}}))},qe=function({isFirstScreen:t,isCustomScreen:i,stepName:s}){t&&e(this,ve,"m",nt).call(this,"ready",{}),i||e(this,ve,"m",ke).call(this,s),e(this,ve,"m",nt).call(this,"page-updated",{screenName:s}),e(this,ve,"m",nt).call(this,"screen-updated",{screenName:s})},_e=function(e,t,i){this.setValidationTrackingEnabled(!!e.clientValidationTrackingEnabled),t&&i("executionId")&&this.setValidationTrackingExecution(t)},Ke=function(){var t,i,s,o,n,r,l;const a=null===(t=this.flowState)||void 0===t?void 0:t.current;return(null==a?void 0:a.executionId)?{executionId:a.executionId,screenId:a.screenId,screenName:(null===(l=null===(r=this.stepState)||void 0===r?void 0:r.current)||void 0===l?void 0:l.stepName)||a.stepName}:{executionId:void 0,screenId:null!==(i=e(this,De,"f"))&&void 0!==i?i:null==a?void 0:a.screenId,screenName:null!==(s=e(this,Be,"f"))&&void 0!==s?s:(null===(n=null===(o=this.stepState)||void 0===o?void 0:o.current)||void 0===n?void 0:n.stepName)||(null==a?void 0:a.stepName)}},He=function(){var e;return(null===(e=this.nativeOptions)||void 0===e?void 0:e.origin)||window.location.origin},Ge=function(){let t=!0;const i=[];return Array.from(this.shadowRoot.querySelectorAll("*[name]")).reverse().forEach((e=>{var s,o,n;"slot"===e.localName||le(e,this.contentRootElement)||(null===(s=e.reportValidity)||void 0===s||s.call(e),e.validity&&!e.validity.valid&&i.push(e),t&&(t=null===(n=null===(o=e.checkValidity)||void 0===o?void 0:o.call(e))||void 0===n||n))})),i.length&&this.trackValidationErrors(i,e(this,ve,"a",Ke)),t},Je=function(){return i(this,void 0,void 0,(function*(){const e=this.getInputs();return(yield Promise.all(e.map((e=>i(this,void 0,void 0,(function*(){return{name:e.getAttribute("name"),value:e.value}})))))).reduce(((e,t)=>Object.assign(Object.assign({},e),{[t.name]:t.value})),{})}))},ze=function(s){var o,n;const r=Array.from(this.contentRootElement.querySelectorAll(':not([disabled]), [disabled="false"]')).filter((e=>e!==s)),l=(null===(n=null===(o=this.flowState.current)||void 0===o?void 0:o.screenState)||void 0===n?void 0:n.clientScripts)||[];s.setAttribute("loading","true"),r.forEach((e=>e.setAttribute("disabled","true")));const a=()=>{s.removeAttribute("loading"),r.forEach((e=>{e.removeAttribute("disabled")}))},d=e=>i(this,void 0,void 0,(function*(){var s;this.loggerWrapper.debug("Restoring components state"),this.removeEventListener("popupclosed",d);if(!0===(null===(s=null==e?void 0:e.detail)||void 0===s?void 0:s.abandoned)&&l.length)return t(this,be,(()=>i(this,void 0,void 0,(function*(){try{yield this.loadSdkScripts(l)}catch(e){this.loggerWrapper.warn("Failed to refresh client scripts on popup close",null==e?void 0:e.message)}})))(),"f"),void a();a();const o=yield this.getFlowConfig(),n=[...o.clientScripts||[],...o.sdkScripts||[]];this.loadSdkScripts(n)})),c=()=>{var i;window.removeEventListener("pageshow",e(this,Qe,"f")),t(this,Qe,(e=>{e.persisted&&(this.logger.debug("Page was loaded from cache, restoring components state"),d())}),"f"),window.addEventListener("pageshow",e(this,Qe,"f"),{once:!0});const s=null===(i=this.stepState)||void 0===i?void 0:i.subscribe(((e,t)=>{e===t&&d(),this.removeEventListener("popupclosed",d),this.stepState.unsubscribe(s)}),(e=>e.screenId),{forceUpdate:!0})},p=this.nextRequestStatus.subscribe((({isLoading:e})=>{e?this.addEventListener("popupclosed",d,{once:!0}):(this.nextRequestStatus.unsubscribe(p),"success"===this.flowStatus?(this.removeEventListener("popupclosed",d),a()):c())}));return a},Xe=function(){F();this.contentRootElement.querySelectorAll('[external-input="true"]').forEach((t=>e(this,ve,"m",Ye).call(this,t)))},Ye=function(e){if(!e)return;e.querySelectorAll("input").forEach((t=>{const i=t.getAttribute("slot"),s=`input-${e.id}-${i}`,o=document.createElement("slot");o.setAttribute("name",s),o.setAttribute("slot",i),e.appendChild(o),t.setAttribute("slot",s),this.appendChild(t)}))},et=function(t){return i(this,void 0,void 0,(function*(){if(e(this,be,"f")){this.loggerWrapper.debug("Waiting for sdk scripts to load");const t=Date.now();yield e(this,be,"f"),this.loggerWrapper.debug("Sdk scripts loaded for",(Date.now()-t).toString())}const i=this.loadSdkScriptsModules(),s=t.map((e=>e.id));for(const e of i)if(s.includes(e.id))try{if("function"==typeof e.present){(yield e.present())||this.loggerWrapper.debug(`Sdk script ${e.id} was cancelled`)}}catch(t){this.loggerWrapper.error(`Failed to present ${e.id} script module`,t.message)}const o=[];for(const e of i)"function"==typeof e.refresh&&o.push(e.refresh());if(o.length>0)try{yield S(u,Promise.all(o),null)}catch(e){this.loggerWrapper.error("Failed to refresh script module",e.message)}}))},tt=function(t,i){this.contentRootElement.querySelectorAll('descope-passcode[data-auto-submit="true"]').forEach((s=>{s.addEventListener("input",(()=>{var o;(null===(o=s.checkValidity)||void 0===o?void 0:o.call(s))&&e(this,Ze,"f").call(this,s,t,i)}))}))},it=function(e,t,i){t&&i&&"true"===e.getAttribute(f)&&re(i,t,this.loggerWrapper)},st=function(e){var t;const i=this.sdk.getLastUserLoginId(),s=null===(t=ne(i,this.loggerWrapper).lastUsedPerScreen)||void 0===t?void 0:t[e];if(!s)return;const o=this.contentRootElement.querySelector(b),n=this.contentRootElement.querySelector(`#${CSS.escape(s)}`);o&&n&&(n.replaceWith(o),o.appendChild(n))},ot=function(t,i){this.contentRootElement.querySelectorAll(`descope-button:not([${w}]), [data-type="button"]:not([${w}]`).forEach((s=>{s.onclick=()=>{e(this,Ze,"f").call(this,s,t,i)}})),e(this,ve,"m",tt).call(this,t,i),this.isDismissScreenErrorOnInput&&this.contentRootElement.querySelectorAll(`*[name]:not([${g}])`).forEach((e=>{e.addEventListener("input",(()=>{this.stepState.update((e=>Object.assign(Object.assign({},e),{screenState:Object.assign(Object.assign({},e.screenState),{errorText:"",errorType:""})})))}))}))},nt=function(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t}))},rt=function(e,t,i){var s;const[o,n]=(null===(s=window.name)||void 0===s?void 0:s.split("|"))||[],r="descope-wc"===o&&!!n,l=r?$(n):void 0;r&&!l&&this.loggerWrapper.warn("Popup opener origin is not approved for this project, add it to the approved domains to send the OAuth result to it",n);const a={data:{code:t,exchangeError:i},action:"code"};if(l){this.loggerWrapper.debug("Using postMessage fallback to notify opener in origin",l);try{window.opener.postMessage(a,l)}catch(e){this.loggerWrapper.error("Failed to send postMessage fallback (likely COOP isolation)",null==e?void 0:e.message)}}else{this.loggerWrapper.debug("Creating popup channel",e);const t=new BroadcastChannel(e);t.postMessage(a),t.close()}try{window.close()}catch(e){}},at.bridgeVersion=3;export{at as default};
2
2
  //# sourceMappingURL=DescopeWc.js.map