@descope/web-component 4.0.1 → 4.1.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.
- package/dist/cjs/descope-wc/BaseDescopeWc.js +1 -1
- package/dist/cjs/descope-wc/DescopeWc.js +1 -1
- package/dist/cjs/descope-wc/DescopeWc.js.map +1 -1
- package/dist/cjs/mixins/passwordManagerMixin.js +1 -1
- package/dist/cjs/mixins/passwordManagerMixin.js.map +1 -1
- package/dist/esm/descope-wc/BaseDescopeWc.js +1 -1
- package/dist/esm/descope-wc/DescopeWc.js +1 -1
- package/dist/esm/descope-wc/DescopeWc.js.map +1 -1
- package/dist/esm/mixins/passwordManagerMixin.js +1 -1
- package/dist/esm/mixins/passwordManagerMixin.js.map +1 -1
- package/dist/index.d.ts +73 -72
- package/dist/index.js +2 -2
- package/package.json +4 -4
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var e=require("tslib"),t=require("@descope/sdk-helpers"),i=require("@descope/sdk-mixins"),r=require("../constants/index.js"),s=require("../helpers/helpers.js");require("../helpers/state.js"),require("@descope/escape-markdown"),require("../helpers/webauthn.js");const n=["externalId","email","phone"],o=["newPassword","password"],a="data-username-anchor",l=e=>{var t;if(!e)return"";try{const i=null===(t=window.sessionStorage)||void 0===t?void 0:t.getItem(r.DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY);if(!i)return"";const s=JSON.parse(i);return s.executionId===e&&s.loginId||""}catch(e){return""}},d=(e,t,i,s)=>{var o;const l=(null==i?void 0:i.email)||(null===(o=null==i?void 0:i.loginIds)||void 0===o?void 0:o[0]);(e=>e.querySelector("descope-new-password")||e.querySelector("descope-password"))(t)?l?(e=>{const t=['input[autocomplete="username"]',...n.map((e=>`[name="${e}"]`))].join(", ");return e.some((e=>e.querySelector(t)))})([e,t])?s.debug("Username anchor: screen already has an identifier field"):(s.debug("Username anchor: injecting hidden username input"),e.appendChild((e=>{const t=document.createElement("input");return t.setAttribute("autocomplete","username"),t.setAttribute("name","username"),t.setAttribute("type","email"),t.setAttribute("readonly","true"),t.setAttribute("tabindex","-1"),t.setAttribute("aria-hidden","true"),t.setAttribute(r.DESCOPE_ATTRIBUTE_EXCLUDE_FIELD,"true"),t.setAttribute(a,"true"),t.setAttribute("value",e),t.value=e,Object.assign(t.style,{position:"absolute",opacity:"0",pointerEvents:"none",height:"0",border:"0"}),t})(l))):s.debug("Username anchor: no user identifier available"):s.debug("Username anchor: no password component on screen")},u=t.createSingletonMixin((u=>{var c,v,
|
|
1
|
+
"use strict";var e=require("tslib"),t=require("@descope/sdk-helpers"),i=require("@descope/sdk-mixins"),r=require("../constants/index.js"),s=require("../helpers/helpers.js");require("../helpers/state.js"),require("@descope/escape-markdown"),require("../helpers/webauthn.js");const n=["externalId","email","phone"],o=["newPassword","password"],a="data-username-anchor",l=e=>{var t;if(!e)return"";try{const i=null===(t=window.sessionStorage)||void 0===t?void 0:t.getItem(r.DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY);if(!i)return"";const s=JSON.parse(i);return s.executionId===e&&s.loginId||""}catch(e){return""}},d=(e,t,i,s)=>{var o;const l=(null==i?void 0:i.email)||(null===(o=null==i?void 0:i.loginIds)||void 0===o?void 0:o[0]);(e=>e.querySelector("descope-new-password")||e.querySelector("descope-password"))(t)?l?(e=>{const t=['input[autocomplete="username"]',...n.map((e=>`[name="${e}"]`))].join(", ");return e.some((e=>e.querySelector(t)))})([e,t])?s.debug("Username anchor: screen already has an identifier field"):(s.debug("Username anchor: injecting hidden username input"),e.appendChild((e=>{const t=document.createElement("input");return t.setAttribute("autocomplete","username"),t.setAttribute("name","username"),t.setAttribute("type","email"),t.setAttribute("readonly","true"),t.setAttribute("tabindex","-1"),t.setAttribute("aria-hidden","true"),t.setAttribute(r.DESCOPE_ATTRIBUTE_EXCLUDE_FIELD,"true"),t.setAttribute(a,"true"),t.setAttribute("value",e),t.value=e,Object.assign(t.style,{position:"absolute",opacity:"0",pointerEvents:"none",height:"0",border:"0"}),t})(l))):s.debug("Username anchor: no user identifier available"):s.debug("Username anchor: no password component on screen")},u=t.createSingletonMixin((u=>{var c,v,h,g,p;const m=t.compose(i.loggerMixin)(u);return p=class extends m{constructor(){super(...arguments),c.add(this),v.set(this,void 0)}updateScreenUser(t){var i,r,s;e.__classPrivateFieldSet(this,v,{email:null==t?void 0:t.email,loginIds:(null===(i=null==t?void 0:t.loginIds)||void 0===i?void 0:i.length)?t.loginIds:[l(e.__classPrivateFieldGet(this,c,"a",g))||(null===(s=null===(r=e.__classPrivateFieldGet(this,c,"a",h).sdk)||void 0===r?void 0:r.getLastUserLoginId)||void 0===s?void 0:s.call(r))].filter(Boolean)},"f")}updateUsernameAnchor(){document.querySelectorAll(`[${a}="true"]`).forEach((e=>e.remove())),d(this,e.__classPrivateFieldGet(this,c,"a",h).contentRootElement,e.__classPrivateFieldGet(this,v,"f"),this.logger)}captureLastSubmittedLoginId(t={},i){const o=s.getFirstNonEmptyValue(t,n);o&&((e,t)=>{var i;if(e&&t)try{null===(i=window.sessionStorage)||void 0===i||i.setItem(r.DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY,JSON.stringify({executionId:t,loginId:e}))}catch(e){}})(o,i||e.__classPrivateFieldGet(this,c,"a",g))}storeCredentials(t={}){var i,r,a,l,d,u;const c=s.getFirstNonEmptyValue(t,n)||(null===(i=e.__classPrivateFieldGet(this,v,"f"))||void 0===i?void 0:i.email)||(null===(a=null===(r=e.__classPrivateFieldGet(this,v,"f"))||void 0===r?void 0:r.loginIds)||void 0===a?void 0:a[0]),h=s.getFirstNonEmptyValue(t,o);if(c&&h)try{if(!globalThis.PasswordCredential)return;const e=new globalThis.PasswordCredential({id:c,password:h});null===(u=null===(d=null===(l=null===navigator||void 0===navigator?void 0:navigator.credentials)||void 0===l?void 0:l.store)||void 0===d?void 0:d.call(l,e))||void 0===u||u.catch((e=>{this.logger.error("Could not store credentials",null==e?void 0:e.message)}))}catch(e){this.logger.error("Could not store credentials",e.message)}}},v=new WeakMap,c=new WeakSet,h=function(){return this},g=function(){var t,i;return(null===(i=null===(t=e.__classPrivateFieldGet(this,c,"a",h).flowState)||void 0===t?void 0:t.current)||void 0===i?void 0:i.executionId)||""},p}));exports.passwordManagerMixin=u;
|
|
2
2
|
//# sourceMappingURL=passwordManagerMixin.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"passwordManagerMixin.js","sources":["../../../src/lib/mixins/passwordManagerMixin.ts"],"sourcesContent":["/* eslint-disable import/prefer-default-export */\nimport { compose, createSingletonMixin } from '@descope/sdk-helpers';\nimport { loggerMixin } from '@descope/sdk-mixins';\nimport {\n DESCOPE_ATTRIBUTE_EXCLUDE_FIELD,\n DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY,\n} from '../constants';\nimport { getFirstNonEmptyValue } from '../helpers';\nimport type { ScreenStateUser } from '../types';\n\nconst LOGIN_ID_FIELDS = ['externalId', 'email', 'phone'];\nconst PASSWORD_FIELDS = ['newPassword', 'password'];\n\nconst USERNAME_ANCHOR_ATTRIBUTE = 'data-username-anchor';\n\n// What the mixin needs from its host. Defined as an interface (not imported)\n// to avoid a circular dependency on DescopeWc. Exported so declaration emit\n// can name it from BaseDescopeWc's composed base class.\nexport interface PasswordManagerHost {\n contentRootElement?: HTMLElement;\n flowState?: { current?: { executionId?: string } };\n sdk?: { getLastUserLoginId?: () => string };\n}\n\n// the last identifier the user submitted on a previous screen in this flow\n// (e.g. the email entered before a magic link was sent), used when neither\n// the flow state nor a previous authentication provides one.\n// kept in sessionStorage (tab scoped, cleared when the tab closes) so it\n// survives page reloads during the flow, and scoped to the flow execution so\n// a stale identifier is never carried into another flow (or another user)\n// running in the same tab\nconst getLastSubmittedLoginId = (executionId: string): string => {\n // a missing execution id must never match anything, otherwise two flows\n // without one would share the stored identifier\n if (!executionId) {\n return '';\n }\n try {\n const raw = window.sessionStorage?.getItem(\n DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY,\n );\n if (!raw) {\n return '';\n }\n const stored = JSON.parse(raw);\n return stored.executionId === executionId ? stored.loginId || '' : '';\n } catch (e) {\n return '';\n }\n};\n\nconst setLastSubmittedLoginId = (loginId: string, executionId: string) => {\n if (!loginId || !executionId) {\n return;\n }\n try {\n window.sessionStorage?.setItem(\n DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY,\n JSON.stringify({ executionId, loginId }),\n );\n } catch (e) {\n // sessionStorage unavailable, losing reload persistence is acceptable\n }\n};\n\nconst clearUsernameAnchorIfExists = () => {\n document\n .querySelectorAll(`[${USERNAME_ANCHOR_ATTRIBUTE}=\"true\"]`)\n .forEach((ele) => ele.remove());\n};\n\nconst findPasswordComponent = (contentRootEle: Element) =>\n contentRootEle.querySelector('descope-new-password') ||\n contentRootEle.querySelector('descope-password');\n\n// an identifier is already on screen when there is an autocomplete=\"username\"\n// input, or a component collecting one of the login id fields (e.g.\n// descope-email-field renders its input inside a closed shadow root, so only\n// its name attribute is visible from here)\nconst hasLoginIdField = (roots: Element[]) => {\n const selector = [\n 'input[autocomplete=\"username\"]',\n ...LOGIN_ID_FIELDS.map((field) => `[name=\"${field}\"]`),\n ].join(', ');\n return roots.some((root) => root.querySelector(selector));\n};\n\nconst createUsernameAnchor = (loginId: string) => {\n const input = document.createElement('input');\n input.setAttribute('autocomplete', 'username');\n input.setAttribute('name', 'username');\n input.setAttribute('type', 'email');\n input.setAttribute('readonly', 'true');\n input.setAttribute('tabindex', '-1');\n input.setAttribute('aria-hidden', 'true');\n // never collect the anchor's value into the submitted form data\n input.setAttribute(DESCOPE_ATTRIBUTE_EXCLUDE_FIELD, 'true');\n // cleaned up by clearUsernameAnchorIfExists between screens\n input.setAttribute(USERNAME_ANCHOR_ATTRIBUTE, 'true');\n // some password managers read the markup value rather than the property\n input.setAttribute('value', loginId);\n input.value = loginId;\n // real input hidden via CSSOM: managers ignore type=\"hidden\", and strict\n // CSP style-src blocks style attributes\n Object.assign(input.style, {\n position: 'absolute',\n opacity: '0',\n pointerEvents: 'none',\n height: '0',\n border: '0',\n });\n return input;\n};\n\n// Anchors a hidden autocomplete=\"username\" input on password screens that\n// have no identifier input, so password managers can associate the credential\n// with a user (descope/etc#16712). Appended to the host light DOM — password\n// manager save heuristics (verified on WebKit) do not scan shadow trees\nconst injectUsernameAnchorIfNeeded = (\n hostEle: HTMLElement,\n contentRootEle: Element,\n user: ScreenStateUser | undefined,\n logger: { debug: (...args: string[]) => void },\n) => {\n const loginId = user?.email || user?.loginIds?.[0];\n\n if (!findPasswordComponent(contentRootEle)) {\n logger.debug('Username anchor: no password component on screen');\n return;\n }\n if (!loginId) {\n logger.debug('Username anchor: no user identifier available');\n return;\n }\n if (hasLoginIdField([hostEle, contentRootEle])) {\n logger.debug('Username anchor: screen already has an identifier field');\n return;\n }\n\n logger.debug('Username anchor: injecting hidden username input');\n hostEle.appendChild(createUsernameAnchor(loginId));\n};\n\n/**\n * Password manager integrations: keeps track of the current screen's user\n * identifier, anchors a hidden username input on password screens that have\n * no identifier input, and stores submitted credentials via the Credential\n * Management API.\n */\nexport const passwordManagerMixin = createSingletonMixin(\n <T extends CustomElementConstructor>(superclass: T) => {\n const BaseClass = compose(loggerMixin)(superclass);\n\n return class PasswordManagerMixinClass extends BaseClass {\n // the authenticated user of the current screen (if any), used as a\n // fallback identifier for password manager integrations on screens that\n // have no identifier input (e.g. step-up password change)\n #screenUser?: ScreenStateUser;\n\n get #host() {\n return this as unknown as PasswordManagerHost;\n }\n\n get #executionId() {\n return this.#host.flowState?.current?.executionId || '';\n }\n\n // called on every screen render. flow state does not always carry the\n // user (e.g. after magic link auth), so fall back to the login id\n // submitted earlier in this flow, then to the last authenticated user\n updateScreenUser(stateUser?: ScreenStateUser) {\n this.#screenUser = {\n email: stateUser?.email,\n loginIds: stateUser?.loginIds?.length\n ? stateUser.loginIds\n : [\n getLastSubmittedLoginId(this.#executionId) ||\n this.#host.sdk?.getLastUserLoginId?.(),\n ].filter(Boolean),\n };\n }\n\n updateUsernameAnchor() {\n // clear the previous screen's anchor, so each screen gets an anchor\n // only if it needs one\n clearUsernameAnchorIfExists();\n\n injectUsernameAnchorIfNeeded(\n this,\n this.#host.contentRootElement,\n this.#screenUser,\n this.logger,\n );\n }\n\n // called after a successful next(): on flows that render their first\n // screen before the flow starts, the execution id only exists on the\n // response, so prefer it over the current flow state\n captureLastSubmittedLoginId(formData = {}, responseExecutionId?: string) {\n const loginId = getFirstNonEmptyValue(formData, LOGIN_ID_FIELDS);\n if (loginId) {\n setLastSubmittedLoginId(\n loginId,\n responseExecutionId || this.#executionId,\n );\n }\n }\n\n // handle storing passwords in password managers\n storeCredentials(formData = {}) {\n const id =\n getFirstNonEmptyValue(formData, LOGIN_ID_FIELDS) ||\n this.#screenUser?.email ||\n this.#screenUser?.loginIds?.[0];\n const password = getFirstNonEmptyValue(formData, PASSWORD_FIELDS);\n\n // PasswordCredential not supported in Firefox\n if (id && password) {\n try {\n if (!globalThis.PasswordCredential) {\n return;\n }\n const cred = new globalThis.PasswordCredential({ id, password });\n\n navigator?.credentials?.store?.(cred);\n } catch (e) {\n this.logger.error('Could not store credentials', e.message);\n }\n }\n }\n };\n },\n);\n"],"names":["LOGIN_ID_FIELDS","PASSWORD_FIELDS","USERNAME_ANCHOR_ATTRIBUTE","getLastSubmittedLoginId","executionId","raw","_a","window","sessionStorage","getItem","DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY","stored","JSON","parse","loginId","e","injectUsernameAnchorIfNeeded","hostEle","contentRootEle","user","logger","email","loginIds","querySelector","findPasswordComponent","roots","selector","map","field","join","some","root","hasLoginIdField","debug","appendChild","input","document","createElement","setAttribute","DESCOPE_ATTRIBUTE_EXCLUDE_FIELD","value","Object","assign","style","position","opacity","pointerEvents","height","border","createUsernameAnchor","passwordManagerMixin","createSingletonMixin","superclass","BaseClass","compose","loggerMixin","constructor","_PasswordManagerMixinClass_screenUser","set","this","updateScreenUser","stateUser","__classPrivateFieldSet","_b","length","__classPrivateFieldGet","_PasswordManagerMixinClass_instances","_PasswordManagerMixinClass_executionId_get","_d","_c","_PasswordManagerMixinClass_host_get","sdk","getLastUserLoginId","call","filter","Boolean","updateUsernameAnchor","querySelectorAll","forEach","ele","remove","contentRootElement","captureLastSubmittedLoginId","formData","responseExecutionId","getFirstNonEmptyValue","setItem","stringify","setLastSubmittedLoginId","storeCredentials","id","password","globalThis","PasswordCredential","cred","_f","_e","navigator","credentials","store","error","message","flowState","current"],"mappings":"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"}
|
|
1
|
+
{"version":3,"file":"passwordManagerMixin.js","sources":["../../../src/lib/mixins/passwordManagerMixin.ts"],"sourcesContent":["/* eslint-disable import/prefer-default-export */\nimport { compose, createSingletonMixin } from '@descope/sdk-helpers';\nimport { loggerMixin } from '@descope/sdk-mixins';\nimport {\n DESCOPE_ATTRIBUTE_EXCLUDE_FIELD,\n DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY,\n} from '../constants';\nimport { getFirstNonEmptyValue } from '../helpers';\nimport type { ScreenStateUser } from '../types';\n\nconst LOGIN_ID_FIELDS = ['externalId', 'email', 'phone'];\nconst PASSWORD_FIELDS = ['newPassword', 'password'];\n\nconst USERNAME_ANCHOR_ATTRIBUTE = 'data-username-anchor';\n\n// What the mixin needs from its host. Defined as an interface (not imported)\n// to avoid a circular dependency on DescopeWc. Exported so declaration emit\n// can name it from BaseDescopeWc's composed base class.\nexport interface PasswordManagerHost {\n contentRootElement?: HTMLElement;\n flowState?: { current?: { executionId?: string } };\n sdk?: { getLastUserLoginId?: () => string };\n}\n\n// the last identifier the user submitted on a previous screen in this flow\n// (e.g. the email entered before a magic link was sent), used when neither\n// the flow state nor a previous authentication provides one.\n// kept in sessionStorage (tab scoped, cleared when the tab closes) so it\n// survives page reloads during the flow, and scoped to the flow execution so\n// a stale identifier is never carried into another flow (or another user)\n// running in the same tab\nconst getLastSubmittedLoginId = (executionId: string): string => {\n // a missing execution id must never match anything, otherwise two flows\n // without one would share the stored identifier\n if (!executionId) {\n return '';\n }\n try {\n const raw = window.sessionStorage?.getItem(\n DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY,\n );\n if (!raw) {\n return '';\n }\n const stored = JSON.parse(raw);\n return stored.executionId === executionId ? stored.loginId || '' : '';\n } catch (e) {\n return '';\n }\n};\n\nconst setLastSubmittedLoginId = (loginId: string, executionId: string) => {\n if (!loginId || !executionId) {\n return;\n }\n try {\n window.sessionStorage?.setItem(\n DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY,\n JSON.stringify({ executionId, loginId }),\n );\n } catch (e) {\n // sessionStorage unavailable, losing reload persistence is acceptable\n }\n};\n\nconst clearUsernameAnchorIfExists = () => {\n document\n .querySelectorAll(`[${USERNAME_ANCHOR_ATTRIBUTE}=\"true\"]`)\n .forEach((ele) => ele.remove());\n};\n\nconst findPasswordComponent = (contentRootEle: Element) =>\n contentRootEle.querySelector('descope-new-password') ||\n contentRootEle.querySelector('descope-password');\n\n// an identifier is already on screen when there is an autocomplete=\"username\"\n// input, or a component collecting one of the login id fields (e.g.\n// descope-email-field renders its input inside a closed shadow root, so only\n// its name attribute is visible from here)\nconst hasLoginIdField = (roots: Element[]) => {\n const selector = [\n 'input[autocomplete=\"username\"]',\n ...LOGIN_ID_FIELDS.map((field) => `[name=\"${field}\"]`),\n ].join(', ');\n return roots.some((root) => root.querySelector(selector));\n};\n\nconst createUsernameAnchor = (loginId: string) => {\n const input = document.createElement('input');\n input.setAttribute('autocomplete', 'username');\n input.setAttribute('name', 'username');\n input.setAttribute('type', 'email');\n input.setAttribute('readonly', 'true');\n input.setAttribute('tabindex', '-1');\n input.setAttribute('aria-hidden', 'true');\n // never collect the anchor's value into the submitted form data\n input.setAttribute(DESCOPE_ATTRIBUTE_EXCLUDE_FIELD, 'true');\n // cleaned up by clearUsernameAnchorIfExists between screens\n input.setAttribute(USERNAME_ANCHOR_ATTRIBUTE, 'true');\n // some password managers read the markup value rather than the property\n input.setAttribute('value', loginId);\n input.value = loginId;\n // real input hidden via CSSOM: managers ignore type=\"hidden\", and strict\n // CSP style-src blocks style attributes\n Object.assign(input.style, {\n position: 'absolute',\n opacity: '0',\n pointerEvents: 'none',\n height: '0',\n border: '0',\n });\n return input;\n};\n\n// Anchors a hidden autocomplete=\"username\" input on password screens that\n// have no identifier input, so password managers can associate the credential\n// with a user (descope/etc#16712). Appended to the host light DOM — password\n// manager save heuristics (verified on WebKit) do not scan shadow trees\nconst injectUsernameAnchorIfNeeded = (\n hostEle: HTMLElement,\n contentRootEle: Element,\n user: ScreenStateUser | undefined,\n logger: { debug: (...args: string[]) => void },\n) => {\n const loginId = user?.email || user?.loginIds?.[0];\n\n if (!findPasswordComponent(contentRootEle)) {\n logger.debug('Username anchor: no password component on screen');\n return;\n }\n if (!loginId) {\n logger.debug('Username anchor: no user identifier available');\n return;\n }\n if (hasLoginIdField([hostEle, contentRootEle])) {\n logger.debug('Username anchor: screen already has an identifier field');\n return;\n }\n\n logger.debug('Username anchor: injecting hidden username input');\n hostEle.appendChild(createUsernameAnchor(loginId));\n};\n\n/**\n * Password manager integrations: keeps track of the current screen's user\n * identifier, anchors a hidden username input on password screens that have\n * no identifier input, and stores submitted credentials via the Credential\n * Management API.\n */\nexport const passwordManagerMixin = createSingletonMixin(\n <T extends CustomElementConstructor>(superclass: T) => {\n const BaseClass = compose(loggerMixin)(superclass);\n\n return class PasswordManagerMixinClass extends BaseClass {\n // the authenticated user of the current screen (if any), used as a\n // fallback identifier for password manager integrations on screens that\n // have no identifier input (e.g. step-up password change)\n #screenUser?: ScreenStateUser;\n\n get #host() {\n return this as unknown as PasswordManagerHost;\n }\n\n get #executionId() {\n return this.#host.flowState?.current?.executionId || '';\n }\n\n // called on every screen render. flow state does not always carry the\n // user (e.g. after magic link auth), so fall back to the login id\n // submitted earlier in this flow, then to the last authenticated user\n updateScreenUser(stateUser?: ScreenStateUser) {\n this.#screenUser = {\n email: stateUser?.email,\n loginIds: stateUser?.loginIds?.length\n ? stateUser.loginIds\n : [\n getLastSubmittedLoginId(this.#executionId) ||\n this.#host.sdk?.getLastUserLoginId?.(),\n ].filter(Boolean),\n };\n }\n\n updateUsernameAnchor() {\n // clear the previous screen's anchor, so each screen gets an anchor\n // only if it needs one\n clearUsernameAnchorIfExists();\n\n injectUsernameAnchorIfNeeded(\n this,\n this.#host.contentRootElement,\n this.#screenUser,\n this.logger,\n );\n }\n\n // called after a successful next(): on flows that render their first\n // screen before the flow starts, the execution id only exists on the\n // response, so prefer it over the current flow state\n captureLastSubmittedLoginId(formData = {}, responseExecutionId?: string) {\n const loginId = getFirstNonEmptyValue(formData, LOGIN_ID_FIELDS);\n if (loginId) {\n setLastSubmittedLoginId(\n loginId,\n responseExecutionId || this.#executionId,\n );\n }\n }\n\n // handle storing passwords in password managers\n storeCredentials(formData = {}) {\n const id =\n getFirstNonEmptyValue(formData, LOGIN_ID_FIELDS) ||\n this.#screenUser?.email ||\n this.#screenUser?.loginIds?.[0];\n const password = getFirstNonEmptyValue(formData, PASSWORD_FIELDS);\n\n // PasswordCredential not supported in Firefox\n if (id && password) {\n try {\n if (!globalThis.PasswordCredential) {\n return;\n }\n const cred = new globalThis.PasswordCredential({ id, password });\n\n navigator?.credentials?.store?.(cred)?.catch((e) => {\n this.logger.error('Could not store credentials', e?.message);\n });\n } catch (e) {\n this.logger.error('Could not store credentials', e.message);\n }\n }\n }\n };\n },\n);\n"],"names":["LOGIN_ID_FIELDS","PASSWORD_FIELDS","USERNAME_ANCHOR_ATTRIBUTE","getLastSubmittedLoginId","executionId","raw","_a","window","sessionStorage","getItem","DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY","stored","JSON","parse","loginId","e","injectUsernameAnchorIfNeeded","hostEle","contentRootEle","user","logger","email","loginIds","querySelector","findPasswordComponent","roots","selector","map","field","join","some","root","hasLoginIdField","debug","appendChild","input","document","createElement","setAttribute","DESCOPE_ATTRIBUTE_EXCLUDE_FIELD","value","Object","assign","style","position","opacity","pointerEvents","height","border","createUsernameAnchor","passwordManagerMixin","createSingletonMixin","superclass","BaseClass","compose","loggerMixin","constructor","_PasswordManagerMixinClass_screenUser","set","this","updateScreenUser","stateUser","__classPrivateFieldSet","_b","length","__classPrivateFieldGet","_PasswordManagerMixinClass_instances","_PasswordManagerMixinClass_executionId_get","_d","_c","_PasswordManagerMixinClass_host_get","sdk","getLastUserLoginId","call","filter","Boolean","updateUsernameAnchor","querySelectorAll","forEach","ele","remove","contentRootElement","captureLastSubmittedLoginId","formData","responseExecutionId","getFirstNonEmptyValue","setItem","stringify","setLastSubmittedLoginId","storeCredentials","id","password","globalThis","PasswordCredential","cred","_g","_f","navigator","credentials","_e","store","catch","error","message","flowState","current"],"mappings":"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"}
|
|
@@ -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 a}from"@descope/web-js-sdk";import{ELEMENTS_TO_IGNORE_ENTER_KEY_ON as u}from"../constants/index.js";import{handleUrlParams as l,clearRunIdsFromUrl as d,camelCase as c,getRunIdsFromUrl as h,getContentUrl as f,fetchContent as g,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{componentConditionsMixin as C}from"../mixins/componentConditionsMixin.js";import{duplicateFlowWarningMixin as y}from"../mixins/duplicateFlowWarningMixin.js";import{passwordManagerMixin as A}from"../mixins/passwordManagerMixin.js";import{CONFIG_FILENAME as x,PREV_VER_ASSETS_FOLDER as j}from"../constants/content.js";import{FETCH_EXCEPTION_ERROR_CODE as I}from"../constants/general.js";var E,M,L,S,U,O,W,D,P,N,F,K,R,T,B,H,J,V,q,$,z,Q;const G=r(s,o,k,C,y,A,n)(HTMLElement);class X extends G{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(),E.add(this),L.set(this,!1),S.set(this,void 0),this.flowStatus="initial",this.loggerWrapper={error:(e,i="")=>{this.logger.error(e,i,new Error),t(this,E,"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)}},U.set(this,new m),O.set(this,new m),W.set(this,{}),this.getComponentsContext=()=>t(this,W,"f"),this.nextRequestStatus=new m({isLoading:!1}),D.set(this,void 0),P.set(this,{popstate:t(this,E,"m",T).bind(this),componentsContext:t(this,E,"m",q).bind(this)}),N.set(this,void 0),this.getConfig=()=>e(this,void 0,void 0,(function*(){return(yield this.config)||{isMissingConfig:!0}})),i(this,N,r,"f"),t(this,E,"m",K).call(this)}get flowId(){return this.getAttribute("flow-id")}get client(){try{return JSON.parse(this.getAttribute("client"))||{}}catch(t){return{}}}get redirectUrl(){return this.getAttribute("redirect-url")||void 0}get debug(){return"true"===this.getAttribute("debug")}get locale(){return this.getAttribute("locale")||void 0}get autoFocus(){var t;const e=null!==(t=this.getAttribute("auto-focus"))&&void 0!==t?t:"true";return"skipFirstScreen"===e?e:"true"===e}get validateOnBlur(){return"true"===this.getAttribute("validate-on-blur")}get storeLastAuthenticatedUser(){var t;return"true"===(null!==(t=this.getAttribute("store-last-authenticated-user"))&&void 0!==t?t:"true")}get refreshCookieName(){return this.getAttribute("refresh-cookie-name")||""}get keepLastAuthenticatedUserAfterLogout(){return"true"===this.getAttribute("keep-last-authenticated-user-after-logout")}get storagePrefix(){return this.getAttribute("storage-prefix")||""}get 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,S,"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,S,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=u.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 a=Array.from(n).filter((t=>"true"===t.getAttribute("auto-submit")));if(1===a.length)return void a[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,O,"f").subscribe(t(this,E,"m",z).bind(this)),t(this,O,"f").update({isDebug:this.debug}),t(this,E,"m",R).call(this),yield t(this,E,"m",J).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:a,code:u,isPopup:d,exchangeError:c,redirectAuthCallbackUrl:h,redirectAuthBackupCallbackUri:f,redirectAuthCodeChallenge:g,redirectAuthInitiator:p,ssoQueryParams:m}=l(this.flowId,this.loggerWrapper);window.addEventListener("popstate",t(this,P,"f").popstate),window.addEventListener("components-context",t(this,P,"f").componentsContext),t(this,U,"f").subscribe(t(this,E,"m",H).bind(this)),t(this,U,"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:a,code:u,isPopup:d,exchangeError:c,redirectAuthCallbackUrl:h,redirectAuthBackupCallbackUri:f,redirectAuthCodeChallenge:g,redirectAuthInitiator:p},m)),i(this,L,!0,"f")}))}disconnectedCallback(){var e;t(this,U,"f").unsubscribeAll(),t(this,O,"f").unsubscribeAll(),t(this,E,"m",$).call(this),window.removeEventListener("popstate",t(this,P,"f").popstate),window.removeEventListener("components-context",t(this,P,"f").componentsContext),null===(e=super.disconnectedCallback)||void 0===e||e.call(this)}attributeChangedCallback(e,i,r){var o;if(null===(o=super.attributeChangedCallback)||void 0===o||o.call(this,e,i,r),this.shadowRoot.isConnected&&t(this,L,"f")&&i!==r&&M.observedAttributes.includes(e)){t(this,E,"m",R).call(this);const o=null===i;t(this,U,"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,O,"f").update({isDebug:this.debug})}}}M=X,L=new WeakMap,S=new WeakMap,U=new WeakMap,O=new WeakMap,W=new WeakMap,D=new WeakMap,P=new WeakMap,N=new WeakMap,E=new WeakSet,F=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 ")},K=function(){t(this,E,"m",F).call(this),this.slotElement=document.createElement("slot"),this.slotElement.classList.add("hidden"),this.rootElement.appendChild(this.slotElement)},R=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","theme-override"];M.observedAttributes.forEach((e=>{if(!t.includes(e)&&!this[c(e)])throw Error(`${e} cannot be empty`)}))},T=function(){const{stepId:e,executionId:i}=h(this.flowId);t(this,U,"f").update({stepId:e,executionId:i})},B=function(i,r){a&&"function"==typeof a||this.logger.error("SDK was not loaded properly",a,JSON.stringify(a));const o=Object.assign(Object.assign({persistTokens:!0,preview:this.preview,storagePrefix:this.storagePrefix,storeLastAuthenticatedUser:this.storeLastAuthenticatedUser,keepLastAuthenticatedUserAfterLogout:this.keepLastAuthenticatedUserAfterLogout,refreshCookieName:this.refreshCookieName},M.sdkConfigOverrides),{projectId:i,baseUrl:r});t(this,S,"f")&&(o.customStorage=t(this,S,"f")),this.sdk=a(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:I,errorDescription:e.toString()}}}}))}))},H=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,E,"m",B).call(this,e,r)}t(this,N,"f").call(this,i)}))},J=function(){return e(this,void 0,void 0,(function*(){const e=yield this.getConfig();return"isMissingConfig"in e&&e.isMissingConfig&&(yield t(this,E,"m",V).call(this))}))},V=function(){return e(this,void 0,void 0,(function*(){const t=f({projectId:this.projectId,filename:x,assetsFolder:j,baseUrl:this.baseStaticUrl});try{return yield g(t,"json"),!0}catch(t){return!1}}))},q=function(e){i(this,W,Object.assign(Object.assign({},t(this,W,"f")),e.detail),"f")},$=function(){var e;null===(e=t(this,D,"f"))||void 0===e||e.remove(),i(this,D,null,"f")},z=function(r){return e(this,arguments,void 0,(function*({isDebug:e}){e?(i(this,D,document.createElement("descope-debugger"),"f"),Object.assign(t(this,D,"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,D,"f"))):t(this,E,"m",$).call(this)}))},Q=function(e,i){var r;e&&this.debug&&(null===(r=t(this,D,"f"))||void 0===r||r.updateData({title:e,description:i}))},X.sdkConfigOverrides={baseHeaders:{"x-descope-sdk-name":"web-component","x-descope-sdk-version":"4.0.1"}};export{X 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 a}from"@descope/web-js-sdk";import{ELEMENTS_TO_IGNORE_ENTER_KEY_ON as u}from"../constants/index.js";import{handleUrlParams as l,clearRunIdsFromUrl as d,camelCase as c,getRunIdsFromUrl as h,getContentUrl as f,fetchContent as g,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{componentConditionsMixin as C}from"../mixins/componentConditionsMixin.js";import{duplicateFlowWarningMixin as y}from"../mixins/duplicateFlowWarningMixin.js";import{passwordManagerMixin as A}from"../mixins/passwordManagerMixin.js";import{CONFIG_FILENAME as x,PREV_VER_ASSETS_FOLDER as j}from"../constants/content.js";import{FETCH_EXCEPTION_ERROR_CODE as I}from"../constants/general.js";var E,M,L,S,U,O,W,D,P,N,F,K,R,T,B,H,J,V,q,$,z,Q;const G=r(s,o,k,C,y,A,n)(HTMLElement);class X extends G{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(),E.add(this),L.set(this,!1),S.set(this,void 0),this.flowStatus="initial",this.loggerWrapper={error:(e,i="")=>{this.logger.error(e,i,new Error),t(this,E,"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)}},U.set(this,new m),O.set(this,new m),W.set(this,{}),this.getComponentsContext=()=>t(this,W,"f"),this.nextRequestStatus=new m({isLoading:!1}),D.set(this,void 0),P.set(this,{popstate:t(this,E,"m",T).bind(this),componentsContext:t(this,E,"m",q).bind(this)}),N.set(this,void 0),this.getConfig=()=>e(this,void 0,void 0,(function*(){return(yield this.config)||{isMissingConfig:!0}})),i(this,N,r,"f"),t(this,E,"m",K).call(this)}get flowId(){return this.getAttribute("flow-id")}get client(){try{return JSON.parse(this.getAttribute("client"))||{}}catch(t){return{}}}get redirectUrl(){return this.getAttribute("redirect-url")||void 0}get debug(){return"true"===this.getAttribute("debug")}get locale(){return this.getAttribute("locale")||void 0}get autoFocus(){var t;const e=null!==(t=this.getAttribute("auto-focus"))&&void 0!==t?t:"true";return"skipFirstScreen"===e?e:"true"===e}get validateOnBlur(){return"true"===this.getAttribute("validate-on-blur")}get storeLastAuthenticatedUser(){var t;return"true"===(null!==(t=this.getAttribute("store-last-authenticated-user"))&&void 0!==t?t:"true")}get refreshCookieName(){return this.getAttribute("refresh-cookie-name")||""}get keepLastAuthenticatedUserAfterLogout(){return"true"===this.getAttribute("keep-last-authenticated-user-after-logout")}get storagePrefix(){return this.getAttribute("storage-prefix")||""}get 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,S,"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,S,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=u.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 a=Array.from(n).filter((t=>"true"===t.getAttribute("auto-submit")));if(1===a.length)return void a[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,O,"f").subscribe(t(this,E,"m",z).bind(this)),t(this,O,"f").update({isDebug:this.debug}),t(this,E,"m",R).call(this),yield t(this,E,"m",J).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:a,code:u,isPopup:d,exchangeError:c,redirectAuthCallbackUrl:h,redirectAuthBackupCallbackUri:f,redirectAuthCodeChallenge:g,redirectAuthInitiator:p,ssoQueryParams:m}=l(this.flowId,this.loggerWrapper);window.addEventListener("popstate",t(this,P,"f").popstate),window.addEventListener("components-context",t(this,P,"f").componentsContext),t(this,U,"f").subscribe(t(this,E,"m",H).bind(this)),t(this,U,"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:a,code:u,isPopup:d,exchangeError:c,redirectAuthCallbackUrl:h,redirectAuthBackupCallbackUri:f,redirectAuthCodeChallenge:g,redirectAuthInitiator:p},m)),i(this,L,!0,"f")}))}disconnectedCallback(){var e;t(this,U,"f").unsubscribeAll(),t(this,O,"f").unsubscribeAll(),t(this,E,"m",$).call(this),window.removeEventListener("popstate",t(this,P,"f").popstate),window.removeEventListener("components-context",t(this,P,"f").componentsContext),null===(e=super.disconnectedCallback)||void 0===e||e.call(this)}attributeChangedCallback(e,i,r){var o;if(null===(o=super.attributeChangedCallback)||void 0===o||o.call(this,e,i,r),this.shadowRoot.isConnected&&t(this,L,"f")&&i!==r&&M.observedAttributes.includes(e)){t(this,E,"m",R).call(this);const o=null===i;t(this,U,"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,O,"f").update({isDebug:this.debug})}}}M=X,L=new WeakMap,S=new WeakMap,U=new WeakMap,O=new WeakMap,W=new WeakMap,D=new WeakMap,P=new WeakMap,N=new WeakMap,E=new WeakSet,F=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 ")},K=function(){t(this,E,"m",F).call(this),this.slotElement=document.createElement("slot"),this.slotElement.classList.add("hidden"),this.rootElement.appendChild(this.slotElement)},R=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","theme-override"];M.observedAttributes.forEach((e=>{if(!t.includes(e)&&!this[c(e)])throw Error(`${e} cannot be empty`)}))},T=function(){const{stepId:e,executionId:i}=h(this.flowId);t(this,U,"f").update({stepId:e,executionId:i})},B=function(i,r){a&&"function"==typeof a||this.logger.error("SDK was not loaded properly",a,JSON.stringify(a));const o=Object.assign(Object.assign({persistTokens:!0,preview:this.preview,storagePrefix:this.storagePrefix,storeLastAuthenticatedUser:this.storeLastAuthenticatedUser,keepLastAuthenticatedUserAfterLogout:this.keepLastAuthenticatedUserAfterLogout,refreshCookieName:this.refreshCookieName},M.sdkConfigOverrides),{projectId:i,baseUrl:r});t(this,S,"f")&&(o.customStorage=t(this,S,"f")),this.sdk=a(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:I,errorDescription:e.toString()}}}}))}))},H=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,E,"m",B).call(this,e,r)}t(this,N,"f").call(this,i)}))},J=function(){return e(this,void 0,void 0,(function*(){const e=yield this.getConfig();return"isMissingConfig"in e&&e.isMissingConfig&&(yield t(this,E,"m",V).call(this))}))},V=function(){return e(this,void 0,void 0,(function*(){const t=f({projectId:this.projectId,filename:x,assetsFolder:j,baseUrl:this.baseStaticUrl});try{return yield g(t,"json"),!0}catch(t){return!1}}))},q=function(e){i(this,W,Object.assign(Object.assign({},t(this,W,"f")),e.detail),"f")},$=function(){var e;null===(e=t(this,D,"f"))||void 0===e||e.remove(),i(this,D,null,"f")},z=function(r){return e(this,arguments,void 0,(function*({isDebug:e}){e?(i(this,D,document.createElement("descope-debugger"),"f"),Object.assign(t(this,D,"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,D,"f"))):t(this,E,"m",$).call(this)}))},Q=function(e,i){var r;e&&this.debug&&(null===(r=t(this,D,"f"))||void 0===r||r.updateData({title:e,description:i}))},X.sdkConfigOverrides={baseHeaders:{"x-descope-sdk-name":"web-component","x-descope-sdk-version":"4.1.0"}};export{X 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{getUserLocale as o}from"@descope/sdk-helpers";import{ensureFingerprintIds as r,clearFingerprintData as n}from"@descope/web-js-sdk";import{RESPONSE_ACTIONS as l,CUSTOM_INTERACTIONS as a,URL_CODE_PARAM_NAME as d,URL_ERR_PARAM_NAME as c,URL_TOKEN_PARAM_NAME as p,URL_RUN_IDS_PARAM_NAME as h,SDK_SCRIPTS_LOAD_TIMEOUT as u,DESCOPE_ATTRIBUTE_EXCLUDE_FIELD as g,ELEMENT_TYPE_ATTRIBUTE as v,DESCOPE_ATTRIBUTE_OPT_IN_LAST_USED as m,DESCOPE_LAST_AUTH_BADGE_COMPONENT as f,DESCOPE_ATTRIBUTE_EXCLUDE_NEXT_BUTTON as b}from"../constants/index.js";import{timeoutPromise as w,withMemCache as S,leadingDebounce as y,showFirstScreenOnExecutionInit as I,injectSamlIdpForm as R,injectWsFedIdpForm as C,openCenteredPopup as W,getAnimationDirection as k,handleAutoFocus as O,transformStepStateForCustomScreen as x,getElementDescopeAttributes as E,getScriptResultPath as A,submitForm as j,transformScreenInputs as T,handleReportValidityOnBlur as L,clearPreviousExternalInputs as U}from"../helpers/helpers.js";import P from"../helpers/state.js";import{disableWebauthnButtons as F,updateTemplateFromScreenState as $,setComponentsAutoDetectByGeo as N,setComponentsAutoDetectByLocale as M,setTOTPVariable as q,setNOTPVariable as V,setCssVars as D,updateScreenFromScreenState as B,replaceElementMessage as K}from"../helpers/templates.js";import{isConditionalLoginSupported as H}from"../helpers/webauthn.js";import{getABTestingKey as _}from"../helpers/abTestingKey.js";import{calculateConditions as G,calculateCondition as J}from"../helpers/conditions.js";import{setLastAuth as z,getInFlightLastUsedPerScreen as Q,clearInFlightLastAuth as X,getLastAuth as Y,updateLastUsedPerScreen as Z}from"../helpers/lastAuth.js";import ee from"./BaseDescopeWc.js";import{FETCH_EXCEPTION_ERROR_CODE as te,FETCH_ERROR_RESPONSE_ERROR_CODE as ie,FLOW_REQUESTED_IS_IN_OLD_VERSION_ERROR_CODE as se,FLOW_TIMED_OUT_ERROR_CODE as oe,NONCE_VALIDATION_ERROR_CODE as re,POLLING_STATUS_NOT_FOUND_ERROR_CODE as ne}from"../constants/general.js";var le,ae,de,ce,pe,he,ue,ge,ve,me,fe,be,we,Se,ye,Ie,Re,Ce,We,ke,Oe,xe,Ee,Ae,je,Te,Le,Ue,Pe,Fe,$e,Ne,Me,qe,Ve,De,Be,Ke,He;class _e extends ee{static set sdkConfigOverrides(e){ee.sdkConfigOverrides=e}static get sdkConfigOverrides(){return ee.sdkConfigOverrides}constructor(){const s=new P({deferredRedirect:!1,deferredPolling:!1});super(s.update.bind(s)),le.add(this),this.stepState=new P({}),ae.set(this,void 0),de.set(this,null),ce.set(this,null),pe.set(this,{visibilitychange:e(this,le,"m",he).bind(this)}),this.bridgeVersion=2,this.nativeCallbacks={},Se.set(this,!1),this.handleRedirect=e=>{window.location.assign(e)},Ie.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,le,"m",Re).call(this,i):i()})),Ce.set(this,((s,o,r,n,d=!1)=>{const c=[oe,ne,re];if(this.flowState.current.action===l.poll){if(e(this,ke,"f").call(this)&&document.hidden)return this.logger.debug("polling - Deferring polling until in foreground"),void this.flowState.update({deferredPolling:!0});this.logger.debug("polling - Scheduling polling request");const l=Date.now(),p=d?500:2e3;t(this,ae,setTimeout((()=>i(this,void 0,void 0,(function*(){var t,i;this.logger.debug("polling - Calling next");const h=this.sdk.flow.next(s,o,a.polling,r,n,{}),u=document.hidden&&!d&&Date.now()-l>p+500;let g;u&&this.logger.debug("polling - The polling seems to be throttled");try{const e=u?1e3:6e3;g=yield w(e,h)}catch(t){return this.logger.warn(`polling - The ${u?"throttled fetch":"fetch"} call timed out or was aborted`),void e(this,Ce,"f").call(this,s,o,r,n,u)}if((null===(t=null==g?void 0:g.error)||void 0===t?void 0:t.errorCode)===te)return this.logger.debug("polling - Got a generic error due to exception in fetch call"),void e(this,Ce,"f").call(this,s,o,r,n);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,Ce,"f").call(this,s,o,r,n),e(this,Oe,"f").call(this,g)}))),p),"f")}})),We.set(this,(()=>{clearTimeout(e(this,ae,"f")),t(this,ae,null,"f")})),ke.set(this,(()=>!!window.descopeBridge||/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent))),Oe.set(this,(i=>{var s,o,r,n,a,d,c,p,h,u,g,v,m;if(!(null==i?void 0:i.ok)){const t=null===(s=null==i?void 0:i.response)||void 0===s?void 0:s.url,l=`${null===(o=null==i?void 0:i.response)||void 0===o?void 0:o.status} - ${null===(r=null==i?void 0:i.response)||void 0===r?void 0:r.statusText}`;e(this,le,"m",Ke).call(this,"error",(null==i?void 0:i.error)||{errorCode:ie,errorDescription:l,errorMessage:t}),this.loggerWrapper.error((null===(n=null==i?void 0:i.error)||void 0===n?void 0:n.errorDescription)||t,(null===(a=null==i?void 0:i.error)||void 0===a?void 0:a.errorMessage)||l);const c=null===(d=null==i?void 0:i.error)||void 0===d?void 0:d.errorCode;return void(c!==se&&c!==oe&&c!==re||!this.isRestartOnError||e(this,le,"m",we).call(this))}null===(p=null===(c=i.data)||void 0===c?void 0:c.runnerLogs)||void 0===p||p.forEach((e=>{const{level:t,title:i,log:s}=e;t&&this.loggerWrapper[t]?this.loggerWrapper[t](i,s):this.loggerWrapper.info(i,s)}));const f=null===(g=null===(u=null===(h=i.data)||void 0===h?void 0:h.screen)||void 0===u?void 0:u.state)||void 0===g?void 0:g.errorText;(null===(v=i.data)||void 0===v?void 0:v.error)?this.loggerWrapper.error(`[${i.data.error.code}]: ${i.data.error.description}`,`${f?`${f} - `:""}${i.data.error.message}`):f&&this.loggerWrapper.error(f);const{status:b,authInfo:w,lastAuth:S,action:y,openInNewTabUrl:I}=i.data;if(y!==l.poll&&e(this,We,"f").call(this),"completed"===b){this.storeLastAuthenticatedUser&&z(Object.assign(Object.assign({},S),{lastUsedPerScreen:Q()})),X(this.loggerWrapper);const t=Object.assign({},w);return i.data.output&&Object.keys(i.data.output).length>0&&(t.flowOutput=i.data.output),void e(this,le,"m",Ke).call(this,"success",t)}this.storeLastAuthenticatedUser&&z(S,!0),I&&window.open(I,"_blank");const{executionId:R,stepId:C,stepName:W,screen:k,redirect:O,webauthn:x,error:E,samlIdpResponse:A,wsFedIdpResponse:j,nativeResponse:T}=i.data,L=Date.now();y!==l.poll?(this.loggerWrapper.info(`Step "${W||`#${C}`}" is ${b}`,"",{screen:k,status:b,stepId:C,stepName:W,action:y,error:E}),(null===(m=k.state)||void 0===m?void 0:m.clientScripts)&&t(this,ce,this.loadSdkScripts(k.state.clientScripts),"f"),this.flowState.update({stepId:C,stepName:W,executionId:R,action:y,redirectTo:null==O?void 0:O.url,redirectIsPopup:null==O?void 0:O.isPopup,screenId:null==k?void 0:k.id,screenState:null==k?void 0:k.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:L})):this.flowState.update({action:y,reqTimestamp:L})})),xe.set(this,S((()=>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)}}))))),Ue.set(this,null),Ne.set(this,y(((t,s,o)=>i(this,void 0,void 0,(function*(){var i,r;if("true"===t.getAttribute("formnovalidate")||e(this,le,"m",Te).call(this)){const n=null==t?void 0:t.getAttribute("id");e(this,le,"m",Ve).call(this,t,n,o),e(this,le,"m",Pe).call(this,t);const l=yield e(this,le,"m",Le).call(this),a=E(t);this.nextRequestStatus.update({isLoading:!0});const d=Object.assign(Object.assign(Object.assign({},a),l),{origin:(null===(i=this.nativeOptions)||void 0===i?void 0:i.origin)||window.location.origin}),c=yield s(n,d);this.nextRequestStatus.update({isLoading:!1}),this.captureLastSubmittedLoginId(l,null===(r=null==c?void 0:c.data)||void 0===r?void 0:r.executionId),this.storeCredentials(l)}}))))),this.flowState=s}nativeResume(t,i){var s,o,r,n,l,a;const u=JSON.parse(i);if("oauthWeb"===t||"sso"===t){let e,{exchangeCode:t}=u;if(!t){const i=new URL(u.url);t=null===(s=i.searchParams)||void 0===s?void 0:s.get(d),e=(null===(o=i.searchParams)||void 0===o?void 0:o.get(c))||void 0}null===(n=(r=this.nativeCallbacks).complete)||void 0===n||n.call(r,{exchangeCode:t,exchangeError:e,idpInitiated:!0})}else if("magicLink"===t){const t=new URL(u.url),i=t.searchParams.get(p),s=t.searchParams.get(h).split("_").pop();e(this,We,"f").call(this),this.flowState.update({token:i,stepId:s,action:void 0})}else if("beforeScreen"===t){const{screenResolve:e}=this.nativeCallbacks;this.nativeCallbacks.screenResolve=null;const{override:t}=u;t||(this.nativeCallbacks.screenNext=null),null==e||e(t)}else if("resumeScreen"===t){const{interactionId:e,form:t}=u,{screenNext:i}=this.nativeCallbacks;this.nativeCallbacks.screenNext=null,null==i||i(e,t)}else null===(a=(l=this.nativeCallbacks).complete)||void 0===a||a.call(l,u)}loadSdkScriptsModules(){const e=this.shadowRoot.querySelectorAll("div[data-script-id]");return Array.from(e).map((e=>e.moduleRes)).filter((e=>!!e))}loadSdkScripts(e){if(!(null==e?void 0:e.length))return null;const t=(e,t)=>i=>{this.dispatchEvent(new CustomEvent("components-context",{detail:{[A(e.id,e.resultKey)]:i},bubbles:!0,composed:!0})),t(e.id)};this.loggerWrapper.debug(`Preparing to load scripts: ${e.map((e=>e.id)).join(", ")}`);const s=Promise.all(null==e?void 0:e.map((e=>i(this,void 0,void 0,(function*(){var i,s,o;const r=this.shadowRoot.querySelector(`[data-script-id="${e.id}"]`);if(r){this.loggerWrapper.debug("Script already loaded",e.id);const{moduleRes:t}=r;return null===(i=null==t?void 0:t.start)||void 0===i||i.call(t),t}(null===(s=globalThis.descope)||void 0===s?void 0:s[e.id])||(yield this.injectNpmLib("@descope/flow-scripts","1.0.17",`dist/${e.id}.js`));const n=null===(o=globalThis.descope)||void 0===o?void 0:o[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);const i=this.nextRequestStatus.subscribe((()=>{var o;this.loggerWrapper.debug("Stopping script",e.id),(null===(o=s.stop)||void 0===o?void 0:o.call(s))&&(this.nextRequestStatus.unsubscribe(i),this.loggerWrapper.debug("Removing script",e.id),this.shadowRoot.removeChild(t))}))}}catch(e){s(e)}}))}))))),o=new Promise((e=>{setTimeout((()=>{this.loggerWrapper.warn("SDK scripts loading timeout"),e(!0)}),u)}));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,le,"m",fe).call(this),window.addEventListener("visibilitychange",e(this,pe,"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,We,"f").call(this),null===(i=e(this,de,"f"))||void 0===i||i.abort(),t(this,de,null,"f"),window.removeEventListener("visibilitychange",e(this,pe,"f").visibilitychange)}getHtmlFilenameWithLocale(e,t){return i(this,void 0,void 0,(function*(){let i;const s=o(e),r=yield this.getTargetLocales();return r.includes(s.locale)?i=`${t}-${s.locale}.html`:r.includes(s.fallback)&&(i=`${t}-${s.fallback}.html`),i}))}getPageContent(e,t){return i(this,void 0,void 0,(function*(){if(t)try{const{body:e}=yield this.fetchStaticResource(t,"text");return e}catch(i){this.loggerWrapper.error(`Failed to fetch flow page from ${t}. Fallback to url ${e}`,i)}try{const{body:t}=yield this.fetchStaticResource(e,"text");return t}catch(e){this.loggerWrapper.error("Failed to fetch flow page",e.message)}return null}))}onFlowChange(d,c,p){return i(this,void 0,void 0,(function*(){var h,u;const{projectId:g,flowId:v,tenant:m,stepId:f,executionId:b,action:w,screenId:S,screenState:y,redirectTo:O,redirectIsPopup:x,redirectUrl:E,token:A,code:L,isPopup:U,exchangeError:P,webauthnTransactionId:F,webauthnOptions:$,redirectAuthCodeChallenge:N,redirectAuthCallbackUrl:M,redirectAuthBackupCallbackUri:q,redirectAuthInitiator:V,locale:D,samlIdpResponseUrl:B,samlIdpResponseSamlResponse:K,samlIdpResponseRelayState:H,wsFedIdpResponseUrl:z,wsFedIdpResponseWresult:Q,wsFedIdpResponseWctx:Z,nativeResponseType:ee,nativePayload:te,reqTimestamp:ie}=d,se=s(d,["projectId","flowId","tenant","stepId","executionId","action","screenId","screenState","redirectTo","redirectIsPopup","redirectUrl","token","code","isPopup","exchangeError","webauthnTransactionId","webauthnOptions","redirectAuthCodeChallenge","redirectAuthCallbackUrl","redirectAuthBackupCallbackUri","redirectAuthInitiator","locale","samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState","wsFedIdpResponseUrl","wsFedIdpResponseWresult","wsFedIdpResponseWctx","nativeResponseType","nativePayload","reqTimestamp"]);let oe,re,ne;const ae=_(),{outboundAppId:pe}=this,{outboundAppScopes:he}=this,ue=this.sdk.getLastUserLoginId(),ge=yield this.getFlowConfig(),me=yield this.getProjectConfig(),fe=Object.entries(me.flows||{}).reduce(((e,[t,i])=>(e[t]=i.version,e)),{}),be=M&&N?{callbackUrl:M,codeChallenge:N,backupCallbackUri:q}:void 0,we=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 Se={};if(!b){X(this.loggerWrapper);const i=[...ge.clientScripts||[],...ge.sdkScripts||[]];if(ge.conditions){let e=[];({startScreenId:oe,conditionInteractionId:ne,startScreenName:re,clientScripts:e,componentsConfig:Se}=G({loginId:ue,code:L,token:A,abTestingKey:ae,lastAuth:Y(ue,this.loggerWrapper)},ge.conditions)),i.push(...e||[])}else ge.condition?({startScreenId:oe,conditionInteractionId:ne}=J(ge.condition,{loginId:ue,code:L,token:A,abTestingKey:ae,lastAuth:Y(ue,this.loggerWrapper)})):(re=ge.startScreenName,oe=ge.startScreenId);if(t(this,ce,this.loadSdkScripts(i),"f"),ge.fingerprintEnabled&&ge.fingerprintKey?yield r(ge.fingerprintKey,this.baseUrl):n(),!I(oe,se)){const t=yield this.sdk.flow.start(v,Object.assign(Object.assign(Object.assign(Object.assign({tenant:m,redirectAuth:be},se),{client:this.client}),E&&{redirectUrl:E}),{lastAuth:Y(ue,this.loggerWrapper),abTestingKey:ae,locale:o(D).locale,nativeOptions:we,outboundAppId:pe,outboundAppScopes:he}),ne,"",me.componentsVersion,fe,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),L?{exchangeCode:L,idpInitiated:!0}:{}),se.descopeIdpInitiated&&{idpInitiated:!0}),A?{token:A}:{}),se.oidcLoginHint?{externalId:se.oidcLoginHint}:{}));return e(this,Oe,"f").call(this,t),void("completed"!==(null===(h=null==t?void 0:t.data)||void 0===h?void 0:h.status)&&this.flowState.update({code:void 0,token:void 0}))}}if(this.loggerWrapper.debug("Before popup postmessage send",JSON.stringify({isPopup:U,code:L,exchangeError:P,isCodeChanged:p("code"),isExchangeErrorChanged:p("exchangeError")})),U&&(p("code")&&L||p("exchangeError")&&P))return void e(this,le,"m",He).call(this,b,L,P);if(b&&(p("token")&&A||p("code")&&L||p("exchangeError")&&P)){const t=yield this.sdk.flow.next(b,f,a.submit,ge.version,me.componentsVersion,{token:A,exchangeCode:L,exchangeError:P});return e(this,Oe,"f").call(this,t),void this.flowState.update({token:void 0,code:void 0,exchangeError:void 0})}if(w===l.loadForm&&B&&["samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState"].some((e=>p(e)))){if(!K)return void this.loggerWrapper.error("Did not get saml idp params data to load");R(B,K,H||"",j)}if(w===l.loadForm&&z&&["wsFedIdpResponseUrl","wsFedIdpResponseWresult","wsFedIdpResponseWctx"].some((e=>p(e)))){if(!Q)return void this.loggerWrapper.error("Did not get wsfed idp params data to load");C(z,Q,Z||"",j)}if(w===l.redirect&&(p("redirectTo")||p("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=W(O,"?",598,700),i=this.shouldUsePopupPostMessage();i&&(t.name=`descope-wc|${window.location.origin}`),this.loggerWrapper.debug("Popup communication method: "+(i?"postMessage":"BroadcastChannel"));let s=!1;const o=e=>{this.loggerWrapper.debug("Received popup message",JSON.stringify(e.data));const t=i?this.popupOrigin:window.location.origin;if(e.origin!==t)return void this.loggerWrapper.debug(`Ignoring message from unexpected origin. received: "${e.origin}", expected: "${t}"`);const{action:o,data:r}=e.data||{};"code"===o&&(s=!0,this.flowState.update({code:r.code,exchangeError:r.exchangeError}))};let r;this.loggerWrapper.debug("Starting popup closed detection");const n=setInterval((()=>{t.closed&&(this.loggerWrapper.debug("Popup closed, dispatching popupclosed event"),clearInterval(n),e(this,le,"m",Ke).call(this,"popupclosed",{abandoned:!s}),this.loggerWrapper.debug("Cleaning up popup listeners"),null==r||r())}),1e3);if(i)window.addEventListener("message",o),r=()=>{this.loggerWrapper.debug("Cleaning up popup postMessage listener"),window.removeEventListener("message",o)};else{this.loggerWrapper.debug("Creating broadcast channel");const e=new BroadcastChannel(b);e.onmessage=o,r=()=>{this.loggerWrapper.debug("Closing channel"),e.close()}}}else this.handleRedirect(O),this.flowState.update({redirectTo:"no-op"}),e(this,le,"m",Ke).call(this,"popupclosed",{});return}if(w===l.webauthnCreate||w===l.webauthnGet){if(!F||!$)return void this.loggerWrapper.error("Did not get webauthn transaction id or options");let i,s,o,r;null===(u=e(this,de,"f"))||void 0===u||u.abort(),t(this,de,null,"f");try{i=w===l.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,o=e.reason,r=e.message}const n=yield this.sdk.flow.next(b,f,a.submit,ge.version,me.componentsVersion,{transactionId:F,response:i,failure:s,failureReason:o,failureMessage:r});e(this,Oe,"f").call(this,n)}if(w===l.nativeBridge)return this.nativeCallbacks.complete=t=>i(this,void 0,void 0,(function*(){const i=yield this.sdk.flow.next(b,f,a.submit,ge.version,me.componentsVersion,t);e(this,Oe,"f").call(this,i)})),e(this,le,"m",ve).call(this,ee,te),void setTimeout((()=>{this.dispatchEvent(new Event("popupclosed"))}),500);if((p("action")||p("deferredPolling"))&&e(this,Ce,"f").call(this,b,f,ge.version,me.componentsVersion),!S&&!oe)return void this.loggerWrapper.warn("No screen was found to show");const Ie=oe||S,Re=yield this.getHtmlFilenameWithLocale(D,Ie),{oidcLoginHint:We,oidcPrompt:ke,oidcErrorRedirectUri:xe,oidcResource:Ee,samlIdpUsername:Ae}=se,je={direction:k(f,c.stepId),screenState:Object.assign(Object.assign({},y),{form:Object.assign(Object.assign({},this.formConfigValues),null==y?void 0:y.form),lastAuth:{loginId:ue,name:this.sdk.getLastUserDisplayName()||ue},componentsConfig:Object.assign(Object.assign(Object.assign({},ge.componentsConfig),Se),null==y?void 0:y.componentsConfig)}),htmlFilename:`${Ie}.html`,htmlLocaleFilename:Re,screenId:Ie,stepName:d.stepName||re,samlIdpUsername:Ae,oidcLoginHint:We,oidcPrompt:ke,oidcErrorRedirectUri:xe,oidcResource:Ee,action:w,locale:o(D).locale},Te=Y(ue,this.loggerWrapper);I(oe,se)?je.next=(t,s)=>i(this,void 0,void 0,(function*(){const i=(null==ge?void 0:ge.clientScripts)||[];yield e(this,le,"m",Me).call(this,i);const r=yield this.sdk.flow.start(v,Object.assign(Object.assign(Object.assign(Object.assign({tenant:m,redirectAuth:be},se),{lastAuth:Te,preview:this.preview,abTestingKey:ae,client:this.client}),E&&{redirectUrl:E}),{locale:o(D).locale,nativeOptions:we,outboundAppId:pe,outboundAppScopes:he}),ne,t,me.componentsVersion,fe,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),this.getComponentsContext()),T(s)),L&&{exchangeCode:L,idpInitiated:!0}),se.descopeIdpInitiated&&{idpInitiated:!0}),A&&{token:A}),je.next.isCustomScreen);return e(this,Oe,"f").call(this,r),r})):(p("projectId")||p("baseUrl")||p("executionId")||p("stepId"))&&(je.next=(t,s)=>i(this,void 0,void 0,(function*(){const i=(null==y?void 0:y.clientScripts)||[];yield e(this,le,"m",Me).call(this,i);const o=yield this.sdk.flow.next(b,f,t,ge.version,me.componentsVersion,Object.assign(Object.assign({},this.getComponentsContext()),T(s)),je.next.isCustomScreen);return e(this,Oe,"f").call(this,o),o}))),this.loggerWrapper.debug("Got a screen with id",je.screenId),yield e(this,le,"m",ye).call(this,je),this.stepState.update(je)}))}onStepChange(t,s){return i(this,void 0,void 0,(function*(){var o,r,n;const{htmlFilename:l,htmlLocaleFilename:d,direction:c,next:p,screenState:h,screenId:u}=t;this.loggerWrapper.debug("Rendering a flow screen"),this.updateScreenUser(null==h?void 0:h.user);const g=document.createElement("template");g.innerHTML=yield this.getPageContent(l,d);const m=g.content.cloneNode(!0),f=this.loadDescopeUiComponents(g);this.sdk.webauthn.helpers.isSupported()?yield e(this,le,"m",Ae).call(this,m,p):F(m),!t.samlIdpUsername||(null===(o=h.form)||void 0===o?void 0:o.loginId)||(null===(r=h.form)||void 0===r?void 0:r.email)||(h.form||(h.form={}),h.form.loginId=t.samlIdpUsername,h.form.email=t.samlIdpUsername),$(m,h,this.formConfig,this.loggerWrapper),this.applyComponentsState(m,null==h?void 0:h.componentsState);const{geo:b}=null!==(n=yield this.getExecutionContext())&&void 0!==n?n:{};N(m,b),M(m,t.locale);const w=()=>i(this,void 0,void 0,(function*(){var i,o;yield f;const r=this.contentRootElement;q(r,null===(i=null==h?void 0:h.totp)||void 0===i?void 0:i.image),V(r,null===(o=null==h?void 0:h.notp)||void 0===o?void 0:o.image),D(r,m,h.cssVars,this.loggerWrapper),r.replaceChildren(m);const n=!s.htmlFilename;setTimeout((()=>{e(this,le,"m",Fe).call(this),this.updateUsernameAnchor(),this.validateOnBlur&&L(r),B(r,h),this.initRealtimeConditions(r,h),e(this,le,"m",je).call(this,{isFirstScreen:n,isCustomScreen:!1,stepName:t.stepName}),O(r,this.autoFocus,n),e(this,le,"m",De).call(this,u)})),e(this,le,"m",Be).call(this,p,u);r.querySelector(`[${v}="polling"]`)&&p(a.polling,{})}));c?e(this,le,"m",Re).call(this,w):w()}))}getInputs(){return Array.from(this.shadowRoot.querySelectorAll(`*:not(slot)[name]:not([${g}])`))}shouldUsePopupPostMessage(){if(!this.popupOrigin)return!1;try{new URL(this.popupOrigin)}catch(e){return!1}return!0}}ae=new WeakMap,de=new WeakMap,ce=new WeakMap,pe=new WeakMap,Se=new WeakMap,Ie=new WeakMap,Ce=new WeakMap,We=new WeakMap,ke=new WeakMap,Oe=new WeakMap,xe=new WeakMap,Ue=new WeakMap,Ne=new WeakMap,le=new WeakSet,he=function(){document.hidden||setTimeout((()=>{this.flowState.update({deferredRedirect:!1,deferredPolling:!1})}),300)},ue=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,le,"m",ve).call(this,"beforeScreen",{screen:t,context:s})}))}))},ge=function(t){var i;(null===(i=this.nativeOptions)||void 0===i?void 0:i.bridgeVersion)>=2&&e(this,le,"m",ve).call(this,"afterScreen",{screen:t})},ve=function(t,i){e(this,le,"m",Ke).call(this,"bridge",{type:t,payload:i})},me=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)}K(this.contentRootElement,"error-message",s)};this.addEventListener("screen-updated",i,{once:!0}),i()},fe=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,le,"m",me).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,le,"m",be).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})},be=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=""}))})),O(this.contentRootElement,this.autoFocus,!1))},we=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")}))},ye=function(o){return i(this,void 0,void 0,(function*(){var i;const r=Object.assign(Object.assign({},this.stepState.current),o),{next:n,stepName:l}=r,a=s(r,["next","stepName"]),d=x(a);let c=yield e(this,le,"m",ue).call(this,l,d,n);c||(c=Boolean(yield null===(i=this.onScreenUpdate)||void 0===i?void 0:i.call(this,l,d,n,this)));const p=!this.stepState.current.htmlFilename;if(e(this,Ie,"f").call(this,c),n&&(n.isCustomScreen=c),e(this,Se,"f")!==c){const[i,s]=["flow","custom"].sort((()=>c?-1:1));this.loggerWrapper.debug(`Switching from ${s} screen to ${i} screen`),t(this,Se,c,"f"),c?this.stepState.unsubscribeAll():e(this,le,"m",fe).call(this)}c?(this.loggerWrapper.debug("Showing a custom screen"),e(this,le,"m",je).call(this,{isFirstScreen:p,isCustomScreen:c,stepName:o.stepName}),this.disableKeyPressHandler()):this.handleKeyPress(),this.stepState.forceUpdate=c}))},Re=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")},Ee=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)}))}},Ae=function(s,o){return i(this,void 0,void 0,(function*(){var r;null===(r=e(this,de,"f"))||void 0===r||r.abort();const n=s.querySelector('*[autocomplete="webauthn"]');if(n&&(yield H())){const{options:s,transactionId:r}=(yield e(this,xe,"f").call(this))||{};s&&r&&(e(this,le,"m",Ee).call(this,n),t(this,de,new AbortController,"f"),this.sdk.webauthn.helpers.conditional(s,e(this,de,"f")).then((e=>i(this,void 0,void 0,(function*(){o(n.id,{transactionId:r,response:e})})))).catch((e=>{"AbortError"!==e.name&&this.loggerWrapper.error("Conditional login failed",e.message)})))}}))},je=function({isFirstScreen:t,isCustomScreen:i,stepName:s}){t&&e(this,le,"m",Ke).call(this,"ready",{}),i||e(this,le,"m",ge).call(this,s),e(this,le,"m",Ke).call(this,"page-updated",{screenName:s}),e(this,le,"m",Ke).call(this,"screen-updated",{screenName:s})},Te=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},Le=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})),{})}))},Pe=function(s){var o,r;const n=Array.from(this.contentRootElement.querySelectorAll(':not([disabled]), [disabled="false"]')).filter((e=>e!==s)),l=(null===(r=null===(o=this.flowState.current)||void 0===o?void 0:o.screenState)||void 0===r?void 0:r.clientScripts)||[],a=()=>{s.removeAttribute("loading"),n.forEach((e=>{e.removeAttribute("disabled")}))},d=e=>i(this,void 0,void 0,(function*(){var s;this.loggerWrapper.debug("Restoring components state"),this.removeEventListener("popupclosed",d);if(!0===(null===(s=null==e?void 0:e.detail)||void 0===s?void 0:s.abandoned)&&l.length)return t(this,ce,(()=>i(this,void 0,void 0,(function*(){try{yield this.loadSdkScripts(l)}catch(e){this.loggerWrapper.warn("Failed to refresh client scripts on popup close",null==e?void 0:e.message)}})))(),"f"),void a();a();const o=yield this.getFlowConfig(),r=[...o.clientScripts||[],...o.sdkScripts||[]];this.loadSdkScripts(r)})),c=()=>{var i;window.removeEventListener("pageshow",e(this,Ue,"f")),t(this,Ue,(e=>{e.persisted&&(this.logger.debug("Page was loaded from cache, restoring components state"),d())}),"f"),window.addEventListener("pageshow",e(this,Ue,"f"),{once:!0});const s=null===(i=this.stepState)||void 0===i?void 0:i.subscribe(((e,t)=>{e===t&&d(),this.removeEventListener("popupclosed",d),this.stepState.unsubscribe(s)}),(e=>e.screenId),{forceUpdate:!0})},p=this.nextRequestStatus.subscribe((({isLoading:e})=>{e?(this.addEventListener("popupclosed",d,{once:!0}),s.setAttribute("loading","true"),n.forEach((e=>e.setAttribute("disabled","true")))):(this.nextRequestStatus.unsubscribe(p),"success"===this.flowStatus?(this.removeEventListener("popupclosed",d),a()):c())}))},Fe=function(){U();this.contentRootElement.querySelectorAll('[external-input="true"]').forEach((t=>e(this,le,"m",$e).call(this,t)))},$e=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)}))},Me=function(t){return i(this,void 0,void 0,(function*(){if(e(this,ce,"f")){this.loggerWrapper.debug("Waiting for sdk scripts to load");const t=Date.now();yield e(this,ce,"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 w(u,Promise.all(o),null)}catch(e){this.loggerWrapper.error("Failed to refresh script module",e.message)}}))},qe=function(t,i){this.contentRootElement.querySelectorAll('descope-passcode[data-auto-submit="true"]').forEach((s=>{s.addEventListener("input",(()=>{var o;(null===(o=s.checkValidity)||void 0===o?void 0:o.call(s))&&e(this,Ne,"f").call(this,s,t,i)}))}))},Ve=function(e,t,i){t&&i&&"true"===e.getAttribute(m)&&Z(i,t,this.loggerWrapper)},De=function(e){var t;const i=this.sdk.getLastUserLoginId(),s=null===(t=Y(i,this.loggerWrapper).lastUsedPerScreen)||void 0===t?void 0:t[e];if(!s)return;const o=this.contentRootElement.querySelector(f),r=this.contentRootElement.querySelector(`#${CSS.escape(s)}`);o&&r&&(r.replaceWith(o),o.appendChild(r))},Be=function(t,i){this.contentRootElement.querySelectorAll(`descope-button:not([${b}]), [data-type="button"]:not([${b}]`).forEach((s=>{s.onclick=()=>{e(this,Ne,"f").call(this,s,t,i)}})),e(this,le,"m",qe).call(this,t,i),this.isDismissScreenErrorOnInput&&this.contentRootElement.querySelectorAll(`*[name]:not([${g}])`).forEach((e=>{e.addEventListener("input",(()=>{this.stepState.update((e=>Object.assign(Object.assign({},e),{screenState:Object.assign(Object.assign({},e.screenState),{errorText:"",errorType:""})})))}))}))},Ke=function(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t}))},He=function(e,t,i){var s;const[o,r]=(null===(s=window.name)||void 0===s?void 0:s.split("|"))||[],n={data:{code:t,exchangeError:i},action:"code"};if("descope-wc"===o&&r){this.loggerWrapper.debug("Using postMessage fallback to notify opener in origin",r);try{window.opener.postMessage(n,r)}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(n),t.close()}try{window.close()}catch(e){}};export{_e as default};
|
|
1
|
+
import{__classPrivateFieldGet as e,__classPrivateFieldSet as t,__awaiter as i,__rest as s}from"tslib";import{getUserLocale as o}from"@descope/sdk-helpers";import{ensureFingerprintIds as n,clearFingerprintData as r}from"@descope/web-js-sdk";import{RESPONSE_ACTIONS as l,CUSTOM_INTERACTIONS as a,URL_CODE_PARAM_NAME as d,URL_ERR_PARAM_NAME as c,URL_TOKEN_PARAM_NAME as p,URL_RUN_IDS_PARAM_NAME as h,SDK_SCRIPTS_LOAD_TIMEOUT as u,DESCOPE_ATTRIBUTE_EXCLUDE_FIELD as g,ELEMENT_TYPE_ATTRIBUTE as v,DESCOPE_ATTRIBUTE_OPT_IN_LAST_USED as m,DESCOPE_LAST_AUTH_BADGE_COMPONENT as f,DESCOPE_ATTRIBUTE_EXCLUDE_NEXT_BUTTON as b}from"../constants/index.js";import{timeoutPromise as w,withMemCache as S,leadingDebounce as y,showFirstScreenOnExecutionInit as I,injectSamlIdpForm as R,injectWsFedIdpForm as C,openCenteredPopup as W,getAnimationDirection as k,handleAutoFocus as O,transformStepStateForCustomScreen as x,getElementDescopeAttributes as E,getScriptResultPath as A,submitForm as j,transformScreenInputs as T,handleReportValidityOnBlur as L,clearPreviousExternalInputs as U}from"../helpers/helpers.js";import P from"../helpers/state.js";import{disableWebauthnButtons as F,updateTemplateFromScreenState as $,setComponentsAutoDetectByGeo as M,setComponentsAutoDetectByLocale as N,setTOTPVariable as q,setNOTPVariable as V,setCssVars as D,updateScreenFromScreenState as B,replaceElementMessage as K}from"../helpers/templates.js";import{isConditionalLoginSupported as H}from"../helpers/webauthn.js";import{getABTestingKey as _}from"../helpers/abTestingKey.js";import{calculateConditions as G,calculateCondition as J}from"../helpers/conditions.js";import{setLastAuth as z,getInFlightLastUsedPerScreen as Q,clearInFlightLastAuth as X,getLastAuth as Y,updateLastUsedPerScreen as Z}from"../helpers/lastAuth.js";import ee from"./BaseDescopeWc.js";import{FETCH_EXCEPTION_ERROR_CODE as te,FETCH_ERROR_RESPONSE_ERROR_CODE as ie,FLOW_REQUESTED_IS_IN_OLD_VERSION_ERROR_CODE as se,FLOW_TIMED_OUT_ERROR_CODE as oe,NONCE_VALIDATION_ERROR_CODE as ne,POLLING_STATUS_NOT_FOUND_ERROR_CODE as re}from"../constants/general.js";var le,ae,de,ce,pe,he,ue,ge,ve,me,fe,be,we,Se,ye,Ie,Re,Ce,We,ke,Oe,xe,Ee,Ae,je,Te,Le,Ue,Pe,Fe,$e,Me,Ne,qe,Ve,De,Be,Ke,He,_e;class Ge extends ee{static set sdkConfigOverrides(e){ee.sdkConfigOverrides=e}static get sdkConfigOverrides(){return ee.sdkConfigOverrides}constructor(){const s=new P({deferredRedirect:!1,deferredPolling:!1});super(s.update.bind(s)),le.add(this),this.stepState=new P({}),ae.set(this,void 0),de.set(this,null),ce.set(this,null),pe.set(this,{visibilitychange:e(this,le,"m",he).bind(this)}),this.bridgeVersion=Ge.bridgeVersion,ue.set(this,void 0),this.nativeCallbacks={},ye.set(this,!1),this.handleRedirect=e=>{window.location.assign(e)},Re.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,le,"m",Ce).call(this,i):i()})),We.set(this,((s,o,n,r,d=!1)=>{const c=[oe,re,ne];if(this.flowState.current.action===l.poll){if(e(this,Oe,"f").call(this)&&document.hidden)return this.logger.debug("polling - Deferring polling until in foreground"),void this.flowState.update({deferredPolling:!0});this.logger.debug("polling - Scheduling polling request");const l=Date.now(),p=d?500:2e3;t(this,ae,setTimeout((()=>i(this,void 0,void 0,(function*(){var t,i;this.logger.debug("polling - Calling next");const h=this.sdk.flow.next(s,o,a.polling,n,r,{}),u=document.hidden&&!d&&Date.now()-l>p+500;let g;u&&this.logger.debug("polling - The polling seems to be throttled");try{const e=u?1e3:6e3;g=yield w(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,r,u)}if((null===(t=null==g?void 0:g.error)||void 0===t?void 0:t.errorCode)===te)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,r);this.logger.debug("polling - Got a response"),(null==g?void 0:g.error)&&this.logger.debug("polling - Response has an error",JSON.stringify(g.error,null,4)),(null===(i=null==g?void 0:g.error)||void 0===i?void 0:i.errorCode)&&c.includes(g.error.errorCode)?this.logger.debug("polling - Stopping polling due to error"):e(this,We,"f").call(this,s,o,n,r),e(this,xe,"f").call(this,g)}))),p),"f")}})),ke.set(this,(()=>{clearTimeout(e(this,ae,"f")),t(this,ae,null,"f")})),Oe.set(this,(()=>!!window.descopeBridge||/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent))),xe.set(this,(i=>{var s,o,n,r,a,d,c,p,h,u,g,v,m;if(!(null==i?void 0:i.ok)){const t=null===(s=null==i?void 0:i.response)||void 0===s?void 0:s.url,l=`${null===(o=null==i?void 0:i.response)||void 0===o?void 0:o.status} - ${null===(n=null==i?void 0:i.response)||void 0===n?void 0:n.statusText}`;e(this,le,"m",He).call(this,"error",(null==i?void 0:i.error)||{errorCode:ie,errorDescription:l,errorMessage:t}),this.loggerWrapper.error((null===(r=null==i?void 0:i.error)||void 0===r?void 0:r.errorDescription)||t,(null===(a=null==i?void 0:i.error)||void 0===a?void 0:a.errorMessage)||l);const c=null===(d=null==i?void 0:i.error)||void 0===d?void 0:d.errorCode;return void(c!==se&&c!==oe&&c!==ne||!this.isRestartOnError||e(this,le,"m",Se).call(this))}null===(p=null===(c=i.data)||void 0===c?void 0:c.runnerLogs)||void 0===p||p.forEach((e=>{const{level:t,title:i,log:s}=e;t&&this.loggerWrapper[t]?this.loggerWrapper[t](i,s):this.loggerWrapper.info(i,s)}));const f=null===(g=null===(u=null===(h=i.data)||void 0===h?void 0:h.screen)||void 0===u?void 0:u.state)||void 0===g?void 0:g.errorText;(null===(v=i.data)||void 0===v?void 0:v.error)?this.loggerWrapper.error(`[${i.data.error.code}]: ${i.data.error.description}`,`${f?`${f} - `:""}${i.data.error.message}`):f&&this.loggerWrapper.error(f);const{status:b,authInfo:w,lastAuth:S,action:y,openInNewTabUrl:I}=i.data;if(y!==l.poll&&e(this,ke,"f").call(this),"completed"===b){this.storeLastAuthenticatedUser&&z(Object.assign(Object.assign({},S),{lastUsedPerScreen:Q()})),X(this.loggerWrapper);const t=Object.assign({},w);return i.data.output&&Object.keys(i.data.output).length>0&&(t.flowOutput=i.data.output),void e(this,le,"m",He).call(this,"success",t)}this.storeLastAuthenticatedUser&&z(S,!0),I&&window.open(I,"_blank");const{executionId:R,stepId:C,stepName:W,screen:k,redirect:O,webauthn:x,error:E,samlIdpResponse:A,wsFedIdpResponse:j,nativeResponse:T}=i.data,L=Date.now();y!==l.poll?(this.loggerWrapper.info(`Step "${W||`#${C}`}" is ${b}`,"",{screen:k,status:b,stepId:C,stepName:W,action:y,error:E}),(null===(m=k.state)||void 0===m?void 0:m.clientScripts)&&t(this,ce,this.loadSdkScripts(k.state.clientScripts),"f"),this.flowState.update({stepId:C,stepName:W,executionId:R,action:y,redirectTo:null==O?void 0:O.url,redirectIsPopup:null==O?void 0:O.isPopup,screenId:null==k?void 0:k.id,screenState:null==k?void 0:k.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:L})):this.flowState.update({action:y,reqTimestamp:L})})),Ee.set(this,S((()=>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)}}))))),Pe.set(this,null),Ne.set(this,y(((t,s,o)=>i(this,void 0,void 0,(function*(){var i,n;if("true"===t.getAttribute("formnovalidate")||e(this,le,"m",Le).call(this)){const r=null==t?void 0:t.getAttribute("id");e(this,le,"m",De).call(this,t,r,o),e(this,le,"m",Fe).call(this,t);const l=yield e(this,le,"m",Ue).call(this),a=E(t);this.nextRequestStatus.update({isLoading:!0});const d=Object.assign(Object.assign(Object.assign({},a),l),{origin:(null===(i=this.nativeOptions)||void 0===i?void 0:i.origin)||window.location.origin}),c=yield s(r,d);this.nextRequestStatus.update({isLoading:!1}),this.captureLastSubmittedLoginId(l,null===(n=null==c?void 0:c.data)||void 0===n?void 0:n.executionId),this.storeCredentials(l)}}))))),this.flowState=s}nativeResume(t,i){var s,o,n,r,l,a;const u=JSON.parse(i);if("oauthWeb"===t||"sso"===t){let e,{exchangeCode:t}=u;if(!t){const i=new URL(u.url);t=null===(s=i.searchParams)||void 0===s?void 0:s.get(d),e=(null===(o=i.searchParams)||void 0===o?void 0:o.get(c))||void 0}null===(r=(n=this.nativeCallbacks).complete)||void 0===r||r.call(n,{exchangeCode:t,exchangeError:e,idpInitiated:!0})}else if("magicLink"===t){const t=new URL(u.url),i=t.searchParams.get(p),s=t.searchParams.get(h).split("_").pop();e(this,ke,"f").call(this),this.flowState.update({token:i,stepId:s,action:void 0})}else if("beforeScreen"===t){const{screenResolve:e}=this.nativeCallbacks;this.nativeCallbacks.screenResolve=null;const{override:t}=u;t||(this.nativeCallbacks.screenNext=null),null==e||e(t)}else if("resumeScreen"===t){const{interactionId:e,form:t}=u,{screenNext:i}=this.nativeCallbacks;this.nativeCallbacks.screenNext=null,null==i||i(e,t)}else null===(a=(l=this.nativeCallbacks).complete)||void 0===a||a.call(l,u)}loadSdkScriptsModules(){const e=this.shadowRoot.querySelectorAll("div[data-script-id]");return Array.from(e).map((e=>e.moduleRes)).filter((e=>!!e))}loadSdkScripts(e){if(!(null==e?void 0:e.length))return null;const t=(e,t)=>i=>{this.dispatchEvent(new CustomEvent("components-context",{detail:{[A(e.id,e.resultKey)]:i},bubbles:!0,composed:!0})),t(e.id)};this.loggerWrapper.debug(`Preparing to load scripts: ${e.map((e=>e.id)).join(", ")}`);const s=Promise.all(null==e?void 0:e.map((e=>i(this,void 0,void 0,(function*(){var i,s,o;const n=this.shadowRoot.querySelector(`[data-script-id="${e.id}"]`);if(n){this.loggerWrapper.debug("Script already loaded",e.id);const{moduleRes:t}=n;return null===(i=null==t?void 0:t.start)||void 0===i||i.call(t),t}(null===(s=globalThis.descope)||void 0===s?void 0:s[e.id])||(yield this.injectNpmLib("@descope/flow-scripts","1.0.17",`dist/${e.id}.js`));const r=null===(o=globalThis.descope)||void 0===o?void 0:o[e.id];return new Promise(((i,s)=>{try{const s=r(e.initArgs,{baseUrl:this.baseUrl,ref:this},t(e,i),this.loggerWrapper);if(s){const t=document.createElement("div");t.setAttribute("data-script-id",e.id),t.moduleRes=s,this.shadowRoot.appendChild(t);const i=this.nextRequestStatus.subscribe((()=>{var o;this.loggerWrapper.debug("Stopping script",e.id),(null===(o=s.stop)||void 0===o?void 0:o.call(s))&&(this.nextRequestStatus.unsubscribe(i),this.loggerWrapper.debug("Removing script",e.id),this.shadowRoot.removeChild(t))}))}}catch(e){s(e)}}))}))))),o=new Promise((e=>{setTimeout((()=>{this.loggerWrapper.warn("SDK scripts loading timeout"),e(!0)}),u)}));return Promise.race([s,o])}get isDismissScreenErrorOnInput(){return"true"===this.getAttribute("dismiss-screen-error-on-input")}init(){var e,i;if(!window.descopeBridge)return this._init();this.lazyInit=this._init,t(this,ue,null===(i=null===(e=null===window||void 0===window?void 0:window.descopeBridge)||void 0===e?void 0:e.registerFlow)||void 0===i?void 0:i.call(e,this),"f")}_init(){const t=Object.create(null,{init:{get:()=>super.init}});return i(this,void 0,void 0,(function*(){var i,s;this.shadowRoot.isConnected&&(null===(i=this.flowState)||void 0===i||i.subscribe(this.onFlowChange.bind(this)),e(this,le,"m",be).call(this),window.addEventListener("visibilitychange",e(this,pe,"f").visibilitychange)),yield null===(s=t.init)||void 0===s?void 0:s.call(this)}))}disconnectedCallback(){var i,s,o;super.disconnectedCallback(),e(this,ue,"f")&&(null===(s=null===(i=window.descopeBridge)||void 0===i?void 0:i.unregisterFlow)||void 0===s||s.call(i,e(this,ue,"f")),t(this,ue,void 0,"f")),this.flowState.unsubscribeAll(),this.stepState.unsubscribeAll(),e(this,ke,"f").call(this),null===(o=e(this,de,"f"))||void 0===o||o.abort(),t(this,de,null,"f"),window.removeEventListener("visibilitychange",e(this,pe,"f").visibilitychange)}getHtmlFilenameWithLocale(e,t){return i(this,void 0,void 0,(function*(){let i;const s=o(e),n=yield this.getTargetLocales();return n.includes(s.locale)?i=`${t}-${s.locale}.html`:n.includes(s.fallback)&&(i=`${t}-${s.fallback}.html`),i}))}getPageContent(e,t){return i(this,void 0,void 0,(function*(){if(t)try{const{body:e}=yield this.fetchStaticResource(t,"text");return e}catch(i){this.loggerWrapper.error(`Failed to fetch flow page from ${t}. Fallback to url ${e}`,i)}try{const{body:t}=yield this.fetchStaticResource(e,"text");return t}catch(e){this.loggerWrapper.error("Failed to fetch flow page",e.message)}return null}))}onFlowChange(d,c,p){return i(this,void 0,void 0,(function*(){var h,u;const{projectId:g,flowId:v,tenant:m,stepId:f,executionId:b,action:w,screenId:S,screenState:y,redirectTo:O,redirectIsPopup:x,redirectUrl:E,token:A,code:L,isPopup:U,exchangeError:P,webauthnTransactionId:F,webauthnOptions:$,redirectAuthCodeChallenge:M,redirectAuthCallbackUrl:N,redirectAuthBackupCallbackUri:q,redirectAuthInitiator:V,locale:D,samlIdpResponseUrl:B,samlIdpResponseSamlResponse:K,samlIdpResponseRelayState:H,wsFedIdpResponseUrl:z,wsFedIdpResponseWresult:Q,wsFedIdpResponseWctx:Z,nativeResponseType:ee,nativePayload:te,reqTimestamp:ie}=d,se=s(d,["projectId","flowId","tenant","stepId","executionId","action","screenId","screenState","redirectTo","redirectIsPopup","redirectUrl","token","code","isPopup","exchangeError","webauthnTransactionId","webauthnOptions","redirectAuthCodeChallenge","redirectAuthCallbackUrl","redirectAuthBackupCallbackUri","redirectAuthInitiator","locale","samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState","wsFedIdpResponseUrl","wsFedIdpResponseWresult","wsFedIdpResponseWctx","nativeResponseType","nativePayload","reqTimestamp"]);let oe,ne,re;const ae=_(),{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=N&&M?{callbackUrl:N,codeChallenge:M,backupCallbackUri:q}:void 0,we=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 Se={};if(!b){X(this.loggerWrapper);const i=[...ge.clientScripts||[],...ge.sdkScripts||[]];if(ge.conditions){let e=[];({startScreenId:oe,conditionInteractionId:re,startScreenName:ne,clientScripts:e,componentsConfig:Se}=G({loginId:ue,code:L,token:A,abTestingKey:ae,lastAuth:Y(ue,this.loggerWrapper)},ge.conditions)),i.push(...e||[])}else ge.condition?({startScreenId:oe,conditionInteractionId:re}=J(ge.condition,{loginId:ue,code:L,token:A,abTestingKey:ae,lastAuth:Y(ue,this.loggerWrapper)})):(ne=ge.startScreenName,oe=ge.startScreenId);if(t(this,ce,this.loadSdkScripts(i),"f"),ge.fingerprintEnabled&&ge.fingerprintKey?yield n(ge.fingerprintKey,this.baseUrl):r(),!I(oe,se)){const t=yield this.sdk.flow.start(v,Object.assign(Object.assign(Object.assign(Object.assign({tenant:m,redirectAuth:be},se),{client:this.client}),E&&{redirectUrl:E}),{lastAuth:Y(ue,this.loggerWrapper),abTestingKey:ae,locale:o(D).locale,nativeOptions:we,outboundAppId:pe,outboundAppScopes:he}),re,"",ve.componentsVersion,fe,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),L?{exchangeCode:L,idpInitiated:!0}:{}),se.descopeIdpInitiated&&{idpInitiated:!0}),A?{token:A}:{}),se.oidcLoginHint?{externalId:se.oidcLoginHint}:{}));return e(this,xe,"f").call(this,t),void("completed"!==(null===(h=null==t?void 0:t.data)||void 0===h?void 0:h.status)&&this.flowState.update({code:void 0,token:void 0}))}}if(this.loggerWrapper.debug("Before popup postmessage send",JSON.stringify({isPopup:U,code:L,exchangeError:P,isCodeChanged:p("code"),isExchangeErrorChanged:p("exchangeError")})),U&&(p("code")&&L||p("exchangeError")&&P))return void e(this,le,"m",_e).call(this,b,L,P);if(b&&(p("token")&&A||p("code")&&L||p("exchangeError")&&P)){const t=yield this.sdk.flow.next(b,f,a.submit,ge.version,ve.componentsVersion,{token:A,exchangeCode:L,exchangeError:P});return e(this,xe,"f").call(this,t),void this.flowState.update({token:void 0,code:void 0,exchangeError:void 0})}if(w===l.loadForm&&B&&["samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState"].some((e=>p(e)))){if(!K)return void this.loggerWrapper.error("Did not get saml idp params data to load");R(B,K,H||"",j)}if(w===l.loadForm&&z&&["wsFedIdpResponseUrl","wsFedIdpResponseWresult","wsFedIdpResponseWctx"].some((e=>p(e)))){if(!Q)return void this.loggerWrapper.error("Did not get wsfed idp params data to load");C(z,Q,Z||"",j)}if(w===l.redirect&&(p("redirectTo")||p("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=W(O,"?",598,700),i=this.shouldUsePopupPostMessage();i&&(t.name=`descope-wc|${window.location.origin}`),this.loggerWrapper.debug("Popup communication method: "+(i?"postMessage":"BroadcastChannel"));let s=!1;const o=e=>{this.loggerWrapper.debug("Received popup message",JSON.stringify(e.data));const t=i?this.popupOrigin:window.location.origin;if(e.origin!==t)return void this.loggerWrapper.debug(`Ignoring message from unexpected origin. received: "${e.origin}", expected: "${t}"`);const{action:o,data:n}=e.data||{};"code"===o&&(s=!0,this.flowState.update({code:n.code,exchangeError:n.exchangeError}))};let n;this.loggerWrapper.debug("Starting popup closed detection");const r=setInterval((()=>{t.closed&&(this.loggerWrapper.debug("Popup closed, dispatching popupclosed event"),clearInterval(r),e(this,le,"m",He).call(this,"popupclosed",{abandoned:!s}),this.loggerWrapper.debug("Cleaning up popup listeners"),null==n||n())}),1e3);if(i)window.addEventListener("message",o),n=()=>{this.loggerWrapper.debug("Cleaning up popup postMessage listener"),window.removeEventListener("message",o)};else{this.loggerWrapper.debug("Creating broadcast channel");const e=new BroadcastChannel(b);e.onmessage=o,n=()=>{this.loggerWrapper.debug("Closing channel"),e.close()}}}else this.handleRedirect(O),this.flowState.update({redirectTo:"no-op"}),e(this,le,"m",He).call(this,"popupclosed",{});return}if(w===l.webauthnCreate||w===l.webauthnGet){if(!F||!$)return void this.loggerWrapper.error("Did not get webauthn transaction id or options");let i,s,o,n;null===(u=e(this,de,"f"))||void 0===u||u.abort(),t(this,de,null,"f");try{i=w===l.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,o=e.reason,n=e.message}const r=yield this.sdk.flow.next(b,f,a.submit,ge.version,ve.componentsVersion,{transactionId:F,response:i,failure:s,failureReason:o,failureMessage:n});e(this,xe,"f").call(this,r)}if(w===l.nativeBridge)return this.nativeCallbacks.complete=t=>i(this,void 0,void 0,(function*(){const i=yield this.sdk.flow.next(b,f,a.submit,ge.version,ve.componentsVersion,t);e(this,xe,"f").call(this,i)})),e(this,le,"m",me).call(this,ee,te),void setTimeout((()=>{this.dispatchEvent(new Event("popupclosed"))}),500);if((p("action")||p("deferredPolling"))&&e(this,We,"f").call(this,b,f,ge.version,ve.componentsVersion),!S&&!oe)return void this.loggerWrapper.warn("No screen was found to show");const ye=oe||S,Re=yield this.getHtmlFilenameWithLocale(D,ye),{oidcLoginHint:Ce,oidcPrompt:ke,oidcErrorRedirectUri:Oe,oidcResource:Ee,samlIdpUsername:Ae}=se,je={direction:k(f,c.stepId),screenState:Object.assign(Object.assign({},y),{form:Object.assign(Object.assign({},this.formConfigValues),null==y?void 0:y.form),lastAuth:{loginId:ue,name:this.sdk.getLastUserDisplayName()||ue},componentsConfig:Object.assign(Object.assign(Object.assign({},ge.componentsConfig),Se),null==y?void 0:y.componentsConfig)}),htmlFilename:`${ye}.html`,htmlLocaleFilename:Re,screenId:ye,stepName:d.stepName||ne,samlIdpUsername:Ae,oidcLoginHint:Ce,oidcPrompt:ke,oidcErrorRedirectUri:Oe,oidcResource:Ee,action:w,locale:o(D).locale},Te=Y(ue,this.loggerWrapper);I(oe,se)?je.next=(t,s)=>i(this,void 0,void 0,(function*(){const i=(null==ge?void 0:ge.clientScripts)||[];yield e(this,le,"m",qe).call(this,i);const n=yield this.sdk.flow.start(v,Object.assign(Object.assign(Object.assign(Object.assign({tenant:m,redirectAuth:be},se),{lastAuth:Te,preview:this.preview,abTestingKey:ae,client:this.client}),E&&{redirectUrl:E}),{locale:o(D).locale,nativeOptions:we,outboundAppId:pe,outboundAppScopes:he}),re,t,ve.componentsVersion,fe,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),this.getComponentsContext()),T(s)),L&&{exchangeCode:L,idpInitiated:!0}),se.descopeIdpInitiated&&{idpInitiated:!0}),A&&{token:A}),je.next.isCustomScreen);return e(this,xe,"f").call(this,n),n})):(p("projectId")||p("baseUrl")||p("executionId")||p("stepId"))&&(je.next=(t,s)=>i(this,void 0,void 0,(function*(){const i=(null==y?void 0:y.clientScripts)||[];yield e(this,le,"m",qe).call(this,i);const o=yield this.sdk.flow.next(b,f,t,ge.version,ve.componentsVersion,Object.assign(Object.assign({},this.getComponentsContext()),T(s)),je.next.isCustomScreen);return e(this,xe,"f").call(this,o),o}))),this.loggerWrapper.debug("Got a screen with id",je.screenId),yield e(this,le,"m",Ie).call(this,je),this.stepState.update(je)}))}onStepChange(t,s){return i(this,void 0,void 0,(function*(){var o,n,r;const{htmlFilename:l,htmlLocaleFilename:d,direction:c,next:p,screenState:h,screenId:u}=t;this.loggerWrapper.debug("Rendering a flow screen"),this.updateScreenUser(null==h?void 0:h.user);const g=document.createElement("template");g.innerHTML=yield this.getPageContent(l,d);const m=g.content.cloneNode(!0),f=this.loadDescopeUiComponents(g);this.sdk.webauthn.helpers.isSupported()?yield e(this,le,"m",je).call(this,m,p):F(m),!t.samlIdpUsername||(null===(o=h.form)||void 0===o?void 0:o.loginId)||(null===(n=h.form)||void 0===n?void 0:n.email)||(h.form||(h.form={}),h.form.loginId=t.samlIdpUsername,h.form.email=t.samlIdpUsername),$(m,h,this.formConfig,this.loggerWrapper),this.applyComponentsState(m,null==h?void 0:h.componentsState);const{geo:b}=null!==(r=yield this.getExecutionContext())&&void 0!==r?r:{};M(m,b),N(m,t.locale);const w=()=>i(this,void 0,void 0,(function*(){var i,o;yield f;const n=this.contentRootElement;q(n,null===(i=null==h?void 0:h.totp)||void 0===i?void 0:i.image),V(n,null===(o=null==h?void 0:h.notp)||void 0===o?void 0:o.image),D(n,m,h.cssVars,this.loggerWrapper),n.replaceChildren(m);const r=!s.htmlFilename;setTimeout((()=>{e(this,le,"m",$e).call(this),this.updateUsernameAnchor(),this.validateOnBlur&&L(n),B(n,h),this.initRealtimeConditions(n,h),e(this,le,"m",Te).call(this,{isFirstScreen:r,isCustomScreen:!1,stepName:t.stepName}),O(n,this.autoFocus,r),e(this,le,"m",Be).call(this,u)})),e(this,le,"m",Ke).call(this,p,u);n.querySelector(`[${v}="polling"]`)&&p(a.polling,{})}));c?e(this,le,"m",Ce).call(this,w):w()}))}getInputs(){return Array.from(this.shadowRoot.querySelectorAll(`*:not(slot)[name]:not([${g}])`))}shouldUsePopupPostMessage(){if(!this.popupOrigin)return!1;try{new URL(this.popupOrigin)}catch(e){return!1}return!0}}ae=new WeakMap,de=new WeakMap,ce=new WeakMap,pe=new WeakMap,ue=new WeakMap,ye=new WeakMap,Re=new WeakMap,We=new WeakMap,ke=new WeakMap,Oe=new WeakMap,xe=new WeakMap,Ee=new WeakMap,Pe=new WeakMap,Ne=new WeakMap,le=new WeakSet,he=function(){document.hidden||setTimeout((()=>{this.flowState.update({deferredRedirect:!1,deferredPolling:!1})}),300)},ge=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,le,"m",me).call(this,"beforeScreen",{screen:t,context:s})}))}))},ve=function(t){var i;(null===(i=this.nativeOptions)||void 0===i?void 0:i.bridgeVersion)>=2&&e(this,le,"m",me).call(this,"afterScreen",{screen:t})},me=function(t,i){e(this,le,"m",He).call(this,"bridge",{type:t,payload:i})},fe=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)}K(this.contentRootElement,"error-message",s)};this.addEventListener("screen-updated",i,{once:!0}),i()},be=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,le,"m",fe).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,le,"m",we).bind(this),(e=>{var t,i;return{errorText:null===(t=null==e?void 0:e.screenState)||void 0===t?void 0:t.errorText,errorType:null===(i=null==e?void 0:e.screenState)||void 0===i?void 0:i.errorType}}),{forceUpdate:!0})},we=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=""}))})),O(this.contentRootElement,this.autoFocus,!1))},Se=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")}))},Ie=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=x(a);let c=yield e(this,le,"m",ge).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,Re,"f").call(this,c),r&&(r.isCustomScreen=c),e(this,ye,"f")!==c){const[i,s]=["flow","custom"].sort((()=>c?-1:1));this.loggerWrapper.debug(`Switching from ${s} screen to ${i} screen`),t(this,ye,c,"f"),c?this.stepState.unsubscribeAll():e(this,le,"m",be).call(this)}c?(this.loggerWrapper.debug("Showing a custom screen"),e(this,le,"m",Te).call(this,{isFirstScreen:p,isCustomScreen:c,stepName:o.stepName}),this.disableKeyPressHandler()):this.handleKeyPress(),this.stepState.forceUpdate=c}))},Ce=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")},Ae=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)}))}},je=function(s,o){return i(this,void 0,void 0,(function*(){var n;null===(n=e(this,de,"f"))||void 0===n||n.abort();const r=s.querySelector('*[autocomplete="webauthn"]');if(r&&(yield H())){const{options:s,transactionId:n}=(yield e(this,Ee,"f").call(this))||{};s&&n&&(e(this,le,"m",Ae).call(this,r),t(this,de,new AbortController,"f"),this.sdk.webauthn.helpers.conditional(s,e(this,de,"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)})))}}))},Te=function({isFirstScreen:t,isCustomScreen:i,stepName:s}){t&&e(this,le,"m",He).call(this,"ready",{}),i||e(this,le,"m",ve).call(this,s),e(this,le,"m",He).call(this,"page-updated",{screenName:s}),e(this,le,"m",He).call(this,"screen-updated",{screenName:s})},Le=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},Ue=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})),{})}))},Fe=function(s){var o,n;const r=Array.from(this.contentRootElement.querySelectorAll(':not([disabled]), [disabled="false"]')).filter((e=>e!==s)),l=(null===(n=null===(o=this.flowState.current)||void 0===o?void 0:o.screenState)||void 0===n?void 0:n.clientScripts)||[],a=()=>{s.removeAttribute("loading"),r.forEach((e=>{e.removeAttribute("disabled")}))},d=e=>i(this,void 0,void 0,(function*(){var s;this.loggerWrapper.debug("Restoring components state"),this.removeEventListener("popupclosed",d);if(!0===(null===(s=null==e?void 0:e.detail)||void 0===s?void 0:s.abandoned)&&l.length)return t(this,ce,(()=>i(this,void 0,void 0,(function*(){try{yield this.loadSdkScripts(l)}catch(e){this.loggerWrapper.warn("Failed to refresh client scripts on popup close",null==e?void 0:e.message)}})))(),"f"),void a();a();const o=yield this.getFlowConfig(),n=[...o.clientScripts||[],...o.sdkScripts||[]];this.loadSdkScripts(n)})),c=()=>{var i;window.removeEventListener("pageshow",e(this,Pe,"f")),t(this,Pe,(e=>{e.persisted&&(this.logger.debug("Page was loaded from cache, restoring components state"),d())}),"f"),window.addEventListener("pageshow",e(this,Pe,"f"),{once:!0});const s=null===(i=this.stepState)||void 0===i?void 0:i.subscribe(((e,t)=>{e===t&&d(),this.removeEventListener("popupclosed",d),this.stepState.unsubscribe(s)}),(e=>e.screenId),{forceUpdate:!0})},p=this.nextRequestStatus.subscribe((({isLoading:e})=>{e?(this.addEventListener("popupclosed",d,{once:!0}),s.setAttribute("loading","true"),r.forEach((e=>e.setAttribute("disabled","true")))):(this.nextRequestStatus.unsubscribe(p),"success"===this.flowStatus?(this.removeEventListener("popupclosed",d),a()):c())}))},$e=function(){U();this.contentRootElement.querySelectorAll('[external-input="true"]').forEach((t=>e(this,le,"m",Me).call(this,t)))},Me=function(e){if(!e)return;e.querySelectorAll("input").forEach((t=>{const i=t.getAttribute("slot"),s=`input-${e.id}-${i}`,o=document.createElement("slot");o.setAttribute("name",s),o.setAttribute("slot",i),e.appendChild(o),t.setAttribute("slot",s),this.appendChild(t)}))},qe=function(t){return i(this,void 0,void 0,(function*(){if(e(this,ce,"f")){this.loggerWrapper.debug("Waiting for sdk scripts to load");const t=Date.now();yield e(this,ce,"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 w(u,Promise.all(o),null)}catch(e){this.loggerWrapper.error("Failed to refresh script module",e.message)}}))},Ve=function(t,i){this.contentRootElement.querySelectorAll('descope-passcode[data-auto-submit="true"]').forEach((s=>{s.addEventListener("input",(()=>{var o;(null===(o=s.checkValidity)||void 0===o?void 0:o.call(s))&&e(this,Ne,"f").call(this,s,t,i)}))}))},De=function(e,t,i){t&&i&&"true"===e.getAttribute(m)&&Z(i,t,this.loggerWrapper)},Be=function(e){var t;const i=this.sdk.getLastUserLoginId(),s=null===(t=Y(i,this.loggerWrapper).lastUsedPerScreen)||void 0===t?void 0:t[e];if(!s)return;const o=this.contentRootElement.querySelector(f),n=this.contentRootElement.querySelector(`#${CSS.escape(s)}`);o&&n&&(n.replaceWith(o),o.appendChild(n))},Ke=function(t,i){this.contentRootElement.querySelectorAll(`descope-button:not([${b}]), [data-type="button"]:not([${b}]`).forEach((s=>{s.onclick=()=>{e(this,Ne,"f").call(this,s,t,i)}})),e(this,le,"m",Ve).call(this,t,i),this.isDismissScreenErrorOnInput&&this.contentRootElement.querySelectorAll(`*[name]:not([${g}])`).forEach((e=>{e.addEventListener("input",(()=>{this.stepState.update((e=>Object.assign(Object.assign({},e),{screenState:Object.assign(Object.assign({},e.screenState),{errorText:"",errorType:""})})))}))}))},He=function(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t}))},_e=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){}},Ge.bridgeVersion=3;export{Ge as default};
|
|
2
2
|
//# sourceMappingURL=DescopeWc.js.map
|