@descope/web-component 3.59.1 → 3.60.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- "use strict";var e=require("tslib"),t=require("../constants/index.js"),r=require("../constants/customScreens.js"),o=require("../types.js"),n=require("../constants/content.js");const i=["descope-enriched-text"];function a(e){return new URLSearchParams(window.location.search).get(e)}function s(e){if(window.history.replaceState&&a(e)){const t=new URL(window.location.href),r=new URLSearchParams(t.search);r.delete(e),t.search=r.toString(),window.history.replaceState({},"",t.toString())}}const c=e=>{let[r="",o=""]=(a(t.URL_RUN_IDS_PARAM_NAME)||"").split("_");const n=(e=>{var t;return(null===(t=/(.*)---.*/.exec(e))||void 0===t?void 0:t[1])||""})(r);return(!e||n&&n!==e)&&(r="",o=""),{executionId:r,stepId:o,executionFlowId:n}};function u(){s(t.URL_RUN_IDS_PARAM_NAME)}function l(){return a(t.URL_TOKEN_PARAM_NAME)||void 0}function d(){s(t.URL_TOKEN_PARAM_NAME)}function p(){return a(t.URL_CODE_PARAM_NAME)||void 0}function A(){return"popup"===a(t.URL_REDIRECT_MODE_PARAM_NAME)}function _(){return a(t.URL_ERR_PARAM_NAME)||void 0}function m(){s(t.URL_CODE_PARAM_NAME)}function P(){s(t.URL_REDIRECT_MODE_PARAM_NAME)}function E(){s(t.URL_ERR_PARAM_NAME)}function I(){return{redirectAuthCodeChallenge:a(t.URL_REDIRECT_AUTH_CHALLENGE_PARAM_NAME),redirectAuthCallbackUrl:a(t.URL_REDIRECT_AUTH_CALLBACK_PARAM_NAME),redirectAuthBackupCallbackUri:a(t.URL_REDIRECT_AUTH_BACKUP_CALLBACK_PARAM_NAME),redirectAuthInitiator:a(t.URL_REDIRECT_AUTH_INITIATOR_PARAM_NAME)}}function R(){return a(t.OIDC_IDP_STATE_ID_PARAM_NAME)}function S(){s(t.OIDC_IDP_STATE_ID_PARAM_NAME)}function h(){return a(t.SAML_IDP_STATE_ID_PARAM_NAME)}function f(){s(t.SAML_IDP_STATE_ID_PARAM_NAME)}function M(){return a(t.WSFED_IDP_STATE_ID_PARAM_NAME)}function C(){s(t.WSFED_IDP_STATE_ID_PARAM_NAME)}function U(){return a(t.SAML_IDP_USERNAME_PARAM_NAME)}function D(){s(t.SAML_IDP_USERNAME_PARAM_NAME)}function T(){return a(t.DESCOPE_IDP_INITIATED_PARAM_NAME)}function x(){s(t.DESCOPE_IDP_INITIATED_PARAM_NAME)}function g(){return a(t.SSO_APP_ID_PARAM_NAME)}function v(){return a(t.THIRD_PARTY_APP_ID_PARAM_NAME)}function N(){s(t.SSO_APP_ID_PARAM_NAME)}function w(){s(t.THIRD_PARTY_APP_ID_PARAM_NAME)}function O(){return a(t.THIRD_PARTY_APP_STATE_ID_PARAM_NAME)}function L(){s(t.THIRD_PARTY_APP_STATE_ID_PARAM_NAME)}function F(){return a(t.APPLICATION_SCOPES_PARAM_NAME)}function y(){s(t.APPLICATION_SCOPES_PARAM_NAME)}function b(){return a(t.OIDC_LOGIN_HINT_PARAM_NAME)}function k(){s(t.OIDC_LOGIN_HINT_PARAM_NAME)}function H(){return a(t.OIDC_PROMPT_PARAM_NAME)}function $(){s(t.OIDC_PROMPT_PARAM_NAME)}function j(){return a(t.OIDC_ERROR_REDIRECT_URI_PARAM_NAME)}function B(){s(t.OIDC_ERROR_REDIRECT_URI_PARAM_NAME)}function W(){return a(t.OIDC_RESOURCE_PARAM_NAME)}function q(){s(t.OIDC_RESOURCE_PARAM_NAME)}const K='*[name]:not([auto-focus="false"]):not([aria-hidden="true"])';exports.FOCUSABLE_INPUTS_SELECTOR=K,exports.camelCase=e=>e.replace(/-./g,(e=>e[1].toUpperCase())),exports.clearApplicationScopesParamFromUrl=y,exports.clearCodeFromUrl=m,exports.clearDescopeIDPInitiatedParamFromUrl=x,exports.clearExchangeErrorFromUrl=E,exports.clearIsPopupFromUrl=P,exports.clearOIDCErrorRedirectUriParamFromUrl=B,exports.clearOIDCIDPParamFromUrl=S,exports.clearOIDCLoginHintParamFromUrl=k,exports.clearOIDCPromptParamFromUrl=$,exports.clearOIDCResourceParamFromUrl=q,exports.clearPreviousExternalInputs=()=>{document.querySelectorAll('[data-hidden-input="true"]').forEach((e=>e.remove()))},exports.clearRunIdsFromUrl=u,exports.clearSAMLIDPParamFromUrl=f,exports.clearSAMLIDPUsernameParamFromUrl=D,exports.clearSSOAppIdParamFromUrl=N,exports.clearThirdPartyAppIdParamFromUrl=w,exports.clearThirdPartyAppStateIdParamFromUrl=L,exports.clearTokenFromUrl=d,exports.clearWSFedIDPParamFromUrl=C,exports.createIsChanged=(e,t)=>r=>e[r]!==t[r],exports.fetchContent=function(t,r){return e.__awaiter(this,void 0,void 0,(function*(){const e=yield fetch(t,{cache:"default"});if(!e.ok)throw Error(`Error fetching URL ${t} [${e.status}]`);return{body:yield e[r](),headers:Object.fromEntries(e.headers.entries())}}))},exports.getAnimationDirection=function(e,t){if(!t)return;const r=+e,n=+t;return Number.isNaN(r)||Number.isNaN(n)?void 0:r>n?o.Direction.forward:r<n?o.Direction.backward:void 0},exports.getApplicationScopesParamFromUrl=F,exports.getChromiumVersion=()=>{var e;const t=null===(e=null===navigator||void 0===navigator?void 0:navigator.userAgentData)||void 0===e?void 0:e.brands,r=null==t?void 0:t.find((({brand:e,version:t})=>"Chromium"===e&&parseFloat(t)));return r?r.version:0},exports.getCodeFromUrl=p,exports.getContentUrl=function({projectId:e,filename:t,assetsFolder:r=n.ASSETS_FOLDER,baseUrl:o}){const i=new URL(n.OVERRIDE_CONTENT_URL||o||n.BASE_CONTENT_URL);return i.pathname=((...e)=>e.join("/").replace(/\/+/g,"/"))(i.pathname,e,r,t),i.toString()},exports.getDescopeIDPInitiatedParamFromUrl=T,exports.getElementDescopeAttributes=e=>Array.from((null==e?void 0:e.attributes)||[]).reduce(((e,r)=>{var o;const n=null===(o=new RegExp(`^${t.DESCOPE_ATTRIBUTE_PREFIX}(\\S+)$`).exec(r.name))||void 0===o?void 0:o[1];return n?Object.assign(e,{[n]:r.value}):e}),{}),exports.getExchangeErrorFromUrl=_,exports.getFirstNonEmptyValue=(e,t)=>{const r=t.find((t=>e[t]));return r?e[r]:null},exports.getIsPopupFromUrl=A,exports.getOIDCErrorRedirectUriParamFromUrl=j,exports.getOIDCIDPParamFromUrl=R,exports.getOIDCLoginHintParamFromUrl=b,exports.getOIDCPromptParamFromUrl=H,exports.getOIDCResourceParamFromUrl=W,exports.getRedirectAuthFromUrl=I,exports.getRunIdsFromUrl=c,exports.getSAMLIDPParamFromUrl=h,exports.getSAMLIDPUsernameParamFromUrl=U,exports.getSSOAppIdParamFromUrl=g,exports.getScriptResultPath=function(e,r){const o=r?`${e}_${r}`:e;return`${t.SDK_SCRIPT_RESULTS_KEY}.${o}`},exports.getThirdPartyAppIdParamFromUrl=v,exports.getThirdPartyAppStateIdParamFromUrl=O,exports.getTokenFromUrl=l,exports.getUserLocale=function(e){if(e)return{locale:e.toLowerCase(),fallback:e.toLowerCase()};const t=navigator.language;return t?t.includes("-")?{locale:t.toLowerCase(),fallback:t.split("-")[0].toLowerCase()}:{locale:t.toLowerCase(),fallback:t.toLowerCase()}:{locale:"",fallback:""}},exports.getWSFedIDPParamFromUrl=M,exports.handleAutoFocus=(e,t,r)=>{if(!0===t||"skipFirstScreen"===t&&!r){const t=e.querySelector(K);setTimeout((()=>{null==t||t.focus()}))}},exports.handleReportValidityOnBlur=e=>{e.querySelectorAll("*[name]").forEach((t=>{t.addEventListener("blur",(()=>{var r;const o=()=>{var e;const r=t.focus;t.focus=()=>{},null===(e=t.reportValidity)||void 0===e||e.call(t),setTimeout((()=>{t.focus=r}))};if("true"===t.getAttribute("invalid")||(null===(r=t.value)||void 0===r?void 0:r.length))return void o();const n={timer:void 0},i=e=>{"true"===e.target.getAttribute("formnovalidate")&&(clearTimeout(n.timer),n.timer=void 0)};n.timer=setTimeout((()=>{e.removeEventListener("click",i),o(),n.timer=void 0}),150),e.addEventListener("click",i,{once:!0})}))}))},exports.handleUrlParams=(e,t)=>{const{executionId:r,stepId:o,executionFlowId:n}=c(e);if(n&&e!==n)return t.debug("Flow id does not match the execution flow id, skipping url params handling"),{ssoQueryParams:{}};(r||o)&&u();const i=l();i&&d();const a=p();a&&m();const s=A();s&&P();const K=_();K&&E();const{redirectAuthCodeChallenge:Y,redirectAuthCallbackUrl:V,redirectAuthBackupCallbackUri:G,redirectAuthInitiator:Q}=I(),X=R();X&&S();const z=h();z&&f();const J=M();J&&C();const Z=U();z&&D();const ee=T();ee&&x();const te=g();te&&N();const re=v();re&&w();const oe=O();oe&&L();const ne=F();ne&&y();const ie=b();ie&&k();const ae=H();ae&&$();const se=j();se&&B();const ce=W();ce&&q();return{executionId:r,stepId:o,token:i,code:a,isPopup:s,exchangeError:K,redirectAuthCodeChallenge:Y,redirectAuthCallbackUrl:V,redirectAuthBackupCallbackUri:G,redirectAuthInitiator:Q,ssoQueryParams:{oidcIdpStateId:X,samlIdpStateId:z,wsfedIdpStateId:J,samlIdpUsername:Z,descopeIdpInitiated:"true"===ee,ssoAppId:te,oidcLoginHint:ie,oidcPrompt:ae,oidcErrorRedirectUri:se,oidcResource:ce,thirdPartyAppId:re,thirdPartyAppStateId:oe,applicationScopes:ne}}},exports.injectSamlIdpForm=(e,t,r,o)=>{const n=document.createElement("form");n.method="POST",n.action=e,n.innerHTML=`\n <input type="hidden" role="saml-response" name="SAMLResponse" value="${t}" />\n <input type="hidden" role="saml-relay-state" name="RelayState" value="${r}" />\n <input style="display: none;" id="SAMLSubmitButton" type="submit" value="Continue" />\n `,document.body.appendChild(n),o(n)},exports.injectWsFedIdpForm=(e,t,r,o)=>{const n=document.createElement("form");n.method="POST",n.action=e;const i=(e,t)=>{const r=document.createElement("input");return r.type="hidden",r.name=e,r.value=t,r};n.appendChild(i("wa","wsignin1.0")),n.appendChild(i("wresult",t)),n.appendChild(i("wctx",r));const a=document.createElement("input");a.type="submit",a.id="WSFedSubmitButton",a.value="Continue",a.style.display="none",n.appendChild(a),document.body.appendChild(n),o(n)},exports.isChromium=function(){return/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)},exports.leadingDebounce=(e,t=100)=>{let r;return function(...o){r||e.apply(this,o),clearTimeout(r),r=setTimeout((()=>{r=null}),t)}},exports.openCenteredPopup=(e,t,r,o)=>{const n=void 0!==window.screenLeft?window.screenLeft:window.screen.left,i=void 0!==window.screenTop?window.screenTop:window.screen.top,a=((window.innerWidth||document.documentElement.clientWidth||window.screen.width)-r)/2+n,s=((window.innerHeight||document.documentElement.clientHeight||window.screen.height)-o)/2+i,c=function(){const e=navigator.userAgent||"",t=/\b(iPhone)\b/.test(e),r=/Safari/.test(e)&&!/CriOS|FxiOS|OPiOS|EdgiOS|Chrome|Chromium/.test(e);return t&&r}()?"about:blank":"",u=window.open(c,t,`width=${r},height=${o},top=${s},left=${a},scrollbars=yes,resizable=yes`);return u.location.href=e,u.focus(),u},exports.shouldHandleMarkdown=e=>i.includes(e),exports.showFirstScreenOnExecutionInit=(e,{oidcIdpStateId:t,samlIdpStateId:r,wsfedIdpStateId:o,samlIdpUsername:n,ssoAppId:i,oidcLoginHint:a,oidcPrompt:s,oidcErrorRedirectUri:c,oidcResource:u,thirdPartyAppId:l,thirdPartyAppStateId:d,applicationScopes:p})=>!(!e||t||r||o||n||i||a||s||c||u||l||d||p),exports.submitForm=e=>null==e?void 0:e.submit(),exports.timeoutPromise=function(e,t,r){return new Promise(((o,n)=>{let i=!1;const a=setTimeout((()=>{i=!0,void 0!==r?o(r):n(new Error(`Promise timed out after ${e} ms`))}),e);t.then((e=>{i||(clearTimeout(a),o(e))})).catch((e=>{i||(clearTimeout(a),n(e))}))}))},exports.transformScreenInputs=e=>{const t=Object.assign({},e);return e.inboundAppApproveScopes&&(t.thirdPartyAppApproveScopes=e.inboundAppApproveScopes),t},exports.transformStepStateForCustomScreen=e=>{var t,o,n;const i=(a=e.screenState,s=(e,t)=>r.EXCLUDED_STATE_KEYS.includes(t)||t.startsWith("_"),Object.fromEntries(Object.entries(a).filter((([e,t])=>!s(t,e)))));var a,s;const{screenState:{errorText:c,errorType:u}}=e;return(c||u)&&(i.error={text:c,type:u}),e.action&&(i.action=e.action),(null===(n=null===(o=null===(t=e.screenState)||void 0===t?void 0:t.componentsConfig)||void 0===o?void 0:o.thirdPartyAppApproveScopes)||void 0===n?void 0:n.data)&&(i.inboundAppApproveScopes=e.screenState.componentsConfig.thirdPartyAppApproveScopes.data),i},exports.withMemCache=e=>{let t,r;return Object.assign(((...o)=>{return t&&(i=o,(n=t).length===i.length&&n.every(((e,t)=>e===i[t])))||(t=o,r=e(...o)),r;var n,i}),{reset:()=>{t=void 0,r=void 0}})},exports.withRetry=function(t,r,o){return(...n)=>e.__awaiter(this,void 0,void 0,(function*(){let e;const i=o+1;for(let a=0;a<i;a++)try{return yield t(...n)}catch(t){e=t,a<o&&(yield new Promise((e=>{setTimeout(e,r*Math.pow(2,a+1))})))}throw e}))};
1
+ "use strict";var e=require("tslib"),t=require("../constants/index.js"),r=require("../constants/customScreens.js"),o=require("../types.js"),n=require("../constants/content.js");const i=["descope-enriched-text"];function a(e){return new URLSearchParams(window.location.search).get(e)}function s(e){if(window.history.replaceState&&a(e)){const t=new URL(window.location.href),r=new URLSearchParams(t.search);r.delete(e),t.search=r.toString(),window.history.replaceState({},"",t.toString())}}const c=e=>{let[r="",o=""]=(a(t.URL_RUN_IDS_PARAM_NAME)||"").split("_");const n=(e=>{var t;return(null===(t=/(.*)\|#\|.*/.exec(e))||void 0===t?void 0:t[1])||""})(r);return(!e||n&&n!==e)&&(r="",o=""),{executionId:r,stepId:o,executionFlowId:n}};function u(){s(t.URL_RUN_IDS_PARAM_NAME)}function l(){return a(t.URL_TOKEN_PARAM_NAME)||void 0}function d(){s(t.URL_TOKEN_PARAM_NAME)}function p(){return a(t.URL_CODE_PARAM_NAME)||void 0}function A(){return"popup"===a(t.URL_REDIRECT_MODE_PARAM_NAME)}function _(){return a(t.URL_ERR_PARAM_NAME)||void 0}function m(){s(t.URL_CODE_PARAM_NAME)}function P(){s(t.URL_REDIRECT_MODE_PARAM_NAME)}function E(){s(t.URL_ERR_PARAM_NAME)}function I(){return{redirectAuthCodeChallenge:a(t.URL_REDIRECT_AUTH_CHALLENGE_PARAM_NAME),redirectAuthCallbackUrl:a(t.URL_REDIRECT_AUTH_CALLBACK_PARAM_NAME),redirectAuthBackupCallbackUri:a(t.URL_REDIRECT_AUTH_BACKUP_CALLBACK_PARAM_NAME),redirectAuthInitiator:a(t.URL_REDIRECT_AUTH_INITIATOR_PARAM_NAME)}}function R(){return a(t.OIDC_IDP_STATE_ID_PARAM_NAME)}function S(){s(t.OIDC_IDP_STATE_ID_PARAM_NAME)}function h(){return a(t.SAML_IDP_STATE_ID_PARAM_NAME)}function f(){s(t.SAML_IDP_STATE_ID_PARAM_NAME)}function M(){return a(t.WSFED_IDP_STATE_ID_PARAM_NAME)}function C(){s(t.WSFED_IDP_STATE_ID_PARAM_NAME)}function U(){return a(t.SAML_IDP_USERNAME_PARAM_NAME)}function D(){s(t.SAML_IDP_USERNAME_PARAM_NAME)}function T(){return a(t.DESCOPE_IDP_INITIATED_PARAM_NAME)}function x(){s(t.DESCOPE_IDP_INITIATED_PARAM_NAME)}function g(){return a(t.SSO_APP_ID_PARAM_NAME)}function v(){return a(t.THIRD_PARTY_APP_ID_PARAM_NAME)}function N(){s(t.SSO_APP_ID_PARAM_NAME)}function w(){s(t.THIRD_PARTY_APP_ID_PARAM_NAME)}function O(){return a(t.THIRD_PARTY_APP_STATE_ID_PARAM_NAME)}function L(){s(t.THIRD_PARTY_APP_STATE_ID_PARAM_NAME)}function F(){return a(t.APPLICATION_SCOPES_PARAM_NAME)}function y(){s(t.APPLICATION_SCOPES_PARAM_NAME)}function b(){return a(t.OIDC_LOGIN_HINT_PARAM_NAME)}function k(){s(t.OIDC_LOGIN_HINT_PARAM_NAME)}function H(){return a(t.OIDC_PROMPT_PARAM_NAME)}function $(){s(t.OIDC_PROMPT_PARAM_NAME)}function j(){return a(t.OIDC_ERROR_REDIRECT_URI_PARAM_NAME)}function B(){s(t.OIDC_ERROR_REDIRECT_URI_PARAM_NAME)}function W(){return a(t.OIDC_RESOURCE_PARAM_NAME)}function q(){s(t.OIDC_RESOURCE_PARAM_NAME)}const K='*[name]:not([auto-focus="false"]):not([aria-hidden="true"])';exports.FOCUSABLE_INPUTS_SELECTOR=K,exports.camelCase=e=>e.replace(/-./g,(e=>e[1].toUpperCase())),exports.clearApplicationScopesParamFromUrl=y,exports.clearCodeFromUrl=m,exports.clearDescopeIDPInitiatedParamFromUrl=x,exports.clearExchangeErrorFromUrl=E,exports.clearIsPopupFromUrl=P,exports.clearOIDCErrorRedirectUriParamFromUrl=B,exports.clearOIDCIDPParamFromUrl=S,exports.clearOIDCLoginHintParamFromUrl=k,exports.clearOIDCPromptParamFromUrl=$,exports.clearOIDCResourceParamFromUrl=q,exports.clearPreviousExternalInputs=()=>{document.querySelectorAll('[data-hidden-input="true"]').forEach((e=>e.remove()))},exports.clearRunIdsFromUrl=u,exports.clearSAMLIDPParamFromUrl=f,exports.clearSAMLIDPUsernameParamFromUrl=D,exports.clearSSOAppIdParamFromUrl=N,exports.clearThirdPartyAppIdParamFromUrl=w,exports.clearThirdPartyAppStateIdParamFromUrl=L,exports.clearTokenFromUrl=d,exports.clearWSFedIDPParamFromUrl=C,exports.createIsChanged=(e,t)=>r=>e[r]!==t[r],exports.fetchContent=function(t,r){return e.__awaiter(this,void 0,void 0,(function*(){const e=yield fetch(t,{cache:"default"});if(!e.ok)throw Error(`Error fetching URL ${t} [${e.status}]`);return{body:yield e[r](),headers:Object.fromEntries(e.headers.entries())}}))},exports.getAnimationDirection=function(e,t){if(!t)return;const r=+e,n=+t;return Number.isNaN(r)||Number.isNaN(n)?void 0:r>n?o.Direction.forward:r<n?o.Direction.backward:void 0},exports.getApplicationScopesParamFromUrl=F,exports.getChromiumVersion=()=>{var e;const t=null===(e=null===navigator||void 0===navigator?void 0:navigator.userAgentData)||void 0===e?void 0:e.brands,r=null==t?void 0:t.find((({brand:e,version:t})=>"Chromium"===e&&parseFloat(t)));return r?r.version:0},exports.getCodeFromUrl=p,exports.getContentUrl=function({projectId:e,filename:t,assetsFolder:r=n.ASSETS_FOLDER,baseUrl:o}){const i=new URL(n.OVERRIDE_CONTENT_URL||o||n.BASE_CONTENT_URL);return i.pathname=((...e)=>e.join("/").replace(/\/+/g,"/"))(i.pathname,e,r,t),i.toString()},exports.getDescopeIDPInitiatedParamFromUrl=T,exports.getElementDescopeAttributes=e=>Array.from((null==e?void 0:e.attributes)||[]).reduce(((e,r)=>{var o;const n=null===(o=new RegExp(`^${t.DESCOPE_ATTRIBUTE_PREFIX}(\\S+)$`).exec(r.name))||void 0===o?void 0:o[1];return n?Object.assign(e,{[n]:r.value}):e}),{}),exports.getExchangeErrorFromUrl=_,exports.getFirstNonEmptyValue=(e,t)=>{const r=t.find((t=>e[t]));return r?e[r]:null},exports.getIsPopupFromUrl=A,exports.getOIDCErrorRedirectUriParamFromUrl=j,exports.getOIDCIDPParamFromUrl=R,exports.getOIDCLoginHintParamFromUrl=b,exports.getOIDCPromptParamFromUrl=H,exports.getOIDCResourceParamFromUrl=W,exports.getRedirectAuthFromUrl=I,exports.getRunIdsFromUrl=c,exports.getSAMLIDPParamFromUrl=h,exports.getSAMLIDPUsernameParamFromUrl=U,exports.getSSOAppIdParamFromUrl=g,exports.getScriptResultPath=function(e,r){const o=r?`${e}_${r}`:e;return`${t.SDK_SCRIPT_RESULTS_KEY}.${o}`},exports.getThirdPartyAppIdParamFromUrl=v,exports.getThirdPartyAppStateIdParamFromUrl=O,exports.getTokenFromUrl=l,exports.getUserLocale=function(e){if(e)return{locale:e.toLowerCase(),fallback:e.toLowerCase()};const t=navigator.language;return t?t.includes("-")?{locale:t.toLowerCase(),fallback:t.split("-")[0].toLowerCase()}:{locale:t.toLowerCase(),fallback:t.toLowerCase()}:{locale:"",fallback:""}},exports.getWSFedIDPParamFromUrl=M,exports.handleAutoFocus=(e,t,r)=>{if(!0===t||"skipFirstScreen"===t&&!r){const t=e.querySelector(K);setTimeout((()=>{null==t||t.focus()}))}},exports.handleReportValidityOnBlur=e=>{e.querySelectorAll("*[name]").forEach((t=>{t.addEventListener("blur",(()=>{var r;const o=()=>{var e;const r=t.focus;t.focus=()=>{},null===(e=t.reportValidity)||void 0===e||e.call(t),setTimeout((()=>{t.focus=r}))};if("true"===t.getAttribute("invalid")||(null===(r=t.value)||void 0===r?void 0:r.length))return void o();const n={timer:void 0},i=e=>{"true"===e.target.getAttribute("formnovalidate")&&(clearTimeout(n.timer),n.timer=void 0)};n.timer=setTimeout((()=>{e.removeEventListener("click",i),o(),n.timer=void 0}),150),e.addEventListener("click",i,{once:!0})}))}))},exports.handleUrlParams=(e,t)=>{const{executionId:r,stepId:o,executionFlowId:n}=c(e);if(n&&e!==n)return t.debug("Flow id does not match the execution flow id, skipping url params handling"),{ssoQueryParams:{}};(r||o)&&u();const i=l();i&&d();const a=p();a&&m();const s=A();s&&P();const K=_();K&&E();const{redirectAuthCodeChallenge:Y,redirectAuthCallbackUrl:V,redirectAuthBackupCallbackUri:G,redirectAuthInitiator:Q}=I(),X=R();X&&S();const z=h();z&&f();const J=M();J&&C();const Z=U();z&&D();const ee=T();ee&&x();const te=g();te&&N();const re=v();re&&w();const oe=O();oe&&L();const ne=F();ne&&y();const ie=b();ie&&k();const ae=H();ae&&$();const se=j();se&&B();const ce=W();ce&&q();return{executionId:r,stepId:o,token:i,code:a,isPopup:s,exchangeError:K,redirectAuthCodeChallenge:Y,redirectAuthCallbackUrl:V,redirectAuthBackupCallbackUri:G,redirectAuthInitiator:Q,ssoQueryParams:{oidcIdpStateId:X,samlIdpStateId:z,wsfedIdpStateId:J,samlIdpUsername:Z,descopeIdpInitiated:"true"===ee,ssoAppId:te,oidcLoginHint:ie,oidcPrompt:ae,oidcErrorRedirectUri:se,oidcResource:ce,thirdPartyAppId:re,thirdPartyAppStateId:oe,applicationScopes:ne}}},exports.injectSamlIdpForm=(e,t,r,o)=>{const n=document.createElement("form");n.method="POST",n.action=e,n.innerHTML=`\n <input type="hidden" role="saml-response" name="SAMLResponse" value="${t}" />\n <input type="hidden" role="saml-relay-state" name="RelayState" value="${r}" />\n <input style="display: none;" id="SAMLSubmitButton" type="submit" value="Continue" />\n `,document.body.appendChild(n),o(n)},exports.injectWsFedIdpForm=(e,t,r,o)=>{const n=document.createElement("form");n.method="POST",n.action=e;const i=(e,t)=>{const r=document.createElement("input");return r.type="hidden",r.name=e,r.value=t,r};n.appendChild(i("wa","wsignin1.0")),n.appendChild(i("wresult",t)),n.appendChild(i("wctx",r));const a=document.createElement("input");a.type="submit",a.id="WSFedSubmitButton",a.value="Continue",a.style.display="none",n.appendChild(a),document.body.appendChild(n),o(n)},exports.isChromium=function(){return/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)},exports.leadingDebounce=(e,t=100)=>{let r;return function(...o){r||e.apply(this,o),clearTimeout(r),r=setTimeout((()=>{r=null}),t)}},exports.openCenteredPopup=(e,t,r,o)=>{const n=void 0!==window.screenLeft?window.screenLeft:window.screen.left,i=void 0!==window.screenTop?window.screenTop:window.screen.top,a=((window.innerWidth||document.documentElement.clientWidth||window.screen.width)-r)/2+n,s=((window.innerHeight||document.documentElement.clientHeight||window.screen.height)-o)/2+i,c=function(){const e=navigator.userAgent||"",t=/\b(iPhone)\b/.test(e),r=/Safari/.test(e)&&!/CriOS|FxiOS|OPiOS|EdgiOS|Chrome|Chromium/.test(e);return t&&r}()?"about:blank":"",u=window.open(c,t,`width=${r},height=${o},top=${s},left=${a},scrollbars=yes,resizable=yes`);return u.location.href=e,u.focus(),u},exports.shouldHandleMarkdown=e=>i.includes(e),exports.showFirstScreenOnExecutionInit=(e,{oidcIdpStateId:t,samlIdpStateId:r,wsfedIdpStateId:o,samlIdpUsername:n,ssoAppId:i,oidcLoginHint:a,oidcPrompt:s,oidcErrorRedirectUri:c,oidcResource:u,thirdPartyAppId:l,thirdPartyAppStateId:d,applicationScopes:p})=>!(!e||t||r||o||n||i||a||s||c||u||l||d||p),exports.submitForm=e=>null==e?void 0:e.submit(),exports.timeoutPromise=function(e,t,r){return new Promise(((o,n)=>{let i=!1;const a=setTimeout((()=>{i=!0,void 0!==r?o(r):n(new Error(`Promise timed out after ${e} ms`))}),e);t.then((e=>{i||(clearTimeout(a),o(e))})).catch((e=>{i||(clearTimeout(a),n(e))}))}))},exports.transformScreenInputs=e=>{const t=Object.assign({},e);return e.inboundAppApproveScopes&&(t.thirdPartyAppApproveScopes=e.inboundAppApproveScopes),t},exports.transformStepStateForCustomScreen=e=>{var t,o,n;const i=(a=e.screenState,s=(e,t)=>r.EXCLUDED_STATE_KEYS.includes(t)||t.startsWith("_"),Object.fromEntries(Object.entries(a).filter((([e,t])=>!s(t,e)))));var a,s;const{screenState:{errorText:c,errorType:u}}=e;return(c||u)&&(i.error={text:c,type:u}),e.action&&(i.action=e.action),(null===(n=null===(o=null===(t=e.screenState)||void 0===t?void 0:t.componentsConfig)||void 0===o?void 0:o.thirdPartyAppApproveScopes)||void 0===n?void 0:n.data)&&(i.inboundAppApproveScopes=e.screenState.componentsConfig.thirdPartyAppApproveScopes.data),i},exports.withMemCache=e=>{let t,r;return Object.assign(((...o)=>{return t&&(i=o,(n=t).length===i.length&&n.every(((e,t)=>e===i[t])))||(t=o,r=e(...o)),r;var n,i}),{reset:()=>{t=void 0,r=void 0}})},exports.withRetry=function(t,r,o){return(...n)=>e.__awaiter(this,void 0,void 0,(function*(){let e;const i=o+1;for(let a=0;a<i;a++)try{return yield t(...n)}catch(t){e=t,a<o&&(yield new Promise((e=>{setTimeout(e,r*Math.pow(2,a+1))})))}throw e}))};
2
2
  //# sourceMappingURL=helpers.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"helpers.js","sources":["../../../src/lib/helpers/helpers.ts"],"sourcesContent":["import {\n ASSETS_FOLDER,\n BASE_CONTENT_URL,\n DESCOPE_ATTRIBUTE_PREFIX,\n URL_CODE_PARAM_NAME,\n URL_ERR_PARAM_NAME,\n URL_RUN_IDS_PARAM_NAME,\n URL_TOKEN_PARAM_NAME,\n URL_REDIRECT_AUTH_CHALLENGE_PARAM_NAME,\n URL_REDIRECT_AUTH_CALLBACK_PARAM_NAME,\n URL_REDIRECT_AUTH_BACKUP_CALLBACK_PARAM_NAME,\n URL_REDIRECT_AUTH_INITIATOR_PARAM_NAME,\n OIDC_IDP_STATE_ID_PARAM_NAME,\n SAML_IDP_STATE_ID_PARAM_NAME,\n WSFED_IDP_STATE_ID_PARAM_NAME,\n SAML_IDP_USERNAME_PARAM_NAME,\n SSO_APP_ID_PARAM_NAME,\n OIDC_LOGIN_HINT_PARAM_NAME,\n DESCOPE_IDP_INITIATED_PARAM_NAME,\n OVERRIDE_CONTENT_URL,\n OIDC_PROMPT_PARAM_NAME,\n OIDC_RESOURCE_PARAM_NAME,\n OIDC_ERROR_REDIRECT_URI_PARAM_NAME,\n THIRD_PARTY_APP_ID_PARAM_NAME,\n THIRD_PARTY_APP_STATE_ID_PARAM_NAME,\n APPLICATION_SCOPES_PARAM_NAME,\n SDK_SCRIPT_RESULTS_KEY,\n URL_REDIRECT_MODE_PARAM_NAME,\n} from '../constants';\nimport { EXCLUDED_STATE_KEYS } from '../constants/customScreens';\nimport {\n AutoFocusOptions,\n CustomScreenState,\n Direction,\n Locale,\n SSOQueryParams,\n StepState,\n} from '../types';\n\nconst MD_COMPONENTS = ['descope-enriched-text'];\n\n/**\n * Wraps an async function with retry logic\n * @param fn - The async function to wrap\n * @param timeoutMs - Time to wait between retries in milliseconds\n * @param maxRetries - Maximum number of retry attempts\n * @returns A new function with retry logic\n */\nexport function withRetry<TArgs extends any[], TReturn>(\n fn: (...args: TArgs) => Promise<TReturn>,\n timeoutMs: number,\n maxRetries: number,\n): (...args: TArgs) => Promise<TReturn> {\n return async (...args: TArgs): Promise<TReturn> => {\n let lastError: any;\n const totalAttempts = maxRetries + 1; // initial attempt + retries\n\n // eslint-disable-next-line no-plusplus\n for (let attempt = 0; attempt < totalAttempts; attempt++) {\n try {\n // eslint-disable-next-line no-await-in-loop\n return await fn(...args);\n } catch (error) {\n lastError = error;\n\n // Don't wait after the last attempt\n if (attempt < maxRetries) {\n // eslint-disable-next-line no-await-in-loop\n await new Promise((resolve) => {\n setTimeout(resolve, timeoutMs * Math.pow(2, attempt + 1));\n });\n }\n }\n }\n\n // All attempts failed, throw the last error\n throw lastError;\n };\n}\n\nfunction getUrlParam(paramName: string) {\n const urlParams = new URLSearchParams(window.location.search);\n\n return urlParams.get(paramName);\n}\n\nfunction getFlowUrlParam() {\n return getUrlParam(URL_RUN_IDS_PARAM_NAME);\n}\n\nfunction setFlowUrlParam(id: string) {\n if (window.history.pushState && id !== getFlowUrlParam()) {\n const newUrl = new URL(window.location.href);\n const search = new URLSearchParams(newUrl.search);\n search.set(URL_RUN_IDS_PARAM_NAME, id);\n newUrl.search = search.toString();\n window.history.pushState({}, '', newUrl.toString());\n }\n}\n\nfunction resetUrlParam(paramName: string) {\n if (window.history.replaceState && getUrlParam(paramName)) {\n const newUrl = new URL(window.location.href);\n const search = new URLSearchParams(newUrl.search);\n search.delete(paramName);\n newUrl.search = search.toString();\n window.history.replaceState({}, '', newUrl.toString());\n }\n}\n\nconst getFlowIdFromExecId = (executionId: string) => {\n const regex = /(.*)---.*/;\n return regex.exec(executionId)?.[1] || '';\n};\n\nexport async function fetchContent<T extends 'text' | 'json'>(\n url: string,\n returnType: T,\n): Promise<{\n body: T extends 'json' ? Record<string, any> : string;\n headers: Record<string, string>;\n}> {\n const res = await fetch(url, { cache: 'default' });\n if (!res.ok) {\n throw Error(`Error fetching URL ${url} [${res.status}]`);\n }\n\n return {\n body: await res[returnType || 'text'](),\n headers: Object.fromEntries(res.headers.entries()),\n };\n}\n\nconst pathJoin = (...paths: string[]) => paths.join('/').replace(/\\/+/g, '/'); // preventing duplicate separators\n\nexport function getContentUrl({\n projectId,\n filename,\n assetsFolder = ASSETS_FOLDER,\n baseUrl,\n}: {\n projectId: string;\n filename: string;\n assetsFolder?: string;\n baseUrl?: string;\n}) {\n const url = new URL(OVERRIDE_CONTENT_URL || baseUrl || BASE_CONTENT_URL);\n url.pathname = pathJoin(url.pathname, projectId, assetsFolder, filename);\n\n return url.toString();\n}\n\nexport function getAnimationDirection(\n currentIdxStr: string,\n prevIdxStr: string,\n) {\n if (!prevIdxStr) return undefined;\n\n const currentIdx = +currentIdxStr;\n const prevIdx = +prevIdxStr;\n\n if (Number.isNaN(currentIdx) || Number.isNaN(prevIdx)) return undefined;\n if (currentIdx > prevIdx) return Direction.forward;\n if (currentIdx < prevIdx) return Direction.backward;\n return undefined;\n}\n\nexport const getRunIdsFromUrl = (flowId: string) => {\n let [executionId = '', stepId = ''] = (getFlowUrlParam() || '').split('_');\n const executionFlowId = getFlowIdFromExecId(executionId);\n\n // if the flow id does not match, this execution id is not for this flow\n if (!flowId || (executionFlowId && executionFlowId !== flowId)) {\n executionId = '';\n stepId = '';\n }\n\n return { executionId, stepId, executionFlowId };\n};\n\nexport const setRunIdsOnUrl = (executionId: string, stepId: string) => {\n setFlowUrlParam([executionId, stepId].join('_'));\n};\n\nexport function isChromium() {\n return (\n /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor)\n );\n}\n\n// Detect Safari running on iPhone specifically.\nfunction isIphoneSafari() {\n const ua = navigator.userAgent || '';\n const isIphone = /\\b(iPhone)\\b/.test(ua);\n // Safari UA contains 'Safari' and usually 'Version/X', exclude other iOS browsers\n const isSafari =\n /Safari/.test(ua) && !/CriOS|FxiOS|OPiOS|EdgiOS|Chrome|Chromium/.test(ua);\n\n return isIphone && isSafari;\n}\n\nexport function clearRunIdsFromUrl() {\n resetUrlParam(URL_RUN_IDS_PARAM_NAME);\n}\n\nexport function getTokenFromUrl() {\n return getUrlParam(URL_TOKEN_PARAM_NAME) || undefined;\n}\n\nexport function clearTokenFromUrl() {\n resetUrlParam(URL_TOKEN_PARAM_NAME);\n}\n\nexport function getCodeFromUrl() {\n return getUrlParam(URL_CODE_PARAM_NAME) || undefined;\n}\n\nexport function getIsPopupFromUrl() {\n return getUrlParam(URL_REDIRECT_MODE_PARAM_NAME) === 'popup';\n}\n\nexport function getExchangeErrorFromUrl() {\n return getUrlParam(URL_ERR_PARAM_NAME) || undefined;\n}\n\nexport function clearCodeFromUrl() {\n resetUrlParam(URL_CODE_PARAM_NAME);\n}\n\nexport function clearIsPopupFromUrl() {\n resetUrlParam(URL_REDIRECT_MODE_PARAM_NAME);\n}\n\nexport function clearExchangeErrorFromUrl() {\n resetUrlParam(URL_ERR_PARAM_NAME);\n}\n\nexport function getRedirectAuthFromUrl() {\n const redirectAuthCodeChallenge = getUrlParam(\n URL_REDIRECT_AUTH_CHALLENGE_PARAM_NAME,\n );\n const redirectAuthCallbackUrl = getUrlParam(\n URL_REDIRECT_AUTH_CALLBACK_PARAM_NAME,\n );\n const redirectAuthBackupCallbackUri = getUrlParam(\n URL_REDIRECT_AUTH_BACKUP_CALLBACK_PARAM_NAME,\n );\n const redirectAuthInitiator = getUrlParam(\n URL_REDIRECT_AUTH_INITIATOR_PARAM_NAME,\n );\n return {\n redirectAuthCodeChallenge,\n redirectAuthCallbackUrl,\n redirectAuthBackupCallbackUri,\n redirectAuthInitiator,\n };\n}\n\nexport function getOIDCIDPParamFromUrl() {\n return getUrlParam(OIDC_IDP_STATE_ID_PARAM_NAME);\n}\n\nexport function clearOIDCIDPParamFromUrl() {\n resetUrlParam(OIDC_IDP_STATE_ID_PARAM_NAME);\n}\n\nexport function getSAMLIDPParamFromUrl() {\n return getUrlParam(SAML_IDP_STATE_ID_PARAM_NAME);\n}\n\nexport function clearSAMLIDPParamFromUrl() {\n resetUrlParam(SAML_IDP_STATE_ID_PARAM_NAME);\n}\n\nexport function getWSFedIDPParamFromUrl() {\n return getUrlParam(WSFED_IDP_STATE_ID_PARAM_NAME);\n}\n\nexport function clearWSFedIDPParamFromUrl() {\n resetUrlParam(WSFED_IDP_STATE_ID_PARAM_NAME);\n}\n\nexport function getSAMLIDPUsernameParamFromUrl() {\n return getUrlParam(SAML_IDP_USERNAME_PARAM_NAME);\n}\n\nexport function clearSAMLIDPUsernameParamFromUrl() {\n resetUrlParam(SAML_IDP_USERNAME_PARAM_NAME);\n}\n\nexport function getDescopeIDPInitiatedParamFromUrl() {\n return getUrlParam(DESCOPE_IDP_INITIATED_PARAM_NAME);\n}\n\nexport function clearDescopeIDPInitiatedParamFromUrl() {\n resetUrlParam(DESCOPE_IDP_INITIATED_PARAM_NAME);\n}\n\nexport function getSSOAppIdParamFromUrl() {\n return getUrlParam(SSO_APP_ID_PARAM_NAME);\n}\n\nexport function getThirdPartyAppIdParamFromUrl() {\n return getUrlParam(THIRD_PARTY_APP_ID_PARAM_NAME);\n}\n\nexport function clearSSOAppIdParamFromUrl() {\n resetUrlParam(SSO_APP_ID_PARAM_NAME);\n}\n\nexport function clearThirdPartyAppIdParamFromUrl() {\n resetUrlParam(THIRD_PARTY_APP_ID_PARAM_NAME);\n}\n\nexport function getThirdPartyAppStateIdParamFromUrl() {\n return getUrlParam(THIRD_PARTY_APP_STATE_ID_PARAM_NAME);\n}\n\nexport function clearThirdPartyAppStateIdParamFromUrl() {\n resetUrlParam(THIRD_PARTY_APP_STATE_ID_PARAM_NAME);\n}\n\nexport function getApplicationScopesParamFromUrl() {\n return getUrlParam(APPLICATION_SCOPES_PARAM_NAME);\n}\n\nexport function clearApplicationScopesParamFromUrl() {\n resetUrlParam(APPLICATION_SCOPES_PARAM_NAME);\n}\n\nexport function getOIDCLoginHintParamFromUrl() {\n return getUrlParam(OIDC_LOGIN_HINT_PARAM_NAME);\n}\n\nexport function clearOIDCLoginHintParamFromUrl() {\n resetUrlParam(OIDC_LOGIN_HINT_PARAM_NAME);\n}\n\nexport function getOIDCPromptParamFromUrl() {\n return getUrlParam(OIDC_PROMPT_PARAM_NAME);\n}\n\nexport function clearOIDCPromptParamFromUrl() {\n resetUrlParam(OIDC_PROMPT_PARAM_NAME);\n}\n\nexport function getOIDCErrorRedirectUriParamFromUrl() {\n return getUrlParam(OIDC_ERROR_REDIRECT_URI_PARAM_NAME);\n}\n\nexport function clearOIDCErrorRedirectUriParamFromUrl() {\n resetUrlParam(OIDC_ERROR_REDIRECT_URI_PARAM_NAME);\n}\n\nexport function getOIDCResourceParamFromUrl() {\n return getUrlParam(OIDC_RESOURCE_PARAM_NAME);\n}\n\nexport function clearOIDCResourceParamFromUrl() {\n resetUrlParam(OIDC_RESOURCE_PARAM_NAME);\n}\n\nexport const camelCase = (s: string) =>\n s.replace(/-./g, (x) => x[1].toUpperCase());\n\nexport const createIsChanged =\n <T extends Record<string, any>>(state: T, prevState: T) =>\n (attrName: keyof T) =>\n state[attrName] !== prevState[attrName];\n\nexport const getElementDescopeAttributes = (ele: HTMLElement) =>\n Array.from(ele?.attributes || []).reduce((acc, attr) => {\n const descopeAttrName = new RegExp(\n `^${DESCOPE_ATTRIBUTE_PREFIX}(\\\\S+)$`,\n ).exec(attr.name)?.[1];\n\n return !descopeAttrName\n ? acc\n : Object.assign(acc, { [descopeAttrName]: attr.value });\n }, {});\n\nexport const getFlowConfig = (config: Record<string, any>, flowId: string) =>\n config?.flows?.[flowId] || {};\n\nexport const handleUrlParams = (\n flowId: string,\n logger: { debug: (...data: any[]) => void },\n) => {\n const { executionId, stepId, executionFlowId } = getRunIdsFromUrl(flowId);\n\n // if the flow id does not match, we do not want to read & remove any query params\n // because it's probably belongs to another flow\n if (executionFlowId && flowId !== executionFlowId) {\n logger.debug(\n 'Flow id does not match the execution flow id, skipping url params handling',\n );\n return { ssoQueryParams: {} };\n }\n\n if (executionId || stepId) {\n clearRunIdsFromUrl();\n }\n\n const token = getTokenFromUrl();\n if (token) {\n clearTokenFromUrl();\n }\n\n const code = getCodeFromUrl();\n if (code) {\n clearCodeFromUrl();\n }\n\n // this is used for oauth when we want to open the provider login page in a new tab\n const isPopup = getIsPopupFromUrl();\n if (isPopup) {\n clearIsPopupFromUrl();\n }\n\n const exchangeError = getExchangeErrorFromUrl();\n if (exchangeError) {\n clearExchangeErrorFromUrl();\n }\n\n // these query params are retained to allow the flow to be refreshed\n // without losing the redirect auth state\n const {\n redirectAuthCodeChallenge,\n redirectAuthCallbackUrl,\n redirectAuthBackupCallbackUri,\n redirectAuthInitiator,\n } = getRedirectAuthFromUrl();\n\n const oidcIdpStateId = getOIDCIDPParamFromUrl();\n if (oidcIdpStateId) {\n clearOIDCIDPParamFromUrl();\n }\n\n const samlIdpStateId = getSAMLIDPParamFromUrl();\n if (samlIdpStateId) {\n clearSAMLIDPParamFromUrl();\n }\n\n const wsfedIdpStateId = getWSFedIDPParamFromUrl();\n if (wsfedIdpStateId) {\n clearWSFedIDPParamFromUrl();\n }\n\n const samlIdpUsername = getSAMLIDPUsernameParamFromUrl();\n if (samlIdpStateId) {\n clearSAMLIDPUsernameParamFromUrl();\n }\n\n const descopeIdpInitiated = getDescopeIDPInitiatedParamFromUrl();\n if (descopeIdpInitiated) {\n clearDescopeIDPInitiatedParamFromUrl();\n }\n\n const ssoAppId = getSSOAppIdParamFromUrl();\n if (ssoAppId) {\n clearSSOAppIdParamFromUrl();\n }\n\n const thirdPartyAppId = getThirdPartyAppIdParamFromUrl();\n if (thirdPartyAppId) {\n clearThirdPartyAppIdParamFromUrl();\n }\n\n const thirdPartyAppStateId = getThirdPartyAppStateIdParamFromUrl();\n if (thirdPartyAppStateId) {\n clearThirdPartyAppStateIdParamFromUrl();\n }\n\n const applicationScopes = getApplicationScopesParamFromUrl();\n if (applicationScopes) {\n clearApplicationScopesParamFromUrl();\n }\n\n const oidcLoginHint = getOIDCLoginHintParamFromUrl();\n if (oidcLoginHint) {\n clearOIDCLoginHintParamFromUrl();\n }\n\n const oidcPrompt = getOIDCPromptParamFromUrl();\n if (oidcPrompt) {\n clearOIDCPromptParamFromUrl();\n }\n\n const oidcErrorRedirectUri = getOIDCErrorRedirectUriParamFromUrl();\n if (oidcErrorRedirectUri) {\n clearOIDCErrorRedirectUriParamFromUrl();\n }\n\n const oidcResource = getOIDCResourceParamFromUrl();\n if (oidcResource) {\n clearOIDCResourceParamFromUrl();\n }\n\n const idpInitiatedVal = descopeIdpInitiated === 'true';\n\n return {\n executionId,\n stepId,\n token,\n code,\n isPopup,\n exchangeError,\n redirectAuthCodeChallenge,\n redirectAuthCallbackUrl,\n redirectAuthBackupCallbackUri,\n redirectAuthInitiator,\n ssoQueryParams: {\n oidcIdpStateId,\n samlIdpStateId,\n wsfedIdpStateId,\n samlIdpUsername,\n descopeIdpInitiated: idpInitiatedVal,\n ssoAppId,\n oidcLoginHint,\n oidcPrompt,\n oidcErrorRedirectUri,\n oidcResource,\n thirdPartyAppId,\n thirdPartyAppStateId,\n applicationScopes,\n },\n };\n};\n\nexport const loadFont = (url: string) => {\n if (!url) return;\n\n const font = document.createElement('link');\n font.href = url;\n font.rel = 'stylesheet';\n document.head.appendChild(font);\n};\n\nconst compareArrays = (array1: any[], array2: any[]) =>\n array1.length === array2.length &&\n array1.every((value: any, index: number) => value === array2[index]);\n\nexport const withMemCache = <I extends any[], O>(fn: (...args: I) => O) => {\n let prevArgs: any[];\n let cache: any;\n return Object.assign(\n (...args: I) => {\n if (prevArgs && compareArrays(prevArgs, args)) return cache as O;\n\n prevArgs = args;\n cache = fn(...args);\n\n return cache as O;\n },\n {\n reset: () => {\n prevArgs = undefined;\n cache = undefined;\n },\n },\n );\n};\n\nexport const FOCUSABLE_INPUTS_SELECTOR =\n '*[name]:not([auto-focus=\"false\"]):not([aria-hidden=\"true\"])';\n\nexport const handleAutoFocus = (\n ele: HTMLElement,\n autoFocus: AutoFocusOptions,\n isFirstScreen: boolean,\n) => {\n if (\n autoFocus === true ||\n (autoFocus === 'skipFirstScreen' && !isFirstScreen)\n ) {\n // focus the first visible input\n const firstVisibleInput: HTMLInputElement = ele.querySelector(\n FOCUSABLE_INPUTS_SELECTOR,\n );\n setTimeout(() => {\n firstVisibleInput?.focus();\n });\n }\n};\n\nexport const handleReportValidityOnBlur = (rootEle: HTMLElement) => {\n rootEle.querySelectorAll('*[name]').forEach((ele: HTMLInputElement) => {\n ele.addEventListener('blur', () => {\n const onBlur = () => {\n // reportValidity also focus the element if it's invalid\n // in order to prevent this we need to override the focus method\n const origFocus = ele.focus;\n // eslint-disable-next-line no-param-reassign\n ele.focus = () => {};\n ele.reportValidity?.();\n setTimeout(() => {\n // eslint-disable-next-line no-param-reassign\n ele.focus = origFocus;\n });\n };\n\n const isInputAlreadyInErrorState = ele.getAttribute('invalid') === 'true';\n\n if (isInputAlreadyInErrorState || ele.value?.length) {\n onBlur();\n return;\n }\n\n // If the input is not in an error state, has no value, and a `formnovalidate` button was clicked,\n // we want to prevent triggering validation.\n // This handles a case where a required input was focused, and the user then clicked a social login button —\n // in that case, we don't want the required error message to flash for a split second.\n const ref = { timer: undefined };\n\n const onClick = (e: MouseEvent) => {\n const target = e.target as HTMLElement;\n\n if (target.getAttribute('formnovalidate') === 'true') {\n clearTimeout(ref.timer);\n ref.timer = undefined;\n }\n };\n\n ref.timer = setTimeout(() => {\n rootEle.removeEventListener('click', onClick);\n onBlur();\n ref.timer = undefined;\n }, 150);\n\n rootEle.addEventListener('click', onClick, { once: true });\n });\n });\n};\n\n/**\n * To return a fallback value in case the timeout expires and the promise\n * isn't fulfilled:\n *\n * const promise = loadUserCount();\n * const count = await timeoutPromise(2000, promise, 0);\n *\n * Or without a fallback value to just throw an error if the timeout expires:\n *\n * try {\n * count = await timeoutPromise(2000, promise);\n * }\n *\n * Fallback is returned only in case of timeout, so if the passed promise rejects\n * the fallback value is not used, and the returned promise will throw as well.\n */\nexport function timeoutPromise<T>(\n timeout: number,\n promise: Promise<T>,\n fallback?: T,\n): Promise<T> {\n return new Promise((resolve, reject) => {\n let expired = false;\n const timer = setTimeout(() => {\n expired = true;\n if (fallback !== undefined) {\n resolve(fallback);\n } else {\n reject(new Error(`Promise timed out after ${timeout} ms`));\n }\n }, timeout);\n\n promise\n .then((value) => {\n if (!expired) {\n clearTimeout(timer);\n resolve(value);\n }\n })\n .catch((error) => {\n if (!expired) {\n clearTimeout(timer);\n reject(error);\n }\n });\n });\n}\n\nexport const getChromiumVersion = (): number => {\n const brands = (navigator as any)?.userAgentData?.brands;\n const found = brands?.find(\n ({ brand, version }) => brand === 'Chromium' && parseFloat(version),\n );\n return found ? found.version : 0;\n};\n\n// As an optimization - We can show first screen if we have startScreenId and we don't have any other of the ssoAppId/oidcIdpStateId/samlIdp params\n// - If there startScreenId it means that the sdk can show the first screen and we don't need to wait for the sdk to return the first screen\n// - If there is any one else of the other params (like oidcIdpStateId, ..) - we can't skip this call because descope may decide not to show the first screen (in cases like a user is already logged in)\nexport const showFirstScreenOnExecutionInit = (\n startScreenId: string,\n {\n oidcIdpStateId,\n samlIdpStateId,\n wsfedIdpStateId,\n samlIdpUsername,\n ssoAppId,\n oidcLoginHint,\n oidcPrompt,\n oidcErrorRedirectUri,\n oidcResource,\n thirdPartyAppId,\n thirdPartyAppStateId,\n applicationScopes,\n }: SSOQueryParams,\n): boolean =>\n !!startScreenId &&\n !oidcIdpStateId &&\n !samlIdpStateId &&\n !wsfedIdpStateId &&\n !samlIdpUsername &&\n !ssoAppId &&\n !oidcLoginHint &&\n !oidcPrompt &&\n !oidcErrorRedirectUri &&\n !oidcResource &&\n !thirdPartyAppId &&\n !thirdPartyAppStateId &&\n !applicationScopes;\n\nexport const injectSamlIdpForm = (\n url: string,\n samlResponse: string,\n relayState: string,\n submitCallback: (form: HTMLFormElement) => void,\n) => {\n const formEle = document.createElement('form');\n formEle.method = 'POST';\n formEle.action = url;\n formEle.innerHTML = `\n <input type=\"hidden\" role=\"saml-response\" name=\"SAMLResponse\" value=\"${samlResponse}\" />\n <input type=\"hidden\" role=\"saml-relay-state\" name=\"RelayState\" value=\"${relayState}\" />\n <input style=\"display: none;\" id=\"SAMLSubmitButton\" type=\"submit\" value=\"Continue\" />\n `;\n\n document.body.appendChild(formEle);\n\n submitCallback(formEle);\n};\n\nexport const injectWsFedIdpForm = (\n url: string,\n wresult: string,\n wctx: string,\n submitCallback: (form: HTMLFormElement) => void,\n) => {\n const formEle = document.createElement('form');\n formEle.method = 'POST';\n formEle.action = url;\n\n // Use DOM APIs to set values safely — wresult is raw XML that would break innerHTML interpolation\n const createHiddenInput = (name: string, value: string) => {\n const input = document.createElement('input');\n input.type = 'hidden';\n input.name = name;\n input.value = value;\n return input;\n };\n\n formEle.appendChild(createHiddenInput('wa', 'wsignin1.0'));\n formEle.appendChild(createHiddenInput('wresult', wresult));\n formEle.appendChild(createHiddenInput('wctx', wctx));\n\n const submitBtn = document.createElement('input');\n submitBtn.type = 'submit';\n submitBtn.id = 'WSFedSubmitButton';\n submitBtn.value = 'Continue';\n submitBtn.style.display = 'none';\n formEle.appendChild(submitBtn);\n\n document.body.appendChild(formEle);\n\n submitCallback(formEle);\n};\n\nexport const submitForm = (formEle: HTMLFormElement) => formEle?.submit();\n\nexport const getFirstNonEmptyValue = (obj: object, keys: string[]) => {\n const firstNonEmptyKey = keys.find((key) => obj[key]);\n return firstNonEmptyKey ? obj[firstNonEmptyKey] : null;\n};\n\nexport const leadingDebounce = <T extends (...args: any[]) => void>(\n func: T,\n wait = 100,\n) => {\n let timeout: NodeJS.Timeout;\n return function executedFunction(...args) {\n if (!timeout) func.apply(this, args);\n clearTimeout(timeout);\n timeout = setTimeout(() => {\n timeout = null;\n }, wait);\n } as T;\n};\n\nexport function getUserLocale(locale: string): Locale {\n if (locale) {\n return { locale: locale.toLowerCase(), fallback: locale.toLowerCase() };\n }\n const nl = navigator.language;\n if (!nl) {\n return { locale: '', fallback: '' };\n }\n\n if (nl.includes('-')) {\n return {\n locale: nl.toLowerCase(),\n fallback: nl.split('-')[0].toLowerCase(),\n };\n }\n\n return { locale: nl.toLowerCase(), fallback: nl.toLowerCase() };\n}\n\nexport const clearPreviousExternalInputs = () => {\n document\n .querySelectorAll('[data-hidden-input=\"true\"]')\n .forEach((ele) => ele.remove());\n};\n\nexport const shouldHandleMarkdown = (compName: string) =>\n MD_COMPONENTS.includes(compName);\n\nconst omitBy = <T extends Record<string, any>>(\n obj: T,\n predicate: (value: any, key: keyof T) => boolean,\n): T =>\n Object.fromEntries(\n Object.entries(obj).filter(\n ([key, value]) => !predicate(value, key as keyof T),\n ),\n ) as T;\n\nexport const transformStepStateForCustomScreen = (\n state: Partial<StepState>,\n) => {\n const sanitizedState: CustomScreenState = omitBy(\n state.screenState,\n (_, key) => EXCLUDED_STATE_KEYS.includes(key) || key.startsWith('_'),\n );\n\n const {\n screenState: { errorText, errorType },\n } = state;\n\n if (errorText || errorType) {\n sanitizedState.error = { text: errorText, type: errorType };\n }\n\n if (state.action) {\n sanitizedState.action = state.action;\n }\n\n if (state.screenState?.componentsConfig?.thirdPartyAppApproveScopes?.data) {\n sanitizedState.inboundAppApproveScopes =\n state.screenState.componentsConfig.thirdPartyAppApproveScopes.data;\n }\n\n return sanitizedState;\n};\n\nexport const transformScreenInputs = (inputs: Record<string, any>) => {\n const res = { ...inputs };\n\n if (inputs.inboundAppApproveScopes) {\n res.thirdPartyAppApproveScopes = inputs.inboundAppApproveScopes;\n }\n\n return res;\n};\n\nexport function getScriptResultPath(scriptId: string, resultKey?: string) {\n const path = resultKey ? `${scriptId}_${resultKey}` : scriptId;\n return `${SDK_SCRIPT_RESULTS_KEY}.${path}`;\n}\n\nexport const openCenteredPopup = (\n url: string,\n title: string,\n w: number,\n h: number,\n) => {\n const dualScreenLeft =\n window.screenLeft !== undefined\n ? window.screenLeft\n : (window.screen as any).left;\n const dualScreenTop =\n window.screenTop !== undefined\n ? window.screenTop\n : (window.screen as any).top;\n\n const width =\n window.innerWidth ||\n document.documentElement.clientWidth ||\n window.screen.width;\n const height =\n window.innerHeight ||\n document.documentElement.clientHeight ||\n window.screen.height;\n\n const left = (width - w) / 2 + dualScreenLeft;\n const top = (height - h) / 2 + dualScreenTop;\n\n // Safari on Mac may detect authentication URLs and replace the popup with a native macOS auth dialog.\n // To avoid that, we open the popup with empty string as URL and then populate it with the needed URL.\n // This avoids the native dialog, and uses the web interface for authentication.\n const initialUrl = isIphoneSafari() ? 'about:blank' : '';\n const popup = window.open(\n initialUrl,\n title,\n `width=${w},height=${h},top=${top},left=${left},scrollbars=yes,resizable=yes`,\n );\n\n popup.location.href = url;\n popup.focus();\n\n return popup;\n};\n"],"names":["MD_COMPONENTS","getUrlParam","paramName","URLSearchParams","window","location","search","get","resetUrlParam","history","replaceState","newUrl","URL","href","delete","toString","getRunIdsFromUrl","flowId","executionId","stepId","URL_RUN_IDS_PARAM_NAME","split","executionFlowId","_a","exec","getFlowIdFromExecId","clearRunIdsFromUrl","getTokenFromUrl","URL_TOKEN_PARAM_NAME","undefined","clearTokenFromUrl","getCodeFromUrl","URL_CODE_PARAM_NAME","getIsPopupFromUrl","URL_REDIRECT_MODE_PARAM_NAME","getExchangeErrorFromUrl","URL_ERR_PARAM_NAME","clearCodeFromUrl","clearIsPopupFromUrl","clearExchangeErrorFromUrl","getRedirectAuthFromUrl","redirectAuthCodeChallenge","URL_REDIRECT_AUTH_CHALLENGE_PARAM_NAME","redirectAuthCallbackUrl","URL_REDIRECT_AUTH_CALLBACK_PARAM_NAME","redirectAuthBackupCallbackUri","URL_REDIRECT_AUTH_BACKUP_CALLBACK_PARAM_NAME","redirectAuthInitiator","URL_REDIRECT_AUTH_INITIATOR_PARAM_NAME","getOIDCIDPParamFromUrl","OIDC_IDP_STATE_ID_PARAM_NAME","clearOIDCIDPParamFromUrl","getSAMLIDPParamFromUrl","SAML_IDP_STATE_ID_PARAM_NAME","clearSAMLIDPParamFromUrl","getWSFedIDPParamFromUrl","WSFED_IDP_STATE_ID_PARAM_NAME","clearWSFedIDPParamFromUrl","getSAMLIDPUsernameParamFromUrl","SAML_IDP_USERNAME_PARAM_NAME","clearSAMLIDPUsernameParamFromUrl","getDescopeIDPInitiatedParamFromUrl","DESCOPE_IDP_INITIATED_PARAM_NAME","clearDescopeIDPInitiatedParamFromUrl","getSSOAppIdParamFromUrl","SSO_APP_ID_PARAM_NAME","getThirdPartyAppIdParamFromUrl","THIRD_PARTY_APP_ID_PARAM_NAME","clearSSOAppIdParamFromUrl","clearThirdPartyAppIdParamFromUrl","getThirdPartyAppStateIdParamFromUrl","THIRD_PARTY_APP_STATE_ID_PARAM_NAME","clearThirdPartyAppStateIdParamFromUrl","getApplicationScopesParamFromUrl","APPLICATION_SCOPES_PARAM_NAME","clearApplicationScopesParamFromUrl","getOIDCLoginHintParamFromUrl","OIDC_LOGIN_HINT_PARAM_NAME","clearOIDCLoginHintParamFromUrl","getOIDCPromptParamFromUrl","OIDC_PROMPT_PARAM_NAME","clearOIDCPromptParamFromUrl","getOIDCErrorRedirectUriParamFromUrl","OIDC_ERROR_REDIRECT_URI_PARAM_NAME","clearOIDCErrorRedirectUriParamFromUrl","getOIDCResourceParamFromUrl","OIDC_RESOURCE_PARAM_NAME","clearOIDCResourceParamFromUrl","FOCUSABLE_INPUTS_SELECTOR","s","replace","x","toUpperCase","document","querySelectorAll","forEach","ele","remove","state","prevState","attrName","url","returnType","res","fetch","cache","ok","Error","status","body","headers","Object","fromEntries","entries","currentIdxStr","prevIdxStr","currentIdx","prevIdx","Number","isNaN","Direction","forward","backward","brands","navigator","userAgentData","found","find","brand","version","parseFloat","projectId","filename","assetsFolder","ASSETS_FOLDER","baseUrl","OVERRIDE_CONTENT_URL","BASE_CONTENT_URL","pathname","paths","join","pathJoin","Array","from","attributes","reduce","acc","attr","descopeAttrName","RegExp","DESCOPE_ATTRIBUTE_PREFIX","name","assign","value","obj","keys","firstNonEmptyKey","key","scriptId","resultKey","path","SDK_SCRIPT_RESULTS_KEY","locale","toLowerCase","fallback","nl","language","includes","autoFocus","isFirstScreen","firstVisibleInput","querySelector","setTimeout","focus","rootEle","addEventListener","onBlur","origFocus","reportValidity","call","getAttribute","length","ref","timer","onClick","e","target","clearTimeout","removeEventListener","once","logger","debug","ssoQueryParams","token","code","isPopup","exchangeError","oidcIdpStateId","samlIdpStateId","wsfedIdpStateId","samlIdpUsername","descopeIdpInitiated","ssoAppId","thirdPartyAppId","thirdPartyAppStateId","applicationScopes","oidcLoginHint","oidcPrompt","oidcErrorRedirectUri","oidcResource","samlResponse","relayState","submitCallback","formEle","createElement","method","action","innerHTML","appendChild","wresult","wctx","createHiddenInput","input","type","submitBtn","id","style","display","test","userAgent","vendor","func","wait","timeout","args","apply","this","title","w","h","dualScreenLeft","screenLeft","screen","left","dualScreenTop","screenTop","top","innerWidth","documentElement","clientWidth","width","innerHeight","clientHeight","height","initialUrl","ua","isIphone","isSafari","isIphoneSafari","popup","open","compName","startScreenId","submit","promise","Promise","resolve","reject","expired","then","catch","error","inputs","inboundAppApproveScopes","thirdPartyAppApproveScopes","sanitizedState","screenState","predicate","_","EXCLUDED_STATE_KEYS","startsWith","filter","errorText","errorType","text","_c","_b","componentsConfig","data","fn","prevArgs","array2","array1","every","index","reset","timeoutMs","maxRetries","__awaiter","lastError","totalAttempts","attempt","Math","pow"],"mappings":"gLAuCA,MAAMA,EAAgB,CAAC,yBAyCvB,SAASC,EAAYC,GAGnB,OAFkB,IAAIC,gBAAgBC,OAAOC,SAASC,QAErCC,IAAIL,EACvB,CAgBA,SAASM,EAAcN,GACrB,GAAIE,OAAOK,QAAQC,cAAgBT,EAAYC,GAAY,CACzD,MAAMS,EAAS,IAAIC,IAAIR,OAAOC,SAASQ,MACjCP,EAAS,IAAIH,gBAAgBQ,EAAOL,QAC1CA,EAAOQ,OAAOZ,GACdS,EAAOL,OAASA,EAAOS,WACvBX,OAAOK,QAAQC,aAAa,CAAA,EAAI,GAAIC,EAAOI,WAC5C,CACH,CA2Da,MAAAC,EAAoBC,IAC/B,IAAKC,EAAc,GAAIC,EAAS,KAjFzBlB,EAAYmB,EAAAA,yBAiFyC,IAAIC,MAAM,KACtE,MAAMC,EA3DoB,CAACJ,UAE3B,OAAiC,QAA1BK,EADO,YACDC,KAAKN,UAAe,IAAAK,OAAA,EAAAA,EAAA,KAAM,EAAE,EAyDjBE,CAAoBP,GAQ5C,QALKD,GAAWK,GAAmBA,IAAoBL,KACrDC,EAAc,GACdC,EAAS,IAGJ,CAAED,cAAaC,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N_PARAM_NAME,\n URL_REDIRECT_AUTH_CHALLENGE_PARAM_NAME,\n URL_REDIRECT_AUTH_CALLBACK_PARAM_NAME,\n URL_REDIRECT_AUTH_BACKUP_CALLBACK_PARAM_NAME,\n URL_REDIRECT_AUTH_INITIATOR_PARAM_NAME,\n OIDC_IDP_STATE_ID_PARAM_NAME,\n SAML_IDP_STATE_ID_PARAM_NAME,\n WSFED_IDP_STATE_ID_PARAM_NAME,\n SAML_IDP_USERNAME_PARAM_NAME,\n SSO_APP_ID_PARAM_NAME,\n OIDC_LOGIN_HINT_PARAM_NAME,\n DESCOPE_IDP_INITIATED_PARAM_NAME,\n OVERRIDE_CONTENT_URL,\n OIDC_PROMPT_PARAM_NAME,\n OIDC_RESOURCE_PARAM_NAME,\n OIDC_ERROR_REDIRECT_URI_PARAM_NAME,\n THIRD_PARTY_APP_ID_PARAM_NAME,\n THIRD_PARTY_APP_STATE_ID_PARAM_NAME,\n APPLICATION_SCOPES_PARAM_NAME,\n SDK_SCRIPT_RESULTS_KEY,\n URL_REDIRECT_MODE_PARAM_NAME,\n} from '../constants';\nimport { EXCLUDED_STATE_KEYS } from '../constants/customScreens';\nimport {\n AutoFocusOptions,\n CustomScreenState,\n Direction,\n Locale,\n SSOQueryParams,\n StepState,\n} from '../types';\n\nconst MD_COMPONENTS = ['descope-enriched-text'];\n\n/**\n * Wraps an async function with retry logic\n * @param fn - The async function to wrap\n * @param timeoutMs - Time to wait between retries in milliseconds\n * @param maxRetries - Maximum number of retry attempts\n * @returns A new function with retry logic\n */\nexport function withRetry<TArgs extends any[], TReturn>(\n fn: (...args: TArgs) => Promise<TReturn>,\n timeoutMs: number,\n maxRetries: number,\n): (...args: TArgs) => Promise<TReturn> {\n return async (...args: TArgs): Promise<TReturn> => {\n let lastError: any;\n const totalAttempts = maxRetries + 1; // initial attempt + retries\n\n // eslint-disable-next-line no-plusplus\n for (let attempt = 0; attempt < totalAttempts; attempt++) {\n try {\n // eslint-disable-next-line no-await-in-loop\n return await fn(...args);\n } catch (error) {\n lastError = error;\n\n // Don't wait after the last attempt\n if (attempt < maxRetries) {\n // eslint-disable-next-line no-await-in-loop\n await new Promise((resolve) => {\n setTimeout(resolve, timeoutMs * Math.pow(2, attempt + 1));\n });\n }\n }\n }\n\n // All attempts failed, throw the last error\n throw lastError;\n };\n}\n\nfunction getUrlParam(paramName: string) {\n const urlParams = new URLSearchParams(window.location.search);\n\n return urlParams.get(paramName);\n}\n\nfunction getFlowUrlParam() {\n return getUrlParam(URL_RUN_IDS_PARAM_NAME);\n}\n\nfunction setFlowUrlParam(id: string) {\n if (window.history.pushState && id !== getFlowUrlParam()) {\n const newUrl = new URL(window.location.href);\n const search = new URLSearchParams(newUrl.search);\n search.set(URL_RUN_IDS_PARAM_NAME, id);\n newUrl.search = search.toString();\n window.history.pushState({}, '', newUrl.toString());\n }\n}\n\nfunction resetUrlParam(paramName: string) {\n if (window.history.replaceState && getUrlParam(paramName)) {\n const newUrl = new URL(window.location.href);\n const search = new URLSearchParams(newUrl.search);\n search.delete(paramName);\n newUrl.search = search.toString();\n window.history.replaceState({}, '', newUrl.toString());\n }\n}\n\nconst getFlowIdFromExecId = (executionId: string) => {\n const regex = /(.*)\\|#\\|.*/;\n return regex.exec(executionId)?.[1] || '';\n};\n\nexport async function fetchContent<T extends 'text' | 'json'>(\n url: string,\n returnType: T,\n): Promise<{\n body: T extends 'json' ? Record<string, any> : string;\n headers: Record<string, string>;\n}> {\n const res = await fetch(url, { cache: 'default' });\n if (!res.ok) {\n throw Error(`Error fetching URL ${url} [${res.status}]`);\n }\n\n return {\n body: await res[returnType || 'text'](),\n headers: Object.fromEntries(res.headers.entries()),\n };\n}\n\nconst pathJoin = (...paths: string[]) => paths.join('/').replace(/\\/+/g, '/'); // preventing duplicate separators\n\nexport function getContentUrl({\n projectId,\n filename,\n assetsFolder = ASSETS_FOLDER,\n baseUrl,\n}: {\n projectId: string;\n filename: string;\n assetsFolder?: string;\n baseUrl?: string;\n}) {\n const url = new URL(OVERRIDE_CONTENT_URL || baseUrl || BASE_CONTENT_URL);\n url.pathname = pathJoin(url.pathname, projectId, assetsFolder, filename);\n\n return url.toString();\n}\n\nexport function getAnimationDirection(\n currentIdxStr: string,\n prevIdxStr: string,\n) {\n if (!prevIdxStr) return undefined;\n\n const currentIdx = +currentIdxStr;\n const prevIdx = +prevIdxStr;\n\n if (Number.isNaN(currentIdx) || Number.isNaN(prevIdx)) return undefined;\n if (currentIdx > prevIdx) return Direction.forward;\n if (currentIdx < prevIdx) return Direction.backward;\n return undefined;\n}\n\nexport const getRunIdsFromUrl = (flowId: string) => {\n let [executionId = '', stepId = ''] = (getFlowUrlParam() || '').split('_');\n const executionFlowId = getFlowIdFromExecId(executionId);\n\n // if the flow id does not match, this execution id is not for this flow\n if (!flowId || (executionFlowId && executionFlowId !== flowId)) {\n executionId = '';\n stepId = '';\n }\n\n return { executionId, stepId, executionFlowId };\n};\n\nexport const setRunIdsOnUrl = (executionId: string, stepId: string) => {\n setFlowUrlParam([executionId, stepId].join('_'));\n};\n\nexport function isChromium() {\n return (\n /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor)\n );\n}\n\n// Detect Safari running on iPhone specifically.\nfunction isIphoneSafari() {\n const ua = navigator.userAgent || '';\n const isIphone = /\\b(iPhone)\\b/.test(ua);\n // Safari UA contains 'Safari' and usually 'Version/X', exclude other iOS browsers\n const isSafari =\n /Safari/.test(ua) && !/CriOS|FxiOS|OPiOS|EdgiOS|Chrome|Chromium/.test(ua);\n\n return isIphone && isSafari;\n}\n\nexport function clearRunIdsFromUrl() {\n resetUrlParam(URL_RUN_IDS_PARAM_NAME);\n}\n\nexport function getTokenFromUrl() {\n return getUrlParam(URL_TOKEN_PARAM_NAME) || undefined;\n}\n\nexport function clearTokenFromUrl() {\n resetUrlParam(URL_TOKEN_PARAM_NAME);\n}\n\nexport function getCodeFromUrl() {\n return getUrlParam(URL_CODE_PARAM_NAME) || undefined;\n}\n\nexport function getIsPopupFromUrl() {\n return getUrlParam(URL_REDIRECT_MODE_PARAM_NAME) === 'popup';\n}\n\nexport function getExchangeErrorFromUrl() {\n return getUrlParam(URL_ERR_PARAM_NAME) || undefined;\n}\n\nexport function clearCodeFromUrl() {\n resetUrlParam(URL_CODE_PARAM_NAME);\n}\n\nexport function clearIsPopupFromUrl() {\n resetUrlParam(URL_REDIRECT_MODE_PARAM_NAME);\n}\n\nexport function clearExchangeErrorFromUrl() {\n resetUrlParam(URL_ERR_PARAM_NAME);\n}\n\nexport function getRedirectAuthFromUrl() {\n const redirectAuthCodeChallenge = getUrlParam(\n URL_REDIRECT_AUTH_CHALLENGE_PARAM_NAME,\n );\n const redirectAuthCallbackUrl = getUrlParam(\n URL_REDIRECT_AUTH_CALLBACK_PARAM_NAME,\n );\n const redirectAuthBackupCallbackUri = getUrlParam(\n URL_REDIRECT_AUTH_BACKUP_CALLBACK_PARAM_NAME,\n );\n const redirectAuthInitiator = getUrlParam(\n URL_REDIRECT_AUTH_INITIATOR_PARAM_NAME,\n );\n return {\n redirectAuthCodeChallenge,\n redirectAuthCallbackUrl,\n redirectAuthBackupCallbackUri,\n redirectAuthInitiator,\n };\n}\n\nexport function getOIDCIDPParamFromUrl() {\n return getUrlParam(OIDC_IDP_STATE_ID_PARAM_NAME);\n}\n\nexport function clearOIDCIDPParamFromUrl() {\n resetUrlParam(OIDC_IDP_STATE_ID_PARAM_NAME);\n}\n\nexport function getSAMLIDPParamFromUrl() {\n return getUrlParam(SAML_IDP_STATE_ID_PARAM_NAME);\n}\n\nexport function clearSAMLIDPParamFromUrl() {\n resetUrlParam(SAML_IDP_STATE_ID_PARAM_NAME);\n}\n\nexport function getWSFedIDPParamFromUrl() {\n return getUrlParam(WSFED_IDP_STATE_ID_PARAM_NAME);\n}\n\nexport function clearWSFedIDPParamFromUrl() {\n resetUrlParam(WSFED_IDP_STATE_ID_PARAM_NAME);\n}\n\nexport function getSAMLIDPUsernameParamFromUrl() {\n return getUrlParam(SAML_IDP_USERNAME_PARAM_NAME);\n}\n\nexport function clearSAMLIDPUsernameParamFromUrl() {\n resetUrlParam(SAML_IDP_USERNAME_PARAM_NAME);\n}\n\nexport function getDescopeIDPInitiatedParamFromUrl() {\n return getUrlParam(DESCOPE_IDP_INITIATED_PARAM_NAME);\n}\n\nexport function clearDescopeIDPInitiatedParamFromUrl() {\n resetUrlParam(DESCOPE_IDP_INITIATED_PARAM_NAME);\n}\n\nexport function getSSOAppIdParamFromUrl() {\n return getUrlParam(SSO_APP_ID_PARAM_NAME);\n}\n\nexport function getThirdPartyAppIdParamFromUrl() {\n return getUrlParam(THIRD_PARTY_APP_ID_PARAM_NAME);\n}\n\nexport function clearSSOAppIdParamFromUrl() {\n resetUrlParam(SSO_APP_ID_PARAM_NAME);\n}\n\nexport function clearThirdPartyAppIdParamFromUrl() {\n resetUrlParam(THIRD_PARTY_APP_ID_PARAM_NAME);\n}\n\nexport function getThirdPartyAppStateIdParamFromUrl() {\n return getUrlParam(THIRD_PARTY_APP_STATE_ID_PARAM_NAME);\n}\n\nexport function clearThirdPartyAppStateIdParamFromUrl() {\n resetUrlParam(THIRD_PARTY_APP_STATE_ID_PARAM_NAME);\n}\n\nexport function getApplicationScopesParamFromUrl() {\n return getUrlParam(APPLICATION_SCOPES_PARAM_NAME);\n}\n\nexport function clearApplicationScopesParamFromUrl() {\n resetUrlParam(APPLICATION_SCOPES_PARAM_NAME);\n}\n\nexport function getOIDCLoginHintParamFromUrl() {\n return getUrlParam(OIDC_LOGIN_HINT_PARAM_NAME);\n}\n\nexport function clearOIDCLoginHintParamFromUrl() {\n resetUrlParam(OIDC_LOGIN_HINT_PARAM_NAME);\n}\n\nexport function getOIDCPromptParamFromUrl() {\n return getUrlParam(OIDC_PROMPT_PARAM_NAME);\n}\n\nexport function clearOIDCPromptParamFromUrl() {\n resetUrlParam(OIDC_PROMPT_PARAM_NAME);\n}\n\nexport function getOIDCErrorRedirectUriParamFromUrl() {\n return getUrlParam(OIDC_ERROR_REDIRECT_URI_PARAM_NAME);\n}\n\nexport function clearOIDCErrorRedirectUriParamFromUrl() {\n resetUrlParam(OIDC_ERROR_REDIRECT_URI_PARAM_NAME);\n}\n\nexport function getOIDCResourceParamFromUrl() {\n return getUrlParam(OIDC_RESOURCE_PARAM_NAME);\n}\n\nexport function clearOIDCResourceParamFromUrl() {\n resetUrlParam(OIDC_RESOURCE_PARAM_NAME);\n}\n\nexport const camelCase = (s: string) =>\n s.replace(/-./g, (x) => x[1].toUpperCase());\n\nexport const createIsChanged =\n <T extends Record<string, any>>(state: T, prevState: T) =>\n (attrName: keyof T) =>\n state[attrName] !== prevState[attrName];\n\nexport const getElementDescopeAttributes = (ele: HTMLElement) =>\n Array.from(ele?.attributes || []).reduce((acc, attr) => {\n const descopeAttrName = new RegExp(\n `^${DESCOPE_ATTRIBUTE_PREFIX}(\\\\S+)$`,\n ).exec(attr.name)?.[1];\n\n return !descopeAttrName\n ? acc\n : Object.assign(acc, { [descopeAttrName]: attr.value });\n }, {});\n\nexport const getFlowConfig = (config: Record<string, any>, flowId: string) =>\n config?.flows?.[flowId] || {};\n\nexport const handleUrlParams = (\n flowId: string,\n logger: { debug: (...data: any[]) => void },\n) => {\n const { executionId, stepId, executionFlowId } = getRunIdsFromUrl(flowId);\n\n // if the flow id does not match, we do not want to read & remove any query params\n // because it's probably belongs to another flow\n if (executionFlowId && flowId !== executionFlowId) {\n logger.debug(\n 'Flow id does not match the execution flow id, skipping url params handling',\n );\n return { ssoQueryParams: {} };\n }\n\n if (executionId || stepId) {\n clearRunIdsFromUrl();\n }\n\n const token = getTokenFromUrl();\n if (token) {\n clearTokenFromUrl();\n }\n\n const code = getCodeFromUrl();\n if (code) {\n clearCodeFromUrl();\n }\n\n // this is used for oauth when we want to open the provider login page in a new tab\n const isPopup = getIsPopupFromUrl();\n if (isPopup) {\n clearIsPopupFromUrl();\n }\n\n const exchangeError = getExchangeErrorFromUrl();\n if (exchangeError) {\n clearExchangeErrorFromUrl();\n }\n\n // these query params are retained to allow the flow to be refreshed\n // without losing the redirect auth state\n const {\n redirectAuthCodeChallenge,\n redirectAuthCallbackUrl,\n redirectAuthBackupCallbackUri,\n redirectAuthInitiator,\n } = getRedirectAuthFromUrl();\n\n const oidcIdpStateId = getOIDCIDPParamFromUrl();\n if (oidcIdpStateId) {\n clearOIDCIDPParamFromUrl();\n }\n\n const samlIdpStateId = getSAMLIDPParamFromUrl();\n if (samlIdpStateId) {\n clearSAMLIDPParamFromUrl();\n }\n\n const wsfedIdpStateId = getWSFedIDPParamFromUrl();\n if (wsfedIdpStateId) {\n clearWSFedIDPParamFromUrl();\n }\n\n const samlIdpUsername = getSAMLIDPUsernameParamFromUrl();\n if (samlIdpStateId) {\n clearSAMLIDPUsernameParamFromUrl();\n }\n\n const descopeIdpInitiated = getDescopeIDPInitiatedParamFromUrl();\n if (descopeIdpInitiated) {\n clearDescopeIDPInitiatedParamFromUrl();\n }\n\n const ssoAppId = getSSOAppIdParamFromUrl();\n if (ssoAppId) {\n clearSSOAppIdParamFromUrl();\n }\n\n const thirdPartyAppId = getThirdPartyAppIdParamFromUrl();\n if (thirdPartyAppId) {\n clearThirdPartyAppIdParamFromUrl();\n }\n\n const thirdPartyAppStateId = getThirdPartyAppStateIdParamFromUrl();\n if (thirdPartyAppStateId) {\n clearThirdPartyAppStateIdParamFromUrl();\n }\n\n const applicationScopes = getApplicationScopesParamFromUrl();\n if (applicationScopes) {\n clearApplicationScopesParamFromUrl();\n }\n\n const oidcLoginHint = getOIDCLoginHintParamFromUrl();\n if (oidcLoginHint) {\n clearOIDCLoginHintParamFromUrl();\n }\n\n const oidcPrompt = getOIDCPromptParamFromUrl();\n if (oidcPrompt) {\n clearOIDCPromptParamFromUrl();\n }\n\n const oidcErrorRedirectUri = getOIDCErrorRedirectUriParamFromUrl();\n if (oidcErrorRedirectUri) {\n clearOIDCErrorRedirectUriParamFromUrl();\n }\n\n const oidcResource = getOIDCResourceParamFromUrl();\n if (oidcResource) {\n clearOIDCResourceParamFromUrl();\n }\n\n const idpInitiatedVal = descopeIdpInitiated === 'true';\n\n return {\n executionId,\n stepId,\n token,\n code,\n isPopup,\n exchangeError,\n redirectAuthCodeChallenge,\n redirectAuthCallbackUrl,\n redirectAuthBackupCallbackUri,\n redirectAuthInitiator,\n ssoQueryParams: {\n oidcIdpStateId,\n samlIdpStateId,\n wsfedIdpStateId,\n samlIdpUsername,\n descopeIdpInitiated: idpInitiatedVal,\n ssoAppId,\n oidcLoginHint,\n oidcPrompt,\n oidcErrorRedirectUri,\n oidcResource,\n thirdPartyAppId,\n thirdPartyAppStateId,\n applicationScopes,\n },\n };\n};\n\nexport const loadFont = (url: string) => {\n if (!url) return;\n\n const font = document.createElement('link');\n font.href = url;\n font.rel = 'stylesheet';\n document.head.appendChild(font);\n};\n\nconst compareArrays = (array1: any[], array2: any[]) =>\n array1.length === array2.length &&\n array1.every((value: any, index: number) => value === array2[index]);\n\nexport const withMemCache = <I extends any[], O>(fn: (...args: I) => O) => {\n let prevArgs: any[];\n let cache: any;\n return Object.assign(\n (...args: I) => {\n if (prevArgs && compareArrays(prevArgs, args)) return cache as O;\n\n prevArgs = args;\n cache = fn(...args);\n\n return cache as O;\n },\n {\n reset: () => {\n prevArgs = undefined;\n cache = undefined;\n },\n },\n );\n};\n\nexport const FOCUSABLE_INPUTS_SELECTOR =\n '*[name]:not([auto-focus=\"false\"]):not([aria-hidden=\"true\"])';\n\nexport const handleAutoFocus = (\n ele: HTMLElement,\n autoFocus: AutoFocusOptions,\n isFirstScreen: boolean,\n) => {\n if (\n autoFocus === true ||\n (autoFocus === 'skipFirstScreen' && !isFirstScreen)\n ) {\n // focus the first visible input\n const firstVisibleInput: HTMLInputElement = ele.querySelector(\n FOCUSABLE_INPUTS_SELECTOR,\n );\n setTimeout(() => {\n firstVisibleInput?.focus();\n });\n }\n};\n\nexport const handleReportValidityOnBlur = (rootEle: HTMLElement) => {\n rootEle.querySelectorAll('*[name]').forEach((ele: HTMLInputElement) => {\n ele.addEventListener('blur', () => {\n const onBlur = () => {\n // reportValidity also focus the element if it's invalid\n // in order to prevent this we need to override the focus method\n const origFocus = ele.focus;\n // eslint-disable-next-line no-param-reassign\n ele.focus = () => {};\n ele.reportValidity?.();\n setTimeout(() => {\n // eslint-disable-next-line no-param-reassign\n ele.focus = origFocus;\n });\n };\n\n const isInputAlreadyInErrorState = ele.getAttribute('invalid') === 'true';\n\n if (isInputAlreadyInErrorState || ele.value?.length) {\n onBlur();\n return;\n }\n\n // If the input is not in an error state, has no value, and a `formnovalidate` button was clicked,\n // we want to prevent triggering validation.\n // This handles a case where a required input was focused, and the user then clicked a social login button —\n // in that case, we don't want the required error message to flash for a split second.\n const ref = { timer: undefined };\n\n const onClick = (e: MouseEvent) => {\n const target = e.target as HTMLElement;\n\n if (target.getAttribute('formnovalidate') === 'true') {\n clearTimeout(ref.timer);\n ref.timer = undefined;\n }\n };\n\n ref.timer = setTimeout(() => {\n rootEle.removeEventListener('click', onClick);\n onBlur();\n ref.timer = undefined;\n }, 150);\n\n rootEle.addEventListener('click', onClick, { once: true });\n });\n });\n};\n\n/**\n * To return a fallback value in case the timeout expires and the promise\n * isn't fulfilled:\n *\n * const promise = loadUserCount();\n * const count = await timeoutPromise(2000, promise, 0);\n *\n * Or without a fallback value to just throw an error if the timeout expires:\n *\n * try {\n * count = await timeoutPromise(2000, promise);\n * }\n *\n * Fallback is returned only in case of timeout, so if the passed promise rejects\n * the fallback value is not used, and the returned promise will throw as well.\n */\nexport function timeoutPromise<T>(\n timeout: number,\n promise: Promise<T>,\n fallback?: T,\n): Promise<T> {\n return new Promise((resolve, reject) => {\n let expired = false;\n const timer = setTimeout(() => {\n expired = true;\n if (fallback !== undefined) {\n resolve(fallback);\n } else {\n reject(new Error(`Promise timed out after ${timeout} ms`));\n }\n }, timeout);\n\n promise\n .then((value) => {\n if (!expired) {\n clearTimeout(timer);\n resolve(value);\n }\n })\n .catch((error) => {\n if (!expired) {\n clearTimeout(timer);\n reject(error);\n }\n });\n });\n}\n\nexport const getChromiumVersion = (): number => {\n const brands = (navigator as any)?.userAgentData?.brands;\n const found = brands?.find(\n ({ brand, version }) => brand === 'Chromium' && parseFloat(version),\n );\n return found ? found.version : 0;\n};\n\n// As an optimization - We can show first screen if we have startScreenId and we don't have any other of the ssoAppId/oidcIdpStateId/samlIdp params\n// - If there startScreenId it means that the sdk can show the first screen and we don't need to wait for the sdk to return the first screen\n// - If there is any one else of the other params (like oidcIdpStateId, ..) - we can't skip this call because descope may decide not to show the first screen (in cases like a user is already logged in)\nexport const showFirstScreenOnExecutionInit = (\n startScreenId: string,\n {\n oidcIdpStateId,\n samlIdpStateId,\n wsfedIdpStateId,\n samlIdpUsername,\n ssoAppId,\n oidcLoginHint,\n oidcPrompt,\n oidcErrorRedirectUri,\n oidcResource,\n thirdPartyAppId,\n thirdPartyAppStateId,\n applicationScopes,\n }: SSOQueryParams,\n): boolean =>\n !!startScreenId &&\n !oidcIdpStateId &&\n !samlIdpStateId &&\n !wsfedIdpStateId &&\n !samlIdpUsername &&\n !ssoAppId &&\n !oidcLoginHint &&\n !oidcPrompt &&\n !oidcErrorRedirectUri &&\n !oidcResource &&\n !thirdPartyAppId &&\n !thirdPartyAppStateId &&\n !applicationScopes;\n\nexport const injectSamlIdpForm = (\n url: string,\n samlResponse: string,\n relayState: string,\n submitCallback: (form: HTMLFormElement) => void,\n) => {\n const formEle = document.createElement('form');\n formEle.method = 'POST';\n formEle.action = url;\n formEle.innerHTML = `\n <input type=\"hidden\" role=\"saml-response\" name=\"SAMLResponse\" value=\"${samlResponse}\" />\n <input type=\"hidden\" role=\"saml-relay-state\" name=\"RelayState\" value=\"${relayState}\" />\n <input style=\"display: none;\" id=\"SAMLSubmitButton\" type=\"submit\" value=\"Continue\" />\n `;\n\n document.body.appendChild(formEle);\n\n submitCallback(formEle);\n};\n\nexport const injectWsFedIdpForm = (\n url: string,\n wresult: string,\n wctx: string,\n submitCallback: (form: HTMLFormElement) => void,\n) => {\n const formEle = document.createElement('form');\n formEle.method = 'POST';\n formEle.action = url;\n\n // Use DOM APIs to set values safely — wresult is raw XML that would break innerHTML interpolation\n const createHiddenInput = (name: string, value: string) => {\n const input = document.createElement('input');\n input.type = 'hidden';\n input.name = name;\n input.value = value;\n return input;\n };\n\n formEle.appendChild(createHiddenInput('wa', 'wsignin1.0'));\n formEle.appendChild(createHiddenInput('wresult', wresult));\n formEle.appendChild(createHiddenInput('wctx', wctx));\n\n const submitBtn = document.createElement('input');\n submitBtn.type = 'submit';\n submitBtn.id = 'WSFedSubmitButton';\n submitBtn.value = 'Continue';\n submitBtn.style.display = 'none';\n formEle.appendChild(submitBtn);\n\n document.body.appendChild(formEle);\n\n submitCallback(formEle);\n};\n\nexport const submitForm = (formEle: HTMLFormElement) => formEle?.submit();\n\nexport const getFirstNonEmptyValue = (obj: object, keys: string[]) => {\n const firstNonEmptyKey = keys.find((key) => obj[key]);\n return firstNonEmptyKey ? obj[firstNonEmptyKey] : null;\n};\n\nexport const leadingDebounce = <T extends (...args: any[]) => void>(\n func: T,\n wait = 100,\n) => {\n let timeout: NodeJS.Timeout;\n return function executedFunction(...args) {\n if (!timeout) func.apply(this, args);\n clearTimeout(timeout);\n timeout = setTimeout(() => {\n timeout = null;\n }, wait);\n } as T;\n};\n\nexport function getUserLocale(locale: string): Locale {\n if (locale) {\n return { locale: locale.toLowerCase(), fallback: locale.toLowerCase() };\n }\n const nl = navigator.language;\n if (!nl) {\n return { locale: '', fallback: '' };\n }\n\n if (nl.includes('-')) {\n return {\n locale: nl.toLowerCase(),\n fallback: nl.split('-')[0].toLowerCase(),\n };\n }\n\n return { locale: nl.toLowerCase(), fallback: nl.toLowerCase() };\n}\n\nexport const clearPreviousExternalInputs = () => {\n document\n .querySelectorAll('[data-hidden-input=\"true\"]')\n .forEach((ele) => ele.remove());\n};\n\nexport const shouldHandleMarkdown = (compName: string) =>\n MD_COMPONENTS.includes(compName);\n\nconst omitBy = <T extends Record<string, any>>(\n obj: T,\n predicate: (value: any, key: keyof T) => boolean,\n): T =>\n Object.fromEntries(\n Object.entries(obj).filter(\n ([key, value]) => !predicate(value, key as keyof T),\n ),\n ) as T;\n\nexport const transformStepStateForCustomScreen = (\n state: Partial<StepState>,\n) => {\n const sanitizedState: CustomScreenState = omitBy(\n state.screenState,\n (_, key) => EXCLUDED_STATE_KEYS.includes(key) || key.startsWith('_'),\n );\n\n const {\n screenState: { errorText, errorType },\n } = state;\n\n if (errorText || errorType) {\n sanitizedState.error = { text: errorText, type: errorType };\n }\n\n if (state.action) {\n sanitizedState.action = state.action;\n }\n\n if (state.screenState?.componentsConfig?.thirdPartyAppApproveScopes?.data) {\n sanitizedState.inboundAppApproveScopes =\n state.screenState.componentsConfig.thirdPartyAppApproveScopes.data;\n }\n\n return sanitizedState;\n};\n\nexport const transformScreenInputs = (inputs: Record<string, any>) => {\n const res = { ...inputs };\n\n if (inputs.inboundAppApproveScopes) {\n res.thirdPartyAppApproveScopes = inputs.inboundAppApproveScopes;\n }\n\n return res;\n};\n\nexport function getScriptResultPath(scriptId: string, resultKey?: string) {\n const path = resultKey ? `${scriptId}_${resultKey}` : scriptId;\n return `${SDK_SCRIPT_RESULTS_KEY}.${path}`;\n}\n\nexport const openCenteredPopup = (\n url: string,\n title: string,\n w: number,\n h: number,\n) => {\n const dualScreenLeft =\n window.screenLeft !== undefined\n ? window.screenLeft\n : (window.screen as any).left;\n const dualScreenTop =\n window.screenTop !== undefined\n ? window.screenTop\n : (window.screen as any).top;\n\n const width =\n window.innerWidth ||\n document.documentElement.clientWidth ||\n window.screen.width;\n const height =\n window.innerHeight ||\n document.documentElement.clientHeight ||\n window.screen.height;\n\n const left = (width - w) / 2 + dualScreenLeft;\n const top = (height - h) / 2 + dualScreenTop;\n\n // Safari on Mac may detect authentication URLs and replace the popup with a native macOS auth dialog.\n // To avoid that, we open the popup with empty string as URL and then populate it with the needed URL.\n // This avoids the native dialog, and uses the web interface for authentication.\n const initialUrl = isIphoneSafari() ? 'about:blank' : '';\n const popup = window.open(\n initialUrl,\n title,\n `width=${w},height=${h},top=${top},left=${left},scrollbars=yes,resizable=yes`,\n );\n\n popup.location.href = url;\n popup.focus();\n\n return popup;\n};\n"],"names":["MD_COMPONENTS","getUrlParam","paramName","URLSearchParams","window","location","search","get","resetUrlParam","history","replaceState","newUrl","URL","href","delete","toString","getRunIdsFromUrl","flowId","executionId","stepId","URL_RUN_IDS_PARAM_NAME","split","executionFlowId","_a","exec","getFlowIdFromExecId","clearRunIdsFromUrl","getTokenFromUrl","URL_TOKEN_PARAM_NAME","undefined","clearTokenFromUrl","getCodeFromUrl","URL_CODE_PARAM_NAME","getIsPopupFromUrl","URL_REDIRECT_MODE_PARAM_NAME","getExchangeErrorFromUrl","URL_ERR_PARAM_NAME","clearCodeFromUrl","clearIsPopupFromUrl","clearExchangeErrorFromUrl","getRedirectAuthFromUrl","redirectAuthCodeChallenge","URL_REDIRECT_AUTH_CHALLENGE_PARAM_NAME","redirectAuthCallbackUrl","URL_REDIRECT_AUTH_CALLBACK_PARAM_NAME","redirectAuthBackupCallbackUri","URL_REDIRECT_AUTH_BACKUP_CALLBACK_PARAM_NAME","redirectAuthInitiator","URL_REDIRECT_AUTH_INITIATOR_PARAM_NAME","getOIDCIDPParamFromUrl","OIDC_IDP_STATE_ID_PARAM_NAME","clearOIDCIDPParamFromUrl","getSAMLIDPParamFromUrl","SAML_IDP_STATE_ID_PARAM_NAME","clearSAMLIDPParamFromUrl","getWSFedIDPParamFromUrl","WSFED_IDP_STATE_ID_PARAM_NAME","clearWSFedIDPParamFromUrl","getSAMLIDPUsernameParamFromUrl","SAML_IDP_USERNAME_PARAM_NAME","clearSAMLIDPUsernameParamFromUrl","getDescopeIDPInitiatedParamFromUrl","DESCOPE_IDP_INITIATED_PARAM_NAME","clearDescopeIDPInitiatedParamFromUrl","getSSOAppIdParamFromUrl","SSO_APP_ID_PARAM_NAME","getThirdPartyAppIdParamFromUrl","THIRD_PARTY_APP_ID_PARAM_NAME","clearSSOAppIdParamFromUrl","clearThirdPartyAppIdParamFromUrl","getThirdPartyAppStateIdParamFromUrl","THIRD_PARTY_APP_STATE_ID_PARAM_NAME","clearThirdPartyAppStateIdParamFromUrl","getApplicationScopesParamFromUrl","APPLICATION_SCOPES_PARAM_NAME","clearApplicationScopesParamFromUrl","getOIDCLoginHintParamFromUrl","OIDC_LOGIN_HINT_PARAM_NAME","clearOIDCLoginHintParamFromUrl","getOIDCPromptParamFromUrl","OIDC_PROMPT_PARAM_NAME","clearOIDCPromptParamFromUrl","getOIDCErrorRedirectUriParamFromUrl","OIDC_ERROR_REDIRECT_URI_PARAM_NAME","clearOIDCErrorRedirectUriParamFromUrl","getOIDCResourceParamFromUrl","OIDC_RESOURCE_PARAM_NAME","clearOIDCResourceParamFromUrl","FOCUSABLE_INPUTS_SELECTOR","s","replace","x","toUpperCase","document","querySelectorAll","forEach","ele","remove","state","prevState","attrName","url","returnType","res","fetch","cache","ok","Error","status","body","headers","Object","fromEntries","entries","currentIdxStr","prevIdxStr","currentIdx","prevIdx","Number","isNaN","Direction","forward","backward","brands","navigator","userAgentData","found","find","brand","version","parseFloat","projectId","filename","assetsFolder","ASSETS_FOLDER","baseUrl","OVERRIDE_CONTENT_URL","BASE_CONTENT_URL","pathname","paths","join","pathJoin","Array","from","attributes","reduce","acc","attr","descopeAttrName","RegExp","DESCOPE_ATTRIBUTE_PREFIX","name","assign","value","obj","keys","firstNonEmptyKey","key","scriptId","resultKey","path","SDK_SCRIPT_RESULTS_KEY","locale","toLowerCase","fallback","nl","language","includes","autoFocus","isFirstScreen","firstVisibleInput","querySelector","setTimeout","focus","rootEle","addEventListener","onBlur","origFocus","reportValidity","call","getAttribute","length","ref","timer","onClick","e","target","clearTimeout","removeEventListener","once","logger","debug","ssoQueryParams","token","code","isPopup","exchangeError","oidcIdpStateId","samlIdpStateId","wsfedIdpStateId","samlIdpUsername","descopeIdpInitiated","ssoAppId","thirdPartyAppId","thirdPartyAppStateId","applicationScopes","oidcLoginHint","oidcPrompt","oidcErrorRedirectUri","oidcResource","samlResponse","relayState","submitCallback","formEle","createElement","method","action","innerHTML","appendChild","wresult","wctx","createHiddenInput","input","type","submitBtn","id","style","display","test","userAgent","vendor","func","wait","timeout","args","apply","this","title","w","h","dualScreenLeft","screenLeft","screen","left","dualScreenTop","screenTop","top","innerWidth","documentElement","clientWidth","width","innerHeight","clientHeight","height","initialUrl","ua","isIphone","isSafari","isIphoneSafari","popup","open","compName","startScreenId","submit","promise","Promise","resolve","reject","expired","then","catch","error","inputs","inboundAppApproveScopes","thirdPartyAppApproveScopes","sanitizedState","screenState","predicate","_","EXCLUDED_STATE_KEYS","startsWith","filter","errorText","errorType","text","_c","_b","componentsConfig","data","fn","prevArgs","array2","array1","every","index","reset","timeoutMs","maxRetries","__awaiter","lastError","totalAttempts","attempt","Math","pow"],"mappings":"gLAuCA,MAAMA,EAAgB,CAAC,yBAyCvB,SAASC,EAAYC,GAGnB,OAFkB,IAAIC,gBAAgBC,OAAOC,SAASC,QAErCC,IAAIL,EACvB,CAgBA,SAASM,EAAcN,GACrB,GAAIE,OAAOK,QAAQC,cAAgBT,EAAYC,GAAY,CACzD,MAAMS,EAAS,IAAIC,IAAIR,OAAOC,SAASQ,MACjCP,EAAS,IAAIH,gBAAgBQ,EAAOL,QAC1CA,EAAOQ,OAAOZ,GACdS,EAAOL,OAASA,EAAOS,WACvBX,OAAOK,QAAQC,aAAa,CAAA,EAAI,GAAIC,EAAOI,WAC5C,CACH,CA2Da,MAAAC,EAAoBC,IAC/B,IAAKC,EAAc,GAAIC,EAAS,KAjFzBlB,EAAYmB,EAAAA,yBAiFyC,IAAIC,MAAM,KACtE,MAAMC,EA3DoB,CAACJ,UAE3B,OAAiC,QAA1BK,EADO,cACDC,KAAKN,UAAe,IAAAK,OAAA,EAAAA,EAAA,KAAM,EAAE,EAyDjBE,CAAoBP,GAQ5C,QALKD,GAAWK,GAAmBA,IAAoBL,KACrDC,EAAc,GACdC,EAAS,IAGJ,CAAED,cAAaC,SAAQG,kBAAiB,WAwBjCI,IACdlB,EA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,EAAMsH,SAGqC,QAAjEqE,EAAqC,QAArCC,EAAmB,QAAnBvQ,EAAA2E,EAAMkL,mBAAa,IAAA7P,OAAA,EAAAA,EAAAwQ,wBAAkB,IAAAD,OAAA,EAAAA,EAAAZ,kCAA4B,IAAAW,OAAA,EAAAA,EAAAG,QACnEb,EAAeF,wBACb/K,EAAMkL,YAAYW,iBAAiBb,2BAA2Bc,MAG3Db,CAAc,uBAjU0Bc,IAC/C,IAAIC,EACAzL,EACJ,OAAOM,OAAOyC,QACZ,IAAIkF,KACF,OAAIwD,IAT4BC,EASQzD,GATvB0D,EASaF,GAR3B7G,SAAW8G,EAAO9G,QACzB+G,EAAOC,OAAM,CAAC5I,EAAY6I,IAAkB7I,IAAU0I,EAAOG,QASzDJ,EAAWxD,EACXjI,EAAQwL,KAAMvD,IAHwCjI,EATtC,IAAC2L,EAAeD,CAcf,GAEnB,CACEI,MAAO,KACLL,OAAWrQ,EACX4E,OAAQ5E,CAAS,GAGtB,6BA/fDoQ,EACAO,EACAC,GAEA,MAAO,IAAU/D,IAAiCgE,EAAAA,UAAA9D,UAAA,OAAA,GAAA,YAChD,IAAI+D,EACJ,MAAMC,EAAgBH,EAAa,EAGnC,IAAK,IAAII,EAAU,EAAGA,EAAUD,EAAeC,IAC7C,IAEE,aAAaZ,KAAMvD,EACpB,CAAC,MAAOqC,GACP4B,EAAY5B,EAGR8B,EAAUJ,UAEN,IAAIhC,SAASC,IACjB9F,WAAW8F,EAAS8B,EAAYM,KAAKC,IAAI,EAAGF,EAAU,GAAG,IAG9D,CAIH,MAAMF,CACR,GACF"}
@@ -1,2 +1,2 @@
1
- import{__classPrivateFieldGet as t,__awaiter as e,__classPrivateFieldSet as i}from"tslib";import{compose as r}from"@descope/sdk-helpers";import{staticResourcesMixin as o}from"@descope/sdk-mixins/static-resources-mixin";import{themeMixin as s}from"@descope/sdk-mixins/theme-mixin";import{injectStyleMixin as n}from"@descope/sdk-mixins/inject-style-mixin";import{createSdk as u}from"@descope/web-js-sdk";import{ELEMENTS_TO_IGNORE_ENTER_KEY_ON as a}from"../constants/index.js";import{handleUrlParams as l,clearRunIdsFromUrl as d,camelCase as c,getRunIdsFromUrl as h,getContentUrl as g,fetchContent as f,withRetry as p}from"../helpers/helpers.js";import m from"../helpers/state.js";import"@descope/escape-markdown";import"../helpers/webauthn.js";import{setCustomStorage as b}from"../helpers/storage.js";import{transformFlowInputFormData as v,extractNestedAttribute as w}from"../helpers/flowInputs.js";import{formMountMixin as k}from"../mixins/formMountMixin.js";import{CONFIG_FILENAME as C,PREV_VER_ASSETS_FOLDER as y}from"../constants/content.js";import{FETCH_EXCEPTION_ERROR_CODE as A}from"../constants/general.js";var x,I,j,E,L,S,U,M,O,W,D,P,N,F,K,R,T,B,H,J,V,q;const $=r(s,o,k,n)(HTMLElement);class z extends ${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","style-id"]}constructor(r){super(),x.add(this),j.set(this,!1),E.set(this,void 0),this.flowStatus="initial",this.loggerWrapper={error:(e,i="")=>{this.logger.error(e,i,new Error),t(this,x,"m",q).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)}},L.set(this,new m),S.set(this,new m),U.set(this,{}),this.getComponentsContext=()=>t(this,U,"f"),this.nextRequestStatus=new m({isLoading:!1}),M.set(this,void 0),O.set(this,{popstate:t(this,x,"m",F).bind(this),componentsContext:t(this,x,"m",H).bind(this)}),W.set(this,void 0),this.getConfig=()=>e(this,void 0,void 0,(function*(){return(yield this.config)||{isMissingConfig:!0}})),i(this,W,r,"f"),t(this,x,"m",P).call(this)}get flowId(){return this.getAttribute("flow-id")}get client(){try{return JSON.parse(this.getAttribute("client"))||{}}catch(t){return{}}}get tenantId(){return this.getAttribute("tenant")||void 0}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 preview(){return!!this.getAttribute("preview")}get formConfig(){return v(this.form)}get form(){return this.getAttribute("form")}get formConfigValues(){return w(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,E,"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,E,t,"f"),b(t)}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(),r=(null===(t=null==i?void 0:i.flows)||void 0===t?void 0:t[this.flowId])||{};return null!==(e=r.version)&&void 0!==e||(r.version=0),r}))}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,r;const o=!!(null===(e=this.shadowRoot.activeElement)||void 0===e?void 0:e.getAttribute("href")),s=a.includes(null!==(r=null===(i=this.shadowRoot.activeElement)||void 0===i?void 0:i.localName)&&void 0!==r?r:"");if("Enter"!==t.key||o||s)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 u=Array.from(n).filter((t=>"true"===t.getAttribute("auto-submit")));if(1===u.length)return void u[0].click();const l=Array.from(n).filter((t=>"button"===t.getAttribute("data-type")));if(1===l.length)"false"!==l[0].getAttribute("auto-submit")&&l[0].click();else if(0===l.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 r=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=r.init)||void 0===e?void 0:e.call(this),t(this,S,"f").subscribe(t(this,x,"m",V).bind(this)),t(this,S,"f").update({isDebug:this.debug}),t(this,x,"m",N).call(this),yield t(this,x,"m",T).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 o=yield this.getConfig();if("isMissingConfig"in o&&o.isMissingConfig)return void this.loggerWrapper.error("Cannot get config file","Make sure that your projectId & flowId are correct");const{executionId:s,stepId:n,token:u,code:a,isPopup:d,exchangeError:c,redirectAuthCallbackUrl:h,redirectAuthBackupCallbackUri:g,redirectAuthCodeChallenge:f,redirectAuthInitiator:p,ssoQueryParams:m}=l(this.flowId,this.loggerWrapper);window.addEventListener("popstate",t(this,O,"f").popstate),window.addEventListener("components-context",t(this,O,"f").componentsContext),t(this,L,"f").subscribe(t(this,x,"m",R).bind(this)),t(this,L,"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:s,token:u,code:a,isPopup:d,exchangeError:c,redirectAuthCallbackUrl:h,redirectAuthBackupCallbackUri:g,redirectAuthCodeChallenge:f,redirectAuthInitiator:p},m)),i(this,j,!0,"f")}))}disconnectedCallback(){t(this,L,"f").unsubscribeAll(),t(this,S,"f").unsubscribeAll(),t(this,x,"m",J).call(this),window.removeEventListener("popstate",t(this,O,"f").popstate),window.removeEventListener("components-context",t(this,O,"f").componentsContext)}attributeChangedCallback(e,i,r){if(this.shadowRoot.isConnected&&t(this,j,"f")&&i!==r&&I.observedAttributes.includes(e)){t(this,x,"m",N).call(this);const o=null===i;t(this,L,"f").update((({stepId:t,executionId:i})=>{let s=t,n=i;return o||(n=null,s=null,d()),{[c(e)]:r,stepId:s,executionId:n}})),t(this,S,"f").update({isDebug:this.debug})}}}I=z,j=new WeakMap,E=new WeakMap,L=new WeakMap,S=new WeakMap,U=new WeakMap,M=new WeakMap,O=new WeakMap,W=new WeakMap,x=new WeakSet,D=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 ")},P=function(){t(this,x,"m",D).call(this),this.slotElement=document.createElement("slot"),this.slotElement.classList.add("hidden"),this.rootElement.appendChild(this.slotElement)},N=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","style-id","outbound-app-id","outbound-app-scopes"];I.observedAttributes.forEach((e=>{if(!t.includes(e)&&!this[c(e)])throw Error(`${e} cannot be empty`)}))},F=function(){const{stepId:e,executionId:i}=h(this.flowId);t(this,L,"f").update({stepId:e,executionId:i})},K=function(i,r){u&&"function"==typeof u||this.logger.error("SDK was not loaded properly",u,JSON.stringify(u));const o=Object.assign(Object.assign({persistTokens:!0,preview:this.preview,storagePrefix:this.storagePrefix,storeLastAuthenticatedUser:this.storeLastAuthenticatedUser,keepLastAuthenticatedUserAfterLogout:this.keepLastAuthenticatedUserAfterLogout,refreshCookieName:this.refreshCookieName},I.sdkConfigOverrides),{projectId:i,baseUrl:r});t(this,E,"f")&&(o.customStorage=t(this,E,"f")),this.sdk=u(o),["start","next"].forEach((t=>{const i=this.sdk.flow[t],r=p(i,1e3,3);this.sdk.flow[t]=(...i)=>e(this,void 0,void 0,(function*(){try{return yield r(...i)}catch(e){return this.logger.error(`Error in sdk flow ${t} function`,e),{error:{errorCode:A,errorDescription:e.toString()}}}}))}))},R=function(i,r,o){return e(this,void 0,void 0,(function*(){const{projectId:e,baseUrl:r}=i;if(o("projectId")||o("baseUrl")){if(!e)return;t(this,x,"m",K).call(this,e,r)}t(this,W,"f").call(this,i)}))},T=function(){return e(this,void 0,void 0,(function*(){const e=yield this.getConfig();return"isMissingConfig"in e&&e.isMissingConfig&&(yield t(this,x,"m",B).call(this))}))},B=function(){return e(this,void 0,void 0,(function*(){const t=g({projectId:this.projectId,filename:C,assetsFolder:y,baseUrl:this.baseStaticUrl});try{return yield f(t,"json"),!0}catch(t){return!1}}))},H=function(e){i(this,U,Object.assign(Object.assign({},t(this,U,"f")),e.detail),"f")},J=function(){var e;null===(e=t(this,M,"f"))||void 0===e||e.remove(),i(this,M,null,"f")},V=function(r){return e(this,arguments,void 0,(function*({isDebug:e}){e?(i(this,M,document.createElement("descope-debugger"),"f"),Object.assign(t(this,M,"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,M,"f"))):t(this,x,"m",J).call(this)}))},q=function(e,i){var r;e&&this.debug&&(null===(r=t(this,M,"f"))||void 0===r||r.updateData({title:e,description:i}))},z.sdkConfigOverrides={baseHeaders:{"x-descope-sdk-name":"web-component","x-descope-sdk-version":"3.59.1"}};export{z as default};
1
+ import{__classPrivateFieldGet as t,__awaiter as e,__classPrivateFieldSet as i}from"tslib";import{compose as r}from"@descope/sdk-helpers";import{staticResourcesMixin as o}from"@descope/sdk-mixins/static-resources-mixin";import{themeMixin as s}from"@descope/sdk-mixins/theme-mixin";import{injectStyleMixin as n}from"@descope/sdk-mixins/inject-style-mixin";import{createSdk as u}from"@descope/web-js-sdk";import{ELEMENTS_TO_IGNORE_ENTER_KEY_ON as a}from"../constants/index.js";import{handleUrlParams as l,clearRunIdsFromUrl as d,camelCase as c,getRunIdsFromUrl as h,getContentUrl as g,fetchContent as f,withRetry as p}from"../helpers/helpers.js";import m from"../helpers/state.js";import"@descope/escape-markdown";import"../helpers/webauthn.js";import{setCustomStorage as b}from"../helpers/storage.js";import{transformFlowInputFormData as v,extractNestedAttribute as w}from"../helpers/flowInputs.js";import{formMountMixin as k}from"../mixins/formMountMixin.js";import{CONFIG_FILENAME as C,PREV_VER_ASSETS_FOLDER as y}from"../constants/content.js";import{FETCH_EXCEPTION_ERROR_CODE as A}from"../constants/general.js";var x,I,j,E,L,S,U,M,O,W,D,P,N,F,K,R,T,B,H,J,V,q;const $=r(s,o,k,n)(HTMLElement);class z extends ${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","style-id"]}constructor(r){super(),x.add(this),j.set(this,!1),E.set(this,void 0),this.flowStatus="initial",this.loggerWrapper={error:(e,i="")=>{this.logger.error(e,i,new Error),t(this,x,"m",q).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)}},L.set(this,new m),S.set(this,new m),U.set(this,{}),this.getComponentsContext=()=>t(this,U,"f"),this.nextRequestStatus=new m({isLoading:!1}),M.set(this,void 0),O.set(this,{popstate:t(this,x,"m",F).bind(this),componentsContext:t(this,x,"m",H).bind(this)}),W.set(this,void 0),this.getConfig=()=>e(this,void 0,void 0,(function*(){return(yield this.config)||{isMissingConfig:!0}})),i(this,W,r,"f"),t(this,x,"m",P).call(this)}get flowId(){return this.getAttribute("flow-id")}get client(){try{return JSON.parse(this.getAttribute("client"))||{}}catch(t){return{}}}get tenantId(){return this.getAttribute("tenant")||void 0}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 preview(){return!!this.getAttribute("preview")}get formConfig(){return v(this.form)}get form(){return this.getAttribute("form")}get formConfigValues(){return w(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,E,"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,E,t,"f"),b(t)}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(),r=(null===(t=null==i?void 0:i.flows)||void 0===t?void 0:t[this.flowId])||{};return null!==(e=r.version)&&void 0!==e||(r.version=0),r}))}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,r;const o=!!(null===(e=this.shadowRoot.activeElement)||void 0===e?void 0:e.getAttribute("href")),s=a.includes(null!==(r=null===(i=this.shadowRoot.activeElement)||void 0===i?void 0:i.localName)&&void 0!==r?r:"");if("Enter"!==t.key||o||s)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 u=Array.from(n).filter((t=>"true"===t.getAttribute("auto-submit")));if(1===u.length)return void u[0].click();const l=Array.from(n).filter((t=>"button"===t.getAttribute("data-type")));if(1===l.length)"false"!==l[0].getAttribute("auto-submit")&&l[0].click();else if(0===l.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 r=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=r.init)||void 0===e?void 0:e.call(this),t(this,S,"f").subscribe(t(this,x,"m",V).bind(this)),t(this,S,"f").update({isDebug:this.debug}),t(this,x,"m",N).call(this),yield t(this,x,"m",T).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 o=yield this.getConfig();if("isMissingConfig"in o&&o.isMissingConfig)return void this.loggerWrapper.error("Cannot get config file","Make sure that your projectId & flowId are correct");const{executionId:s,stepId:n,token:u,code:a,isPopup:d,exchangeError:c,redirectAuthCallbackUrl:h,redirectAuthBackupCallbackUri:g,redirectAuthCodeChallenge:f,redirectAuthInitiator:p,ssoQueryParams:m}=l(this.flowId,this.loggerWrapper);window.addEventListener("popstate",t(this,O,"f").popstate),window.addEventListener("components-context",t(this,O,"f").componentsContext),t(this,L,"f").subscribe(t(this,x,"m",R).bind(this)),t(this,L,"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:s,token:u,code:a,isPopup:d,exchangeError:c,redirectAuthCallbackUrl:h,redirectAuthBackupCallbackUri:g,redirectAuthCodeChallenge:f,redirectAuthInitiator:p},m)),i(this,j,!0,"f")}))}disconnectedCallback(){t(this,L,"f").unsubscribeAll(),t(this,S,"f").unsubscribeAll(),t(this,x,"m",J).call(this),window.removeEventListener("popstate",t(this,O,"f").popstate),window.removeEventListener("components-context",t(this,O,"f").componentsContext)}attributeChangedCallback(e,i,r){if(this.shadowRoot.isConnected&&t(this,j,"f")&&i!==r&&I.observedAttributes.includes(e)){t(this,x,"m",N).call(this);const o=null===i;t(this,L,"f").update((({stepId:t,executionId:i})=>{let s=t,n=i;return o||(n=null,s=null,d()),{[c(e)]:r,stepId:s,executionId:n}})),t(this,S,"f").update({isDebug:this.debug})}}}I=z,j=new WeakMap,E=new WeakMap,L=new WeakMap,S=new WeakMap,U=new WeakMap,M=new WeakMap,O=new WeakMap,W=new WeakMap,x=new WeakSet,D=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 ")},P=function(){t(this,x,"m",D).call(this),this.slotElement=document.createElement("slot"),this.slotElement.classList.add("hidden"),this.rootElement.appendChild(this.slotElement)},N=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","style-id","outbound-app-id","outbound-app-scopes"];I.observedAttributes.forEach((e=>{if(!t.includes(e)&&!this[c(e)])throw Error(`${e} cannot be empty`)}))},F=function(){const{stepId:e,executionId:i}=h(this.flowId);t(this,L,"f").update({stepId:e,executionId:i})},K=function(i,r){u&&"function"==typeof u||this.logger.error("SDK was not loaded properly",u,JSON.stringify(u));const o=Object.assign(Object.assign({persistTokens:!0,preview:this.preview,storagePrefix:this.storagePrefix,storeLastAuthenticatedUser:this.storeLastAuthenticatedUser,keepLastAuthenticatedUserAfterLogout:this.keepLastAuthenticatedUserAfterLogout,refreshCookieName:this.refreshCookieName},I.sdkConfigOverrides),{projectId:i,baseUrl:r});t(this,E,"f")&&(o.customStorage=t(this,E,"f")),this.sdk=u(o),["start","next"].forEach((t=>{const i=this.sdk.flow[t],r=p(i,1e3,3);this.sdk.flow[t]=(...i)=>e(this,void 0,void 0,(function*(){try{return yield r(...i)}catch(e){return this.logger.error(`Error in sdk flow ${t} function`,e),{error:{errorCode:A,errorDescription:e.toString()}}}}))}))},R=function(i,r,o){return e(this,void 0,void 0,(function*(){const{projectId:e,baseUrl:r}=i;if(o("projectId")||o("baseUrl")){if(!e)return;t(this,x,"m",K).call(this,e,r)}t(this,W,"f").call(this,i)}))},T=function(){return e(this,void 0,void 0,(function*(){const e=yield this.getConfig();return"isMissingConfig"in e&&e.isMissingConfig&&(yield t(this,x,"m",B).call(this))}))},B=function(){return e(this,void 0,void 0,(function*(){const t=g({projectId:this.projectId,filename:C,assetsFolder:y,baseUrl:this.baseStaticUrl});try{return yield f(t,"json"),!0}catch(t){return!1}}))},H=function(e){i(this,U,Object.assign(Object.assign({},t(this,U,"f")),e.detail),"f")},J=function(){var e;null===(e=t(this,M,"f"))||void 0===e||e.remove(),i(this,M,null,"f")},V=function(r){return e(this,arguments,void 0,(function*({isDebug:e}){e?(i(this,M,document.createElement("descope-debugger"),"f"),Object.assign(t(this,M,"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,M,"f"))):t(this,x,"m",J).call(this)}))},q=function(e,i){var r;e&&this.debug&&(null===(r=t(this,M,"f"))||void 0===r||r.updateData({title:e,description:i}))},z.sdkConfigOverrides={baseHeaders:{"x-descope-sdk-name":"web-component","x-descope-sdk-version":"3.60.0"}};export{z as default};
2
2
  //# sourceMappingURL=BaseDescopeWc.js.map
@@ -1,2 +1,2 @@
1
- import{__classPrivateFieldGet as e,__classPrivateFieldSet as t,__awaiter as i,__rest as s}from"tslib";import{ensureFingerprintIds as o,clearFingerprintData as n}from"@descope/web-js-sdk";import{RESPONSE_ACTIONS as r,CUSTOM_INTERACTIONS as l,URL_CODE_PARAM_NAME as a,URL_ERR_PARAM_NAME as d,URL_TOKEN_PARAM_NAME as c,URL_RUN_IDS_PARAM_NAME as p,SDK_SCRIPTS_LOAD_TIMEOUT as h,DESCOPE_ATTRIBUTE_EXCLUDE_FIELD as u,ELEMENT_TYPE_ATTRIBUTE as g,DESCOPE_ATTRIBUTE_EXCLUDE_NEXT_BUTTON as v}from"../constants/index.js";import{timeoutPromise as m,withMemCache as f,leadingDebounce as b,getUserLocale as w,showFirstScreenOnExecutionInit as S,injectSamlIdpForm as y,injectWsFedIdpForm as I,openCenteredPopup as R,getAnimationDirection as C,handleAutoFocus as k,transformStepStateForCustomScreen as W,getElementDescopeAttributes as O,getScriptResultPath as x,submitForm as E,transformScreenInputs as A,handleReportValidityOnBlur as j,getFirstNonEmptyValue as T,clearPreviousExternalInputs as P}from"../helpers/helpers.js";import U from"../helpers/state.js";import{disableWebauthnButtons as L,updateTemplateFromScreenState as F,setComponentsAutoDetectByGeo as $,setComponentsAutoDetectByLocale as N,setTOTPVariable as M,setNOTPVariable as q,setCssVars as V,updateScreenFromScreenState as D,replaceElementMessage as B}from"../helpers/templates.js";import{isConditionalLoginSupported as K}from"../helpers/webauthn.js";import{getABTestingKey as H}from"../helpers/abTestingKey.js";import{calculateConditions as _,calculateCondition as G}from"../helpers/conditions.js";import{setLastAuth as J,getLastAuth as z}from"../helpers/lastAuth.js";import Q from"./BaseDescopeWc.js";import{FETCH_EXCEPTION_ERROR_CODE as X,FETCH_ERROR_RESPONSE_ERROR_CODE as Y,FLOW_REQUESTED_IS_IN_OLD_VERSION_ERROR_CODE as Z,FLOW_TIMED_OUT_ERROR_CODE as ee,POLLING_STATUS_NOT_FOUND_ERROR_CODE as te}from"../constants/general.js";var ie,se,oe,ne,re,le,ae,de,ce,pe,he,ue,ge,ve,me,fe,be,we,Se,ye,Ie,Re,Ce,ke,We,Oe,xe,Ee,Ae,je,Te,Pe,Ue,Le,Fe,$e,Ne,Me;class qe extends Q{static set sdkConfigOverrides(e){Q.sdkConfigOverrides=e}static get sdkConfigOverrides(){return Q.sdkConfigOverrides}constructor(){const s=new U({deferredRedirect:!1,deferredPolling:!1});super(s.update.bind(s)),ie.add(this),this.stepState=new U({}),se.set(this,void 0),oe.set(this,null),ne.set(this,null),re.set(this,{visibilitychange:e(this,ie,"m",le).bind(this)}),this.bridgeVersion=2,this.nativeCallbacks={},ve.set(this,!1),this.handleRedirect=e=>{window.location.assign(e)},fe.set(this,(t=>{const i=()=>{this.contentRootElement.classList.toggle("hidden",t),this.slotElement.classList.toggle("hidden",!t),t&&(this.contentRootElement.innerHTML="")};t&&this.contentRootElement.hasChildNodes()?e(this,ie,"m",be).call(this,i):i()})),we.set(this,((s,o,n,a,d=!1)=>{const c=[ee,te];if(this.flowState.current.action===r.poll){if(e(this,ye,"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 r=Date.now(),p=d?500:2e3;t(this,se,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,l.polling,n,a,{}),u=document.hidden&&!d&&Date.now()-r>p+500;let g;u&&this.logger.debug("polling - The polling seems to be throttled");try{const e=u?1e3:6e3;g=yield m(e,h)}catch(t){return this.logger.warn(`polling - The ${u?"throttled fetch":"fetch"} call timed out or was aborted`),void e(this,we,"f").call(this,s,o,n,a,u)}if((null===(t=null==g?void 0:g.error)||void 0===t?void 0:t.errorCode)===X)return this.logger.debug("polling - Got a generic error due to exception in fetch call"),void e(this,we,"f").call(this,s,o,n,a);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,we,"f").call(this,s,o,n,a),e(this,Ie,"f").call(this,g)}))),p),"f")}})),Se.set(this,(()=>{clearTimeout(e(this,se,"f")),t(this,se,null,"f")})),ye.set(this,(()=>!!window.descopeBridge||/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent))),Ie.set(this,(i=>{var s,o,n,l,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,r=`${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,ie,"m",Ne).call(this,"error",(null==i?void 0:i.error)||{errorCode:Y,errorDescription:r,errorMessage:t}),this.loggerWrapper.error((null===(l=null==i?void 0:i.error)||void 0===l?void 0:l.errorDescription)||t,(null===(a=null==i?void 0:i.error)||void 0===a?void 0:a.errorMessage)||r);const c=null===(d=null==i?void 0:i.error)||void 0===d?void 0:d.errorCode;return void(c!==Z&&c!==ee||!this.isRestartOnError||e(this,ie,"m",ge).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!==r.poll&&e(this,Se,"f").call(this),"completed"===b){this.storeLastAuthenticatedUser&&J(S);const t=Object.assign({},w);return i.data.output&&Object.keys(i.data.output).length>0&&(t.flowOutput=i.data.output),void e(this,ie,"m",Ne).call(this,"success",t)}this.storeLastAuthenticatedUser&&J(S,!0),I&&window.open(I,"_blank");const{executionId:R,stepId:C,stepName:k,screen:W,redirect:O,webauthn:x,error:E,samlIdpResponse:A,wsFedIdpResponse:j,nativeResponse:T}=i.data,P=Date.now();y!==r.poll?(this.loggerWrapper.info(`Step "${k||`#${C}`}" is ${b}`,"",{screen:W,status:b,stepId:C,stepName:k,action:y,error:E}),(null===(m=W.state)||void 0===m?void 0:m.clientScripts)&&t(this,ne,this.loadSdkScripts(W.state.clientScripts),"f"),this.flowState.update({stepId:C,stepName:k,executionId:R,action:y,redirectTo:null==O?void 0:O.url,redirectIsPopup:null==O?void 0:O.isPopup,screenId:null==W?void 0:W.id,screenState:null==W?void 0:W.state,webauthnTransactionId:null==x?void 0:x.transactionId,webauthnOptions:null==x?void 0:x.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})})),Re.set(this,f((()=>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)}}))))),Ee.set(this,null),Ue.set(this,b(((t,s)=>i(this,void 0,void 0,(function*(){var i;if("true"===t.getAttribute("formnovalidate")||e(this,ie,"m",Oe).call(this)){const o=null==t?void 0:t.getAttribute("id");e(this,ie,"m",Ae).call(this,t);const n=yield e(this,ie,"m",xe).call(this),r=O(t);this.nextRequestStatus.update({isLoading:!0});const l=Object.assign(Object.assign(Object.assign({},r),n),{origin:(null===(i=this.nativeOptions)||void 0===i?void 0:i.origin)||window.location.origin});yield s(o,l),this.nextRequestStatus.update({isLoading:!1}),e(this,ie,"m",je).call(this,n)}}))))),this.flowState=s}nativeResume(t,i){var s,o,n,r,l,h;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(a),e=(null===(o=i.searchParams)||void 0===o?void 0:o.get(d))||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(c),s=t.searchParams.get(p).split("_").pop();e(this,Se,"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===(h=(l=this.nativeCallbacks).complete)||void 0===h||h.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:{[x(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;const o=this.shadowRoot.querySelector(`[data-script-id="${e.id}"]`);if(o){this.loggerWrapper.debug("Script already loaded",e.id);const{moduleRes:t}=o;return null===(i=null==t?void 0:t.start)||void 0===i||i.call(t),t}yield this.injectNpmLib("@descope/flow-scripts","1.0.14",`dist/${e.id}.js`);const n=null===(s=globalThis.descope)||void 0===s?void 0:s[e.id];return new Promise(((i,s)=>{try{const s=n(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),this.nextRequestStatus.subscribe((()=>{var t;this.loggerWrapper.debug("Unloading script",e.id),null===(t=s.stop)||void 0===t||t.call(s)}))}}catch(e){s(e)}}))}))))),o=new Promise((e=>{setTimeout((()=>{this.loggerWrapper.warn("SDK scripts loading timeout"),e(!0)}),h)}));return Promise.race([s,o])}get isDismissScreenErrorOnInput(){return"true"===this.getAttribute("dismiss-screen-error-on-input")}init(){if(!window.descopeBridge)return this._init();this.lazyInit=this._init}_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,ie,"m",he).call(this),window.addEventListener("visibilitychange",e(this,re,"f").visibilitychange)),yield null===(s=t.init)||void 0===s?void 0:s.call(this)}))}disconnectedCallback(){var i;super.disconnectedCallback(),this.flowState.unsubscribeAll(),this.stepState.unsubscribeAll(),e(this,Se,"f").call(this),null===(i=e(this,oe,"f"))||void 0===i||i.abort(),t(this,oe,null,"f"),window.removeEventListener("visibilitychange",e(this,re,"f").visibilitychange)}getHtmlFilenameWithLocale(e,t){return i(this,void 0,void 0,(function*(){let i;const s=w(e),o=yield this.getTargetLocales();return o.includes(s.locale)?i=`${t}-${s.locale}.html`:o.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(a,d,c){return i(this,void 0,void 0,(function*(){var p,h;const{projectId:u,flowId:g,tenant:v,stepId:m,executionId:f,action:b,screenId:k,screenState:W,redirectTo:O,redirectIsPopup:x,redirectUrl:j,token:T,code:P,isPopup:U,exchangeError:L,webauthnTransactionId:F,webauthnOptions:$,redirectAuthCodeChallenge:N,redirectAuthCallbackUrl:M,redirectAuthBackupCallbackUri:q,redirectAuthInitiator:V,locale:D,samlIdpResponseUrl:B,samlIdpResponseSamlResponse:K,samlIdpResponseRelayState:J,wsFedIdpResponseUrl:Q,wsFedIdpResponseWresult:X,wsFedIdpResponseWctx:Y,nativeResponseType:Z,nativePayload:ee,reqTimestamp:te}=a,se=s(a,["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 re,le,ae;const de=H(),{outboundAppId:pe}=this,{outboundAppScopes:he}=this,ue=this.sdk.getLastUserLoginId(),ge=yield this.getFlowConfig(),ve=yield this.getProjectConfig(),fe=Object.entries(ve.flows||{}).reduce(((e,[t,i])=>(e[t]=i.version,e)),{}),be=M&&N?{callbackUrl:M,codeChallenge:N,backupCallbackUri:q}:void 0,Se=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}:void 0;let ye={};if(!f){const i=[...ge.clientScripts||[],...ge.sdkScripts||[]];if(ge.conditions){let e=[];({startScreenId:re,conditionInteractionId:ae,startScreenName:le,clientScripts:e,componentsConfig:ye}=_({loginId:ue,code:P,token:T,abTestingKey:de,lastAuth:z(ue)},ge.conditions)),i.push(...e||[])}else ge.condition?({startScreenId:re,conditionInteractionId:ae}=G(ge.condition,{loginId:ue,code:P,token:T,abTestingKey:de,lastAuth:z(ue)})):(le=ge.startScreenName,re=ge.startScreenId);if(t(this,ne,this.loadSdkScripts(i),"f"),ge.fingerprintEnabled&&ge.fingerprintKey?yield o(ge.fingerprintKey,this.baseUrl):n(),!S(re,se)){const t=yield this.sdk.flow.start(g,Object.assign(Object.assign(Object.assign(Object.assign({tenant:v,redirectAuth:be},se),{client:this.client}),j&&{redirectUrl:j}),{lastAuth:z(ue),abTestingKey:de,locale:w(D).locale,nativeOptions:Se,outboundAppId:pe,outboundAppScopes:he}),ae,"",ve.componentsVersion,fe,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),P?{exchangeCode:P,idpInitiated:!0}:{}),se.descopeIdpInitiated&&{idpInitiated:!0}),T?{token:T}:{}),se.oidcLoginHint?{externalId:se.oidcLoginHint}:{}));return e(this,Ie,"f").call(this,t),void("completed"!==(null===(p=null==t?void 0:t.data)||void 0===p?void 0:p.status)&&this.flowState.update({code:void 0,token:void 0}))}}if(this.loggerWrapper.debug("Before popup postmessage send",JSON.stringify({isPopup:U,code:P,exchangeError:L,isCodeChanged:c("code"),isExchangeErrorChanged:c("exchangeError")})),U&&(c("code")&&P||c("exchangeError")&&L))return void e(this,ie,"m",Me).call(this,f,P,L);if(f&&(c("token")&&T||c("code")&&P||c("exchangeError")&&L)){const t=yield this.sdk.flow.next(f,m,l.submit,ge.version,ve.componentsVersion,{token:T,exchangeCode:P,exchangeError:L});return e(this,Ie,"f").call(this,t),void this.flowState.update({token:void 0,code:void 0,exchangeError:void 0})}if(b===r.loadForm&&B&&["samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState"].some((e=>c(e)))){if(!K)return void this.loggerWrapper.error("Did not get saml idp params data to load");y(B,K,J||"",E)}if(b===r.loadForm&&Q&&["wsFedIdpResponseUrl","wsFedIdpResponseWresult","wsFedIdpResponseWctx"].some((e=>c(e)))){if(!X)return void this.loggerWrapper.error("Did not get wsfed idp params data to load");I(Q,X,Y||"",E)}if(b===r.redirect&&(c("redirectTo")||c("deferredRedirect"))){if(!O)return void this.loggerWrapper.error("Did not get redirect url");if("no-op"===O)return;if("android"===V&&document.hidden)return void this.flowState.update({deferredRedirect:!0});if(this.loggerWrapper.debug(`Redirect is popup ${x}`),x){this.loggerWrapper.debug("Opening redirect in popup");const t=R(O,"?",598,700),i=this.shouldUsePopupPostMessage();i&&(t.name=`descope-wc|${window.location.origin}`),this.loggerWrapper.debug("Popup communication method: "+(i?"postMessage":"BroadcastChannel"));const s=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:s,data:o}=e.data||{};"code"===s&&this.flowState.update({code:o.code,exchangeError:o.exchangeError})};let o;this.loggerWrapper.debug("Starting popup closed detection");const n=setInterval((()=>{t.closed&&(this.loggerWrapper.debug("Popup closed, dispatching popupclosed event"),clearInterval(n),e(this,ie,"m",Ne).call(this,"popupclosed",{}),this.loggerWrapper.debug("Cleaning up popup listeners"),null==o||o())}),1e3);if(i)window.addEventListener("message",s),o=()=>{this.loggerWrapper.debug("Cleaning up popup postMessage listener"),window.removeEventListener("message",s)};else{this.loggerWrapper.debug("Creating broadcast channel");const e=new BroadcastChannel(f);e.onmessage=s,o=()=>{this.loggerWrapper.debug("Closing channel"),e.close()}}}else this.handleRedirect(O),this.flowState.update({redirectTo:"no-op"}),e(this,ie,"m",Ne).call(this,"popupclosed",{});return}if(b===r.webauthnCreate||b===r.webauthnGet){if(!F||!$)return void this.loggerWrapper.error("Did not get webauthn transaction id or options");let i,s;null===(h=e(this,oe,"f"))||void 0===h||h.abort(),t(this,oe,null,"f");try{i=b===r.webauthnCreate?yield this.sdk.webauthn.helpers.create($):yield this.sdk.webauthn.helpers.get($)}catch(e){"InvalidStateError"===e.name?this.loggerWrapper.warn("WebAuthn operation failed",e.message):"NotAllowedError"!==e.name&&this.loggerWrapper.error(e.message),s=e.name}const o=yield this.sdk.flow.next(f,m,l.submit,ge.version,ve.componentsVersion,{transactionId:F,response:i,failure:s});e(this,Ie,"f").call(this,o)}if(b===r.nativeBridge)return this.nativeCallbacks.complete=t=>i(this,void 0,void 0,(function*(){const i=yield this.sdk.flow.next(f,m,l.submit,ge.version,ve.componentsVersion,t);e(this,Ie,"f").call(this,i)})),e(this,ie,"m",ce).call(this,Z,ee),void setTimeout((()=>{this.dispatchEvent(new Event("popupclosed"))}),500);if((c("action")||c("deferredPolling"))&&e(this,we,"f").call(this,f,m,ge.version,ve.componentsVersion),!k&&!re)return void this.loggerWrapper.warn("No screen was found to show");const Re=re||k,Ce=yield this.getHtmlFilenameWithLocale(D,Re),{oidcLoginHint:ke,oidcPrompt:We,oidcErrorRedirectUri:Oe,oidcResource:xe,samlIdpUsername:Ee}=se,Ae={direction:C(m,d.stepId),screenState:Object.assign(Object.assign({},W),{form:Object.assign(Object.assign({},this.formConfigValues),null==W?void 0:W.form),lastAuth:{loginId:ue,name:this.sdk.getLastUserDisplayName()||ue},componentsConfig:Object.assign(Object.assign(Object.assign({},ge.componentsConfig),ye),null==W?void 0:W.componentsConfig)}),htmlFilename:`${Re}.html`,htmlLocaleFilename:Ce,screenId:Re,stepName:a.stepName||le,samlIdpUsername:Ee,oidcLoginHint:ke,oidcPrompt:We,oidcErrorRedirectUri:Oe,oidcResource:xe,action:b,locale:w(D).locale},je=z(ue);S(re,se)?Ae.next=(t,s)=>i(this,void 0,void 0,(function*(){const i=(null==ge?void 0:ge.clientScripts)||[];yield e(this,ie,"m",Le).call(this,i);const o=yield this.sdk.flow.start(g,Object.assign(Object.assign(Object.assign(Object.assign({tenant:v,redirectAuth:be},se),{lastAuth:je,preview:this.preview,abTestingKey:de,client:this.client}),j&&{redirectUrl:j}),{locale:w(D).locale,nativeOptions:Se,outboundAppId:pe,outboundAppScopes:he}),ae,t,ve.componentsVersion,fe,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),this.getComponentsContext()),A(s)),P&&{exchangeCode:P,idpInitiated:!0}),se.descopeIdpInitiated&&{idpInitiated:!0}),T&&{token:T}),Ae.next.isCustomScreen);return e(this,Ie,"f").call(this,o),o})):(c("projectId")||c("baseUrl")||c("executionId")||c("stepId"))&&(Ae.next=(t,s)=>i(this,void 0,void 0,(function*(){const i=(null==W?void 0:W.clientScripts)||[];yield e(this,ie,"m",Le).call(this,i);const o=yield this.sdk.flow.next(f,m,t,ge.version,ve.componentsVersion,Object.assign(Object.assign({},this.getComponentsContext()),A(s)),Ae.next.isCustomScreen);return e(this,Ie,"f").call(this,o),o}))),this.loggerWrapper.debug("Got a screen with id",Ae.screenId),yield e(this,ie,"m",me).call(this,Ae),this.stepState.update(Ae)}))}onStepChange(t,s){return i(this,void 0,void 0,(function*(){var o,n,r;const{htmlFilename:a,htmlLocaleFilename:d,direction:c,next:p,screenState:h}=t;this.loggerWrapper.debug("Rendering a flow screen");const u=document.createElement("template");u.innerHTML=yield this.getPageContent(a,d);const v=u.content.cloneNode(!0),m=this.loadDescopeUiComponents(u);this.sdk.webauthn.helpers.isSupported()?yield e(this,ie,"m",ke).call(this,v,p):L(v),!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),F(v,h,this.formConfig,this.loggerWrapper);const{geo:f}=null!==(r=yield this.getExecutionContext())&&void 0!==r?r:{};$(v,f),N(v,t.locale);const b=()=>i(this,void 0,void 0,(function*(){var i,o;yield m;const n=this.contentRootElement;M(n,null===(i=null==h?void 0:h.totp)||void 0===i?void 0:i.image),q(n,null===(o=null==h?void 0:h.notp)||void 0===o?void 0:o.image),V(n,v,h.cssVars,this.loggerWrapper),n.replaceChildren(v);const r=!s.htmlFilename;setTimeout((()=>{e(this,ie,"m",Te).call(this),this.validateOnBlur&&j(n),D(n,h),e(this,ie,"m",We).call(this,{isFirstScreen:r,isCustomScreen:!1,stepName:t.stepName}),k(n,this.autoFocus,r)})),e(this,ie,"m",$e).call(this,p);n.querySelector(`[${g}="polling"]`)&&p(l.polling,{})}));c?e(this,ie,"m",be).call(this,b):b()}))}getInputs(){return Array.from(this.shadowRoot.querySelectorAll(`*:not(slot)[name]:not([${u}])`))}shouldUsePopupPostMessage(){if(!this.popupOrigin)return!1;try{new URL(this.popupOrigin)}catch(e){return!1}return!0}}se=new WeakMap,oe=new WeakMap,ne=new WeakMap,re=new WeakMap,ve=new WeakMap,fe=new WeakMap,we=new WeakMap,Se=new WeakMap,ye=new WeakMap,Ie=new WeakMap,Re=new WeakMap,Ee=new WeakMap,Ue=new WeakMap,ie=new WeakSet,le=function(){document.hidden||setTimeout((()=>{this.flowState.update({deferredRedirect:!1,deferredPolling:!1})}),300)},ae=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,ie,"m",ce).call(this,"beforeScreen",{screen:t,context:s})}))}))},de=function(t){var i;(null===(i=this.nativeOptions)||void 0===i?void 0:i.bridgeVersion)>=2&&e(this,ie,"m",ce).call(this,"afterScreen",{screen:t})},ce=function(t,i){e(this,ie,"m",Ne).call(this,"bridge",{type:t,payload:i})},pe=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)}B(this.contentRootElement,"error-message",s)};this.addEventListener("screen-updated",i,{once:!0}),i()},he=function(){var t,i,o;null===(t=this.stepState)||void 0===t||t.subscribe(this.onStepChange.bind(this),(e=>{var t=e.screenState,i=s(void 0===t?{}:t,["errorText","errorType"]),o=s(e,["screenState"]);return Object.assign(Object.assign({},o),{screenState:i})})),null===(i=this.stepState)||void 0===i||i.subscribe(e(this,ie,"m",pe).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,ie,"m",ue).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})},ue=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=""}))})),k(this.contentRootElement,this.autoFocus,!1))},ge=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")}))},me=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=W(a);let c=yield e(this,ie,"m",ae).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,fe,"f").call(this,c),r&&(r.isCustomScreen=c),e(this,ve,"f")!==c){const[i,s]=["flow","custom"].sort((()=>c?-1:1));this.loggerWrapper.debug(`Switching from ${s} screen to ${i} screen`),t(this,ve,c,"f"),c?this.stepState.unsubscribeAll():e(this,ie,"m",he).call(this)}c?(this.loggerWrapper.debug("Showing a custom screen"),e(this,ie,"m",We).call(this,{isFirstScreen:p,isCustomScreen:c,stepName:o.stepName}),this.disableKeyPressHandler()):this.handleKeyPress(),this.stepState.forceUpdate=c}))},be=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")},Ce=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)}))}},ke=function(s,o){return i(this,void 0,void 0,(function*(){var n;null===(n=e(this,oe,"f"))||void 0===n||n.abort();const r=s.querySelector('*[autocomplete="webauthn"]');if(r&&(yield K())){const{options:s,transactionId:n}=(yield e(this,Re,"f").call(this))||{};s&&n&&(e(this,ie,"m",Ce).call(this,r),t(this,oe,new AbortController,"f"),this.sdk.webauthn.helpers.conditional(s,e(this,oe,"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)})))}}))},We=function({isFirstScreen:t,isCustomScreen:i,stepName:s}){t&&e(this,ie,"m",Ne).call(this,"ready",{}),i||e(this,ie,"m",de).call(this,s),e(this,ie,"m",Ne).call(this,"page-updated",{screenName:s}),e(this,ie,"m",Ne).call(this,"screen-updated",{screenName:s})},Oe=function(){let e=!0;return Array.from(this.shadowRoot.querySelectorAll("*[name]")).reverse().forEach((t=>{var i,s;"slot"===t.localName||t.classList.contains("hidden")||(null===(i=t.reportValidity)||void 0===i||i.call(t),e&&(e=null===(s=t.checkValidity)||void 0===s?void 0:s.call(t)))})),e},xe=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})),{})}))},Ae=function(s){const o=Array.from(this.contentRootElement.querySelectorAll(':not([disabled]), [disabled="false"]')).filter((e=>e!==s)),n=()=>i(this,void 0,void 0,(function*(){this.loggerWrapper.debug("Restoring components state"),this.removeEventListener("popupclosed",n),s.removeAttribute("loading"),o.forEach((e=>{e.removeAttribute("disabled")}));const e=yield this.getFlowConfig(),t=[...e.clientScripts||[],...e.sdkScripts||[]];this.loadSdkScripts(t)})),r=()=>{var i;window.removeEventListener("pageshow",e(this,Ee,"f")),t(this,Ee,(e=>{e.persisted&&(this.logger.debug("Page was loaded from cache, restoring components state"),n())}),"f"),window.addEventListener("pageshow",e(this,Ee,"f"),{once:!0});const s=null===(i=this.stepState)||void 0===i?void 0:i.subscribe(((e,t)=>{e===t&&n(),this.removeEventListener("popupclosed",n),this.stepState.unsubscribe(s)}),(e=>e.screenId),{forceUpdate:!0})},l=this.nextRequestStatus.subscribe((({isLoading:e})=>{e?(this.addEventListener("popupclosed",n,{once:!0}),s.setAttribute("loading","true"),o.forEach((e=>e.setAttribute("disabled","true")))):(this.nextRequestStatus.unsubscribe(l),r())}))},je=function(e={}){var t,i;const s=T(e,["externalId","email","phone"]),o=T(e,["newPassword","password"]);if(s&&o)try{if(!globalThis.PasswordCredential)return;const e=new globalThis.PasswordCredential({id:s,password:o});null===(i=null===(t=null===navigator||void 0===navigator?void 0:navigator.credentials)||void 0===t?void 0:t.store)||void 0===i||i.call(t,e)}catch(e){this.loggerWrapper.error("Could not store credentials",e.message)}},Te=function(){P();this.contentRootElement.querySelectorAll('[external-input="true"]').forEach((t=>e(this,ie,"m",Pe).call(this,t)))},Pe=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)}))},Le=function(t){return i(this,void 0,void 0,(function*(){if(e(this,ne,"f")){this.loggerWrapper.debug("Waiting for sdk scripts to load");const t=Date.now();yield e(this,ne,"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 m(h,Promise.all(o),null)}catch(e){this.loggerWrapper.error("Failed to refresh script module",e.message)}}))},Fe=function(t){this.contentRootElement.querySelectorAll('descope-passcode[data-auto-submit="true"]').forEach((i=>{i.addEventListener("input",(()=>{var s;(null===(s=i.checkValidity)||void 0===s?void 0:s.call(i))&&e(this,Ue,"f").call(this,i,t)}))}))},$e=function(t){this.contentRootElement.querySelectorAll(`descope-button:not([${v}]), [data-type="button"]:not([${v}]`).forEach((i=>{i.onclick=()=>{e(this,Ue,"f").call(this,i,t)}})),e(this,ie,"m",Fe).call(this,t),this.isDismissScreenErrorOnInput&&this.contentRootElement.querySelectorAll(`*[name]:not([${u}])`).forEach((e=>{e.addEventListener("input",(()=>{this.stepState.update((e=>Object.assign(Object.assign({},e),{screenState:Object.assign(Object.assign({},e.screenState),{errorText:"",errorType:""})})))}))}))},Ne=function(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t}))},Me=function(e,t,i){var s;const[o,n]=(null===(s=window.name)||void 0===s?void 0:s.split("|"))||[],r={data:{code:t,exchangeError:i},action:"code"};if("descope-wc"===o&&n){this.loggerWrapper.debug("Using postMessage fallback to notify opener in origin",n);try{window.opener.postMessage(r,n)}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(r),t.close()}try{window.close()}catch(e){}};export{qe as default};
1
+ import{__classPrivateFieldGet as e,__classPrivateFieldSet as t,__awaiter as i,__rest as s}from"tslib";import{ensureFingerprintIds as o,clearFingerprintData as n}from"@descope/web-js-sdk";import{RESPONSE_ACTIONS as r,CUSTOM_INTERACTIONS as l,URL_CODE_PARAM_NAME as a,URL_ERR_PARAM_NAME as d,URL_TOKEN_PARAM_NAME as c,URL_RUN_IDS_PARAM_NAME as p,SDK_SCRIPTS_LOAD_TIMEOUT as h,DESCOPE_ATTRIBUTE_EXCLUDE_FIELD as u,ELEMENT_TYPE_ATTRIBUTE as g,DESCOPE_ATTRIBUTE_EXCLUDE_NEXT_BUTTON as v}from"../constants/index.js";import{timeoutPromise as m,withMemCache as f,leadingDebounce as b,getUserLocale as w,showFirstScreenOnExecutionInit as S,injectSamlIdpForm as y,injectWsFedIdpForm as I,openCenteredPopup as R,getAnimationDirection as C,handleAutoFocus as k,transformStepStateForCustomScreen as W,getElementDescopeAttributes as x,getScriptResultPath as O,submitForm as E,transformScreenInputs as A,handleReportValidityOnBlur as j,getFirstNonEmptyValue as T,clearPreviousExternalInputs as P}from"../helpers/helpers.js";import U from"../helpers/state.js";import{disableWebauthnButtons as L,updateTemplateFromScreenState as F,setComponentsAutoDetectByGeo as $,setComponentsAutoDetectByLocale as N,setTOTPVariable as M,setNOTPVariable as q,setCssVars as V,updateScreenFromScreenState as D,replaceElementMessage as B}from"../helpers/templates.js";import{isConditionalLoginSupported as K}from"../helpers/webauthn.js";import{getABTestingKey as H}from"../helpers/abTestingKey.js";import{calculateConditions as _,calculateCondition as G}from"../helpers/conditions.js";import{setLastAuth as J,getLastAuth as z}from"../helpers/lastAuth.js";import Q from"./BaseDescopeWc.js";import{FETCH_EXCEPTION_ERROR_CODE as X,FETCH_ERROR_RESPONSE_ERROR_CODE as Y,FLOW_REQUESTED_IS_IN_OLD_VERSION_ERROR_CODE as Z,FLOW_TIMED_OUT_ERROR_CODE as ee,POLLING_STATUS_NOT_FOUND_ERROR_CODE as te}from"../constants/general.js";var ie,se,oe,ne,re,le,ae,de,ce,pe,he,ue,ge,ve,me,fe,be,we,Se,ye,Ie,Re,Ce,ke,We,xe,Oe,Ee,Ae,je,Te,Pe,Ue,Le,Fe,$e,Ne,Me;class qe extends Q{static set sdkConfigOverrides(e){Q.sdkConfigOverrides=e}static get sdkConfigOverrides(){return Q.sdkConfigOverrides}constructor(){const s=new U({deferredRedirect:!1,deferredPolling:!1});super(s.update.bind(s)),ie.add(this),this.stepState=new U({}),se.set(this,void 0),oe.set(this,null),ne.set(this,null),re.set(this,{visibilitychange:e(this,ie,"m",le).bind(this)}),this.bridgeVersion=2,this.nativeCallbacks={},ve.set(this,!1),this.handleRedirect=e=>{window.location.assign(e)},fe.set(this,(t=>{const i=()=>{this.contentRootElement.classList.toggle("hidden",t),this.slotElement.classList.toggle("hidden",!t),t&&(this.contentRootElement.innerHTML="")};t&&this.contentRootElement.hasChildNodes()?e(this,ie,"m",be).call(this,i):i()})),we.set(this,((s,o,n,a,d=!1)=>{const c=[ee,te];if(this.flowState.current.action===r.poll){if(e(this,ye,"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 r=Date.now(),p=d?500:2e3;t(this,se,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,l.polling,n,a,{}),u=document.hidden&&!d&&Date.now()-r>p+500;let g;u&&this.logger.debug("polling - The polling seems to be throttled");try{const e=u?1e3:6e3;g=yield m(e,h)}catch(t){return this.logger.warn(`polling - The ${u?"throttled fetch":"fetch"} call timed out or was aborted`),void e(this,we,"f").call(this,s,o,n,a,u)}if((null===(t=null==g?void 0:g.error)||void 0===t?void 0:t.errorCode)===X)return this.logger.debug("polling - Got a generic error due to exception in fetch call"),void e(this,we,"f").call(this,s,o,n,a);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,we,"f").call(this,s,o,n,a),e(this,Ie,"f").call(this,g)}))),p),"f")}})),Se.set(this,(()=>{clearTimeout(e(this,se,"f")),t(this,se,null,"f")})),ye.set(this,(()=>!!window.descopeBridge||/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent))),Ie.set(this,(i=>{var s,o,n,l,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,r=`${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,ie,"m",Ne).call(this,"error",(null==i?void 0:i.error)||{errorCode:Y,errorDescription:r,errorMessage:t}),this.loggerWrapper.error((null===(l=null==i?void 0:i.error)||void 0===l?void 0:l.errorDescription)||t,(null===(a=null==i?void 0:i.error)||void 0===a?void 0:a.errorMessage)||r);const c=null===(d=null==i?void 0:i.error)||void 0===d?void 0:d.errorCode;return void(c!==Z&&c!==ee||!this.isRestartOnError||e(this,ie,"m",ge).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!==r.poll&&e(this,Se,"f").call(this),"completed"===b){this.storeLastAuthenticatedUser&&J(S);const t=Object.assign({},w);return i.data.output&&Object.keys(i.data.output).length>0&&(t.flowOutput=i.data.output),void e(this,ie,"m",Ne).call(this,"success",t)}this.storeLastAuthenticatedUser&&J(S,!0),I&&window.open(I,"_blank");const{executionId:R,stepId:C,stepName:k,screen:W,redirect:x,webauthn:O,error:E,samlIdpResponse:A,wsFedIdpResponse:j,nativeResponse:T}=i.data,P=Date.now();y!==r.poll?(this.loggerWrapper.info(`Step "${k||`#${C}`}" is ${b}`,"",{screen:W,status:b,stepId:C,stepName:k,action:y,error:E}),(null===(m=W.state)||void 0===m?void 0:m.clientScripts)&&t(this,ne,this.loadSdkScripts(W.state.clientScripts),"f"),this.flowState.update({stepId:C,stepName:k,executionId:R,action:y,redirectTo:null==x?void 0:x.url,redirectIsPopup:null==x?void 0:x.isPopup,screenId:null==W?void 0:W.id,screenState:null==W?void 0:W.state,webauthnTransactionId:null==O?void 0:O.transactionId,webauthnOptions:null==O?void 0:O.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})})),Re.set(this,f((()=>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)}}))))),Ee.set(this,null),Ue.set(this,b(((t,s)=>i(this,void 0,void 0,(function*(){var i;if("true"===t.getAttribute("formnovalidate")||e(this,ie,"m",xe).call(this)){const o=null==t?void 0:t.getAttribute("id");e(this,ie,"m",Ae).call(this,t);const n=yield e(this,ie,"m",Oe).call(this),r=x(t);this.nextRequestStatus.update({isLoading:!0});const l=Object.assign(Object.assign(Object.assign({},r),n),{origin:(null===(i=this.nativeOptions)||void 0===i?void 0:i.origin)||window.location.origin});yield s(o,l),this.nextRequestStatus.update({isLoading:!1}),e(this,ie,"m",je).call(this,n)}}))))),this.flowState=s}nativeResume(t,i){var s,o,n,r,l,h;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(a),e=(null===(o=i.searchParams)||void 0===o?void 0:o.get(d))||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(c),s=t.searchParams.get(p).split("_").pop();e(this,Se,"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===(h=(l=this.nativeCallbacks).complete)||void 0===h||h.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:{[O(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;const o=this.shadowRoot.querySelector(`[data-script-id="${e.id}"]`);if(o){this.loggerWrapper.debug("Script already loaded",e.id);const{moduleRes:t}=o;return null===(i=null==t?void 0:t.start)||void 0===i||i.call(t),t}yield this.injectNpmLib("@descope/flow-scripts","1.0.14",`dist/${e.id}.js`);const n=null===(s=globalThis.descope)||void 0===s?void 0:s[e.id];return new Promise(((i,s)=>{try{const s=n(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),this.nextRequestStatus.subscribe((()=>{var t;this.loggerWrapper.debug("Unloading script",e.id),null===(t=s.stop)||void 0===t||t.call(s)}))}}catch(e){s(e)}}))}))))),o=new Promise((e=>{setTimeout((()=>{this.loggerWrapper.warn("SDK scripts loading timeout"),e(!0)}),h)}));return Promise.race([s,o])}get isDismissScreenErrorOnInput(){return"true"===this.getAttribute("dismiss-screen-error-on-input")}init(){if(!window.descopeBridge)return this._init();this.lazyInit=this._init}_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,ie,"m",he).call(this),window.addEventListener("visibilitychange",e(this,re,"f").visibilitychange)),yield null===(s=t.init)||void 0===s?void 0:s.call(this)}))}disconnectedCallback(){var i;super.disconnectedCallback(),this.flowState.unsubscribeAll(),this.stepState.unsubscribeAll(),e(this,Se,"f").call(this),null===(i=e(this,oe,"f"))||void 0===i||i.abort(),t(this,oe,null,"f"),window.removeEventListener("visibilitychange",e(this,re,"f").visibilitychange)}getHtmlFilenameWithLocale(e,t){return i(this,void 0,void 0,(function*(){let i;const s=w(e),o=yield this.getTargetLocales();return o.includes(s.locale)?i=`${t}-${s.locale}.html`:o.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(a,d,c){return i(this,void 0,void 0,(function*(){var p,h;const{projectId:u,flowId:g,tenant:v,stepId:m,executionId:f,action:b,screenId:k,screenState:W,redirectTo:x,redirectIsPopup:O,redirectUrl:j,token:T,code:P,isPopup:U,exchangeError:L,webauthnTransactionId:F,webauthnOptions:$,redirectAuthCodeChallenge:N,redirectAuthCallbackUrl:M,redirectAuthBackupCallbackUri:q,redirectAuthInitiator:V,locale:D,samlIdpResponseUrl:B,samlIdpResponseSamlResponse:K,samlIdpResponseRelayState:J,wsFedIdpResponseUrl:Q,wsFedIdpResponseWresult:X,wsFedIdpResponseWctx:Y,nativeResponseType:Z,nativePayload:ee,reqTimestamp:te}=a,se=s(a,["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 re,le,ae;const de=H(),{outboundAppId:pe}=this,{outboundAppScopes:he}=this,ue=this.sdk.getLastUserLoginId(),ge=yield this.getFlowConfig(),ve=yield this.getProjectConfig(),fe=Object.entries(ve.flows||{}).reduce(((e,[t,i])=>(e[t]=i.version,e)),{}),be=M&&N?{callbackUrl:M,codeChallenge:N,backupCallbackUri:q}:void 0,Se=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 ye={};if(!f){const i=[...ge.clientScripts||[],...ge.sdkScripts||[]];if(ge.conditions){let e=[];({startScreenId:re,conditionInteractionId:ae,startScreenName:le,clientScripts:e,componentsConfig:ye}=_({loginId:ue,code:P,token:T,abTestingKey:de,lastAuth:z(ue)},ge.conditions)),i.push(...e||[])}else ge.condition?({startScreenId:re,conditionInteractionId:ae}=G(ge.condition,{loginId:ue,code:P,token:T,abTestingKey:de,lastAuth:z(ue)})):(le=ge.startScreenName,re=ge.startScreenId);if(t(this,ne,this.loadSdkScripts(i),"f"),ge.fingerprintEnabled&&ge.fingerprintKey?yield o(ge.fingerprintKey,this.baseUrl):n(),!S(re,se)){const t=yield this.sdk.flow.start(g,Object.assign(Object.assign(Object.assign(Object.assign({tenant:v,redirectAuth:be},se),{client:this.client}),j&&{redirectUrl:j}),{lastAuth:z(ue),abTestingKey:de,locale:w(D).locale,nativeOptions:Se,outboundAppId:pe,outboundAppScopes:he}),ae,"",ve.componentsVersion,fe,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),P?{exchangeCode:P,idpInitiated:!0}:{}),se.descopeIdpInitiated&&{idpInitiated:!0}),T?{token:T}:{}),se.oidcLoginHint?{externalId:se.oidcLoginHint}:{}));return e(this,Ie,"f").call(this,t),void("completed"!==(null===(p=null==t?void 0:t.data)||void 0===p?void 0:p.status)&&this.flowState.update({code:void 0,token:void 0}))}}if(this.loggerWrapper.debug("Before popup postmessage send",JSON.stringify({isPopup:U,code:P,exchangeError:L,isCodeChanged:c("code"),isExchangeErrorChanged:c("exchangeError")})),U&&(c("code")&&P||c("exchangeError")&&L))return void e(this,ie,"m",Me).call(this,f,P,L);if(f&&(c("token")&&T||c("code")&&P||c("exchangeError")&&L)){const t=yield this.sdk.flow.next(f,m,l.submit,ge.version,ve.componentsVersion,{token:T,exchangeCode:P,exchangeError:L});return e(this,Ie,"f").call(this,t),void this.flowState.update({token:void 0,code:void 0,exchangeError:void 0})}if(b===r.loadForm&&B&&["samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState"].some((e=>c(e)))){if(!K)return void this.loggerWrapper.error("Did not get saml idp params data to load");y(B,K,J||"",E)}if(b===r.loadForm&&Q&&["wsFedIdpResponseUrl","wsFedIdpResponseWresult","wsFedIdpResponseWctx"].some((e=>c(e)))){if(!X)return void this.loggerWrapper.error("Did not get wsfed idp params data to load");I(Q,X,Y||"",E)}if(b===r.redirect&&(c("redirectTo")||c("deferredRedirect"))){if(!x)return void this.loggerWrapper.error("Did not get redirect url");if("no-op"===x)return;if("android"===V&&document.hidden)return void this.flowState.update({deferredRedirect:!0});if(this.loggerWrapper.debug(`Redirect is popup ${O}`),O){this.loggerWrapper.debug("Opening redirect in popup");const t=R(x,"?",598,700),i=this.shouldUsePopupPostMessage();i&&(t.name=`descope-wc|${window.location.origin}`),this.loggerWrapper.debug("Popup communication method: "+(i?"postMessage":"BroadcastChannel"));const s=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:s,data:o}=e.data||{};"code"===s&&this.flowState.update({code:o.code,exchangeError:o.exchangeError})};let o;this.loggerWrapper.debug("Starting popup closed detection");const n=setInterval((()=>{t.closed&&(this.loggerWrapper.debug("Popup closed, dispatching popupclosed event"),clearInterval(n),e(this,ie,"m",Ne).call(this,"popupclosed",{}),this.loggerWrapper.debug("Cleaning up popup listeners"),null==o||o())}),1e3);if(i)window.addEventListener("message",s),o=()=>{this.loggerWrapper.debug("Cleaning up popup postMessage listener"),window.removeEventListener("message",s)};else{this.loggerWrapper.debug("Creating broadcast channel");const e=new BroadcastChannel(f);e.onmessage=s,o=()=>{this.loggerWrapper.debug("Closing channel"),e.close()}}}else this.handleRedirect(x),this.flowState.update({redirectTo:"no-op"}),e(this,ie,"m",Ne).call(this,"popupclosed",{});return}if(b===r.webauthnCreate||b===r.webauthnGet){if(!F||!$)return void this.loggerWrapper.error("Did not get webauthn transaction id or options");let i,s;null===(h=e(this,oe,"f"))||void 0===h||h.abort(),t(this,oe,null,"f");try{i=b===r.webauthnCreate?yield this.sdk.webauthn.helpers.create($):yield this.sdk.webauthn.helpers.get($)}catch(e){"InvalidStateError"===e.name?this.loggerWrapper.warn("WebAuthn operation failed",e.message):"NotAllowedError"!==e.name&&this.loggerWrapper.error(e.message),s=e.name}const o=yield this.sdk.flow.next(f,m,l.submit,ge.version,ve.componentsVersion,{transactionId:F,response:i,failure:s});e(this,Ie,"f").call(this,o)}if(b===r.nativeBridge)return this.nativeCallbacks.complete=t=>i(this,void 0,void 0,(function*(){const i=yield this.sdk.flow.next(f,m,l.submit,ge.version,ve.componentsVersion,t);e(this,Ie,"f").call(this,i)})),e(this,ie,"m",ce).call(this,Z,ee),void setTimeout((()=>{this.dispatchEvent(new Event("popupclosed"))}),500);if((c("action")||c("deferredPolling"))&&e(this,we,"f").call(this,f,m,ge.version,ve.componentsVersion),!k&&!re)return void this.loggerWrapper.warn("No screen was found to show");const Re=re||k,Ce=yield this.getHtmlFilenameWithLocale(D,Re),{oidcLoginHint:ke,oidcPrompt:We,oidcErrorRedirectUri:xe,oidcResource:Oe,samlIdpUsername:Ee}=se,Ae={direction:C(m,d.stepId),screenState:Object.assign(Object.assign({},W),{form:Object.assign(Object.assign({},this.formConfigValues),null==W?void 0:W.form),lastAuth:{loginId:ue,name:this.sdk.getLastUserDisplayName()||ue},componentsConfig:Object.assign(Object.assign(Object.assign({},ge.componentsConfig),ye),null==W?void 0:W.componentsConfig)}),htmlFilename:`${Re}.html`,htmlLocaleFilename:Ce,screenId:Re,stepName:a.stepName||le,samlIdpUsername:Ee,oidcLoginHint:ke,oidcPrompt:We,oidcErrorRedirectUri:xe,oidcResource:Oe,action:b,locale:w(D).locale},je=z(ue);S(re,se)?Ae.next=(t,s)=>i(this,void 0,void 0,(function*(){const i=(null==ge?void 0:ge.clientScripts)||[];yield e(this,ie,"m",Le).call(this,i);const o=yield this.sdk.flow.start(g,Object.assign(Object.assign(Object.assign(Object.assign({tenant:v,redirectAuth:be},se),{lastAuth:je,preview:this.preview,abTestingKey:de,client:this.client}),j&&{redirectUrl:j}),{locale:w(D).locale,nativeOptions:Se,outboundAppId:pe,outboundAppScopes:he}),ae,t,ve.componentsVersion,fe,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),this.getComponentsContext()),A(s)),P&&{exchangeCode:P,idpInitiated:!0}),se.descopeIdpInitiated&&{idpInitiated:!0}),T&&{token:T}),Ae.next.isCustomScreen);return e(this,Ie,"f").call(this,o),o})):(c("projectId")||c("baseUrl")||c("executionId")||c("stepId"))&&(Ae.next=(t,s)=>i(this,void 0,void 0,(function*(){const i=(null==W?void 0:W.clientScripts)||[];yield e(this,ie,"m",Le).call(this,i);const o=yield this.sdk.flow.next(f,m,t,ge.version,ve.componentsVersion,Object.assign(Object.assign({},this.getComponentsContext()),A(s)),Ae.next.isCustomScreen);return e(this,Ie,"f").call(this,o),o}))),this.loggerWrapper.debug("Got a screen with id",Ae.screenId),yield e(this,ie,"m",me).call(this,Ae),this.stepState.update(Ae)}))}onStepChange(t,s){return i(this,void 0,void 0,(function*(){var o,n,r;const{htmlFilename:a,htmlLocaleFilename:d,direction:c,next:p,screenState:h}=t;this.loggerWrapper.debug("Rendering a flow screen");const u=document.createElement("template");u.innerHTML=yield this.getPageContent(a,d);const v=u.content.cloneNode(!0),m=this.loadDescopeUiComponents(u);this.sdk.webauthn.helpers.isSupported()?yield e(this,ie,"m",ke).call(this,v,p):L(v),!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),F(v,h,this.formConfig,this.loggerWrapper);const{geo:f}=null!==(r=yield this.getExecutionContext())&&void 0!==r?r:{};$(v,f),N(v,t.locale);const b=()=>i(this,void 0,void 0,(function*(){var i,o;yield m;const n=this.contentRootElement;M(n,null===(i=null==h?void 0:h.totp)||void 0===i?void 0:i.image),q(n,null===(o=null==h?void 0:h.notp)||void 0===o?void 0:o.image),V(n,v,h.cssVars,this.loggerWrapper),n.replaceChildren(v);const r=!s.htmlFilename;setTimeout((()=>{e(this,ie,"m",Te).call(this),this.validateOnBlur&&j(n),D(n,h),e(this,ie,"m",We).call(this,{isFirstScreen:r,isCustomScreen:!1,stepName:t.stepName}),k(n,this.autoFocus,r)})),e(this,ie,"m",$e).call(this,p);n.querySelector(`[${g}="polling"]`)&&p(l.polling,{})}));c?e(this,ie,"m",be).call(this,b):b()}))}getInputs(){return Array.from(this.shadowRoot.querySelectorAll(`*:not(slot)[name]:not([${u}])`))}shouldUsePopupPostMessage(){if(!this.popupOrigin)return!1;try{new URL(this.popupOrigin)}catch(e){return!1}return!0}}se=new WeakMap,oe=new WeakMap,ne=new WeakMap,re=new WeakMap,ve=new WeakMap,fe=new WeakMap,we=new WeakMap,Se=new WeakMap,ye=new WeakMap,Ie=new WeakMap,Re=new WeakMap,Ee=new WeakMap,Ue=new WeakMap,ie=new WeakSet,le=function(){document.hidden||setTimeout((()=>{this.flowState.update({deferredRedirect:!1,deferredPolling:!1})}),300)},ae=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,ie,"m",ce).call(this,"beforeScreen",{screen:t,context:s})}))}))},de=function(t){var i;(null===(i=this.nativeOptions)||void 0===i?void 0:i.bridgeVersion)>=2&&e(this,ie,"m",ce).call(this,"afterScreen",{screen:t})},ce=function(t,i){e(this,ie,"m",Ne).call(this,"bridge",{type:t,payload:i})},pe=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)}B(this.contentRootElement,"error-message",s)};this.addEventListener("screen-updated",i,{once:!0}),i()},he=function(){var t,i,o;null===(t=this.stepState)||void 0===t||t.subscribe(this.onStepChange.bind(this),(e=>{var t=e.screenState,i=s(void 0===t?{}:t,["errorText","errorType"]),o=s(e,["screenState"]);return Object.assign(Object.assign({},o),{screenState:i})})),null===(i=this.stepState)||void 0===i||i.subscribe(e(this,ie,"m",pe).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,ie,"m",ue).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})},ue=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=""}))})),k(this.contentRootElement,this.autoFocus,!1))},ge=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")}))},me=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=W(a);let c=yield e(this,ie,"m",ae).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,fe,"f").call(this,c),r&&(r.isCustomScreen=c),e(this,ve,"f")!==c){const[i,s]=["flow","custom"].sort((()=>c?-1:1));this.loggerWrapper.debug(`Switching from ${s} screen to ${i} screen`),t(this,ve,c,"f"),c?this.stepState.unsubscribeAll():e(this,ie,"m",he).call(this)}c?(this.loggerWrapper.debug("Showing a custom screen"),e(this,ie,"m",We).call(this,{isFirstScreen:p,isCustomScreen:c,stepName:o.stepName}),this.disableKeyPressHandler()):this.handleKeyPress(),this.stepState.forceUpdate=c}))},be=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")},Ce=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)}))}},ke=function(s,o){return i(this,void 0,void 0,(function*(){var n;null===(n=e(this,oe,"f"))||void 0===n||n.abort();const r=s.querySelector('*[autocomplete="webauthn"]');if(r&&(yield K())){const{options:s,transactionId:n}=(yield e(this,Re,"f").call(this))||{};s&&n&&(e(this,ie,"m",Ce).call(this,r),t(this,oe,new AbortController,"f"),this.sdk.webauthn.helpers.conditional(s,e(this,oe,"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)})))}}))},We=function({isFirstScreen:t,isCustomScreen:i,stepName:s}){t&&e(this,ie,"m",Ne).call(this,"ready",{}),i||e(this,ie,"m",de).call(this,s),e(this,ie,"m",Ne).call(this,"page-updated",{screenName:s}),e(this,ie,"m",Ne).call(this,"screen-updated",{screenName:s})},xe=function(){let e=!0;return Array.from(this.shadowRoot.querySelectorAll("*[name]")).reverse().forEach((t=>{var i,s;"slot"===t.localName||t.classList.contains("hidden")||(null===(i=t.reportValidity)||void 0===i||i.call(t),e&&(e=null===(s=t.checkValidity)||void 0===s?void 0:s.call(t)))})),e},Oe=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})),{})}))},Ae=function(s){const o=Array.from(this.contentRootElement.querySelectorAll(':not([disabled]), [disabled="false"]')).filter((e=>e!==s)),n=()=>i(this,void 0,void 0,(function*(){this.loggerWrapper.debug("Restoring components state"),this.removeEventListener("popupclosed",n),s.removeAttribute("loading"),o.forEach((e=>{e.removeAttribute("disabled")}));const e=yield this.getFlowConfig(),t=[...e.clientScripts||[],...e.sdkScripts||[]];this.loadSdkScripts(t)})),r=()=>{var i;window.removeEventListener("pageshow",e(this,Ee,"f")),t(this,Ee,(e=>{e.persisted&&(this.logger.debug("Page was loaded from cache, restoring components state"),n())}),"f"),window.addEventListener("pageshow",e(this,Ee,"f"),{once:!0});const s=null===(i=this.stepState)||void 0===i?void 0:i.subscribe(((e,t)=>{e===t&&n(),this.removeEventListener("popupclosed",n),this.stepState.unsubscribe(s)}),(e=>e.screenId),{forceUpdate:!0})},l=this.nextRequestStatus.subscribe((({isLoading:e})=>{e?(this.addEventListener("popupclosed",n,{once:!0}),s.setAttribute("loading","true"),o.forEach((e=>e.setAttribute("disabled","true")))):(this.nextRequestStatus.unsubscribe(l),r())}))},je=function(e={}){var t,i;const s=T(e,["externalId","email","phone"]),o=T(e,["newPassword","password"]);if(s&&o)try{if(!globalThis.PasswordCredential)return;const e=new globalThis.PasswordCredential({id:s,password:o});null===(i=null===(t=null===navigator||void 0===navigator?void 0:navigator.credentials)||void 0===t?void 0:t.store)||void 0===i||i.call(t,e)}catch(e){this.loggerWrapper.error("Could not store credentials",e.message)}},Te=function(){P();this.contentRootElement.querySelectorAll('[external-input="true"]').forEach((t=>e(this,ie,"m",Pe).call(this,t)))},Pe=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)}))},Le=function(t){return i(this,void 0,void 0,(function*(){if(e(this,ne,"f")){this.loggerWrapper.debug("Waiting for sdk scripts to load");const t=Date.now();yield e(this,ne,"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 m(h,Promise.all(o),null)}catch(e){this.loggerWrapper.error("Failed to refresh script module",e.message)}}))},Fe=function(t){this.contentRootElement.querySelectorAll('descope-passcode[data-auto-submit="true"]').forEach((i=>{i.addEventListener("input",(()=>{var s;(null===(s=i.checkValidity)||void 0===s?void 0:s.call(i))&&e(this,Ue,"f").call(this,i,t)}))}))},$e=function(t){this.contentRootElement.querySelectorAll(`descope-button:not([${v}]), [data-type="button"]:not([${v}]`).forEach((i=>{i.onclick=()=>{e(this,Ue,"f").call(this,i,t)}})),e(this,ie,"m",Fe).call(this,t),this.isDismissScreenErrorOnInput&&this.contentRootElement.querySelectorAll(`*[name]:not([${u}])`).forEach((e=>{e.addEventListener("input",(()=>{this.stepState.update((e=>Object.assign(Object.assign({},e),{screenState:Object.assign(Object.assign({},e.screenState),{errorText:"",errorType:""})})))}))}))},Ne=function(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t}))},Me=function(e,t,i){var s;const[o,n]=(null===(s=window.name)||void 0===s?void 0:s.split("|"))||[],r={data:{code:t,exchangeError:i},action:"code"};if("descope-wc"===o&&n){this.loggerWrapper.debug("Using postMessage fallback to notify opener in origin",n);try{window.opener.postMessage(r,n)}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(r),t.close()}try{window.close()}catch(e){}};export{qe as default};
2
2
  //# sourceMappingURL=DescopeWc.js.map