@descope/web-component 3.46.3 → 3.47.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/helpers/conditions.js +1 -1
- package/dist/cjs/helpers/conditions.js.map +1 -1
- package/dist/cjs/helpers/lastAuth.js +1 -1
- package/dist/cjs/helpers/lastAuth.js.map +1 -1
- package/dist/cjs/types.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/helpers/conditions.js +1 -1
- package/dist/esm/helpers/conditions.js.map +1 -1
- package/dist/esm/helpers/lastAuth.js +1 -1
- package/dist/esm/helpers/lastAuth.js.map +1 -1
- package/dist/esm/types.js.map +1 -1
- package/dist/index.js +2 -2
- package/package.json +2 -2
package/dist/cjs/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sources":["../../src/lib/types.ts"],"sourcesContent":["/* istanbul ignore file */\n\nimport createSdk from '@descope/web-js-sdk';\n\nexport type SdkConfig = Parameters<typeof createSdk>[0];\nexport type Sdk = ReturnType<typeof createSdk>;\n\nexport type SdkFlowNext = Sdk['flow']['next'];\n\nexport type ComponentsDynamicAttrs = {\n attributes: Record<string, any>;\n};\n\nexport type ComponentsConfig = Record<string, any> & {\n componentsDynamicAttrs?: Record<string, ComponentsDynamicAttrs>;\n};\nexport type CssVars = Record<string, any>;\n\ntype KeepArgsByIndex<F, Indices extends readonly number[]> = F extends (\n ...args: infer A\n) => infer R\n ? (...args: PickArgsByIndex<A, Indices>) => R\n : never;\n\ntype PickArgsByIndex<\n All extends readonly any[],\n Indices extends readonly number[],\n> = {\n [K in keyof Indices]: Indices[K] extends keyof All ? All[Indices[K]] : never;\n};\n\ntype Project = {\n name: string;\n};\n\nexport enum Direction {\n backward = 'backward',\n forward = 'forward',\n}\n\nexport interface LastAuthState {\n loginId?: string;\n name?: string;\n}\n\nexport interface ScreenState {\n errorText?: string;\n errorType?: string;\n componentsConfig?: ComponentsConfig;\n cssVars?: CssVars;\n form?: Record<string, string>;\n inputs?: Record<string, string>; // Backward compatibility\n lastAuth?: LastAuthState;\n project?: Project;\n totp?: { image?: string; provisionUrl?: string };\n notp?: { image?: string; redirectUrl?: string };\n selfProvisionDomains?: unknown;\n user?: unknown;\n sso?: unknown;\n dynamicSelects?: unknown;\n keysInUse?: unknown;\n genericForm?: unknown;\n linkId?: unknown;\n sentTo?: unknown;\n clientScripts?: ClientScript[];\n}\n\nexport type SSOQueryParams = {\n oidcIdpStateId?: string;\n samlIdpStateId?: string;\n samlIdpUsername?: string;\n descopeIdpInitiated?: boolean;\n ssoAppId?: string;\n thirdPartyAppId: string;\n thirdPartyAppStateId?: string;\n applicationScopes?: string;\n} & OIDCOptions;\n\nexport type OIDCOptions = {\n oidcLoginHint?: string;\n oidcPrompt?: string;\n oidcErrorRedirectUri?: string;\n oidcResource?: string;\n};\n\nexport type Locale = {\n locale: string;\n fallback: string;\n};\n\nexport type FlowState = {\n flowId: string;\n projectId: string;\n baseUrl: string;\n tenant: string;\n stepId: string;\n stepName: string;\n executionId: string;\n action: string;\n redirectTo: string;\n redirectIsPopup: boolean;\n openInNewTabUrl?: string;\n redirectUrl: string;\n screenId: string;\n screenState: ScreenState;\n token: string;\n code: string;\n isPopup: boolean;\n exchangeError: string;\n webauthnTransactionId: string;\n webauthnOptions: string;\n redirectAuthCodeChallenge: string;\n redirectAuthCallbackUrl: string;\n redirectAuthBackupCallbackUri: string;\n redirectAuthInitiator: string;\n deferredRedirect: boolean;\n locale: string;\n samlIdpResponseUrl: string;\n samlIdpResponseSamlResponse: string;\n samlIdpResponseRelayState: string;\n nativeResponseType: string;\n nativePayload: Record<string, any>;\n reqTimestamp: number;\n} & SSOQueryParams;\n\nexport type StepState = {\n screenState: ScreenState;\n screenId: string;\n stepName: string;\n htmlFilename: string;\n htmlLocaleFilename: string;\n next: NextFn;\n direction: Direction | undefined;\n samlIdpUsername: string;\n action?: string;\n} & OIDCOptions;\n\nexport type CustomScreenState = Omit<\n ScreenState,\n 'cssVars' | 'componentsConfig' | 'inputs'\n> & {\n error?: {\n text: ScreenState['errorText'];\n type: ScreenState['errorType'];\n };\n action?: string;\n inboundAppApproveScopes?: {\n desc: string;\n id: string;\n required: boolean;\n }[];\n};\n\nexport type DebugState = {\n isDebug: boolean;\n};\n\nexport interface ScriptElement extends HTMLDivElement {\n moduleRes?: ScriptModule;\n}\n\nexport type ScriptModule = {\n stop: () => void;\n start: () => void;\n /**\n * Refreshes any tokens or state that might be needed before form submission\n * Currently implemented for reCAPTCHA to ensure we have a fresh token\n */\n refresh?: () => Promise<void>;\n};\n\nexport type ClientScript = {\n id: string;\n initArgs: Record<string, any>;\n resultKey?: string;\n};\n\nexport type NextFn = KeepArgsByIndex<SdkFlowNext, [2, 5]>;\nexport type NextFnReturnPromiseValue = Awaited<ReturnType<NextFn>>;\n\nexport type DebuggerMessage = {\n title: string;\n description?: string;\n};\n\nexport type FlowStateUpdateFn = (state: FlowState) => void;\n\ntype Operator =\n | 'equal'\n | 'not-equal'\n | 'contains'\n | 'greater-than'\n | 'greater-than-or-equal'\n | 'less-than'\n | 'less-than-or-equal'\n | 'empty'\n | 'not-empty'\n | 'is-true'\n | 'is-false'\n | 'in'\n | 'not-in'\n | 'in-range'\n | 'not-in-range'\n | 'devised-by';\n\nexport interface ClientConditionResult {\n screenId: string;\n screenName: string;\n clientScripts?: ClientScript[];\n componentsConfig?: ComponentsConfig;\n interactionId: string;\n}\n\nexport interface ClientCondition {\n operator: Operator;\n key: string;\n predicate?: string | number;\n met: ClientConditionResult;\n unmet?: ClientConditionResult;\n}\n\nexport type AutoFocusOptions = true | false | 'skipFirstScreen';\n\nexport type ThemeOptions = 'light' | 'dark' | 'os';\n\nexport type Key =\n | 'lastAuth.loginId'\n | 'idpInitiated'\n | 'externalToken'\n | 'abTestingKey';\n\ntype CheckFunction = (ctx: Context, predicate?: string | number) => boolean;\n\nexport type ConditionsMap = {\n [key in Key]: {\n [operator in Operator]?: CheckFunction;\n };\n};\n\nexport interface Context {\n loginId?: string;\n code?: string;\n token?: string;\n abTestingKey?: number;\n}\n\nexport type DescopeUI = Record<string, () => Promise<void>> & {\n componentsThemeManager: Record<string, any>;\n};\n\ntype Font = {\n family: string[];\n label: string;\n url?: string;\n};\n\ntype ThemeTemplate = {\n fonts: {\n font1: Font;\n font2: Font;\n };\n};\n\nexport type FlowConfig = {\n startScreenId?: string;\n startScreenName?: string;\n version: number;\n targetLocales?: string[];\n conditions?: ClientCondition[];\n condition?: ClientCondition;\n fingerprintEnabled?: boolean;\n fingerprintKey?: string;\n sdkScripts?: [\n {\n id: string;\n initArgs: Record<string, any>;\n resultKey?: string;\n },\n ];\n clientScripts?: ClientScript[];\n componentsConfig?: ComponentsConfig;\n};\n\nexport interface ProjectConfiguration {\n componentsVersion: string;\n cssTemplate: {\n dark: ThemeTemplate;\n light: ThemeTemplate;\n };\n flows: {\n [key: string]: FlowConfig; // dynamic key names for flows\n };\n}\n\nexport type FlowStatus = 'loading' | 'error' | 'success' | 'ready' | 'initial';\n"],"names":["Direction"],"mappings":"aAmCA,IAAYA,EAAAA,QAGXA,eAAA,GAHWA,EAAAA,QAASA,YAATA,kBAGX,CAAA,IAFC,SAAA,WACAA,EAAA,QAAA"}
|
|
1
|
+
{"version":3,"file":"types.js","sources":["../../src/lib/types.ts"],"sourcesContent":["/* istanbul ignore file */\n\nimport createSdk from '@descope/web-js-sdk';\n\nexport type SdkConfig = Parameters<typeof createSdk>[0];\nexport type Sdk = ReturnType<typeof createSdk>;\n\nexport type SdkFlowNext = Sdk['flow']['next'];\n\nexport type ComponentsDynamicAttrs = {\n attributes: Record<string, any>;\n};\n\nexport type ComponentsConfig = Record<string, any> & {\n componentsDynamicAttrs?: Record<string, ComponentsDynamicAttrs>;\n};\nexport type CssVars = Record<string, any>;\n\ntype KeepArgsByIndex<F, Indices extends readonly number[]> = F extends (\n ...args: infer A\n) => infer R\n ? (...args: PickArgsByIndex<A, Indices>) => R\n : never;\n\ntype PickArgsByIndex<\n All extends readonly any[],\n Indices extends readonly number[],\n> = {\n [K in keyof Indices]: Indices[K] extends keyof All ? All[Indices[K]] : never;\n};\n\ntype Project = {\n name: string;\n};\n\nexport enum Direction {\n backward = 'backward',\n forward = 'forward',\n}\n\nexport interface LastAuthState {\n loginId?: string;\n name?: string;\n}\n\nexport interface ScreenState {\n errorText?: string;\n errorType?: string;\n componentsConfig?: ComponentsConfig;\n cssVars?: CssVars;\n form?: Record<string, string>;\n inputs?: Record<string, string>; // Backward compatibility\n lastAuth?: LastAuthState;\n project?: Project;\n totp?: { image?: string; provisionUrl?: string };\n notp?: { image?: string; redirectUrl?: string };\n selfProvisionDomains?: unknown;\n user?: unknown;\n sso?: unknown;\n dynamicSelects?: unknown;\n keysInUse?: unknown;\n genericForm?: unknown;\n linkId?: unknown;\n sentTo?: unknown;\n clientScripts?: ClientScript[];\n}\n\nexport type SSOQueryParams = {\n oidcIdpStateId?: string;\n samlIdpStateId?: string;\n samlIdpUsername?: string;\n descopeIdpInitiated?: boolean;\n ssoAppId?: string;\n thirdPartyAppId: string;\n thirdPartyAppStateId?: string;\n applicationScopes?: string;\n} & OIDCOptions;\n\nexport type OIDCOptions = {\n oidcLoginHint?: string;\n oidcPrompt?: string;\n oidcErrorRedirectUri?: string;\n oidcResource?: string;\n};\n\nexport type Locale = {\n locale: string;\n fallback: string;\n};\n\nexport type FlowState = {\n flowId: string;\n projectId: string;\n baseUrl: string;\n tenant: string;\n stepId: string;\n stepName: string;\n executionId: string;\n action: string;\n redirectTo: string;\n redirectIsPopup: boolean;\n openInNewTabUrl?: string;\n redirectUrl: string;\n screenId: string;\n screenState: ScreenState;\n token: string;\n code: string;\n isPopup: boolean;\n exchangeError: string;\n webauthnTransactionId: string;\n webauthnOptions: string;\n redirectAuthCodeChallenge: string;\n redirectAuthCallbackUrl: string;\n redirectAuthBackupCallbackUri: string;\n redirectAuthInitiator: string;\n deferredRedirect: boolean;\n locale: string;\n samlIdpResponseUrl: string;\n samlIdpResponseSamlResponse: string;\n samlIdpResponseRelayState: string;\n nativeResponseType: string;\n nativePayload: Record<string, any>;\n reqTimestamp: number;\n} & SSOQueryParams;\n\nexport type StepState = {\n screenState: ScreenState;\n screenId: string;\n stepName: string;\n htmlFilename: string;\n htmlLocaleFilename: string;\n next: NextFn;\n direction: Direction | undefined;\n samlIdpUsername: string;\n action?: string;\n} & OIDCOptions;\n\nexport type CustomScreenState = Omit<\n ScreenState,\n 'cssVars' | 'componentsConfig' | 'inputs'\n> & {\n error?: {\n text: ScreenState['errorText'];\n type: ScreenState['errorType'];\n };\n action?: string;\n inboundAppApproveScopes?: {\n desc: string;\n id: string;\n required: boolean;\n }[];\n};\n\nexport type DebugState = {\n isDebug: boolean;\n};\n\nexport interface ScriptElement extends HTMLDivElement {\n moduleRes?: ScriptModule;\n}\n\nexport type ScriptModule = {\n stop: () => void;\n start: () => void;\n /**\n * Refreshes any tokens or state that might be needed before form submission\n * Currently implemented for reCAPTCHA to ensure we have a fresh token\n */\n refresh?: () => Promise<void>;\n};\n\nexport type ClientScript = {\n id: string;\n initArgs: Record<string, any>;\n resultKey?: string;\n};\n\nexport type NextFn = KeepArgsByIndex<SdkFlowNext, [2, 5]>;\nexport type NextFnReturnPromiseValue = Awaited<ReturnType<NextFn>>;\n\nexport type DebuggerMessage = {\n title: string;\n description?: string;\n};\n\nexport type FlowStateUpdateFn = (state: FlowState) => void;\n\ntype Operator =\n | 'equal'\n | 'not-equal'\n | 'contains'\n | 'greater-than'\n | 'greater-than-or-equal'\n | 'less-than'\n | 'less-than-or-equal'\n | 'empty'\n | 'not-empty'\n | 'is-true'\n | 'is-false'\n | 'in'\n | 'not-in'\n | 'in-range'\n | 'not-in-range'\n | 'devised-by';\n\nexport interface ClientConditionResult {\n screenId: string;\n screenName: string;\n clientScripts?: ClientScript[];\n componentsConfig?: ComponentsConfig;\n interactionId: string;\n}\n\nexport interface ClientCondition {\n operator: Operator;\n key: string;\n predicate?: string | number;\n met: ClientConditionResult;\n unmet?: ClientConditionResult;\n}\n\nexport type AutoFocusOptions = true | false | 'skipFirstScreen';\n\nexport type ThemeOptions = 'light' | 'dark' | 'os';\n\nexport type Key =\n | 'lastAuth.loginId'\n | 'idpInitiated'\n | 'externalToken'\n | 'abTestingKey';\n\ntype CheckFunction = (ctx: Context, predicate?: string | number) => boolean;\n\nexport type ConditionsMap = {\n [key in Key]: {\n [operator in Operator]?: CheckFunction;\n };\n};\n\nexport interface Context {\n loginId?: string;\n code?: string;\n token?: string;\n abTestingKey?: number;\n lastAuth?: LastAuthState;\n}\n\nexport type DescopeUI = Record<string, () => Promise<void>> & {\n componentsThemeManager: Record<string, any>;\n};\n\ntype Font = {\n family: string[];\n label: string;\n url?: string;\n};\n\ntype ThemeTemplate = {\n fonts: {\n font1: Font;\n font2: Font;\n };\n};\n\nexport type FlowConfig = {\n startScreenId?: string;\n startScreenName?: string;\n version: number;\n targetLocales?: string[];\n conditions?: ClientCondition[];\n condition?: ClientCondition;\n fingerprintEnabled?: boolean;\n fingerprintKey?: string;\n sdkScripts?: [\n {\n id: string;\n initArgs: Record<string, any>;\n resultKey?: string;\n },\n ];\n clientScripts?: ClientScript[];\n componentsConfig?: ComponentsConfig;\n};\n\nexport interface ProjectConfiguration {\n componentsVersion: string;\n cssTemplate: {\n dark: ThemeTemplate;\n light: ThemeTemplate;\n };\n flows: {\n [key: string]: FlowConfig; // dynamic key names for flows\n };\n}\n\nexport type FlowStatus = 'loading' | 'error' | 'success' | 'ready' | 'initial';\n"],"names":["Direction"],"mappings":"aAmCA,IAAYA,EAAAA,QAGXA,eAAA,GAHWA,EAAAA,QAASA,YAATA,kBAGX,CAAA,IAFC,SAAA,WACAA,EAAA,QAAA"}
|
|
@@ -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 u from"@descope/web-js-sdk";import{ELEMENTS_TO_IGNORE_ENTER_KEY_ON as a}from"../constants/index.js";import{handleUrlParams as l,clearRunIdsFromUrl as d,camelCase as c,getRunIdsFromUrl as h,getContentUrl as f,fetchContent as g}from"../helpers/helpers.js";import p from"../helpers/state.js";import"@descope/escape-markdown";import"../helpers/webauthn.js";import{transformFlowInputFormData as m,extractNestedAttribute as b}from"../helpers/flowInputs.js";import{formMountMixin as v}from"../mixins/formMountMixin.js";import{CONFIG_FILENAME as w,PREV_VER_ASSETS_FOLDER as k}from"../constants/content.js";import{FETCH_EXCEPTION_ERROR_CODE as C}from"../constants/general.js";var A,x,y,j,I,E,L,U,M,S,O,W,D,P,N,F,R,T,B,V,q,H;const J=r(s,o,v,n)(HTMLElement);class K extends J{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(),A.add(this),y.set(this,!1),this.flowStatus="initial",this.loggerWrapper={error:(e,i="")=>{this.logger.error(e,i,new Error),t(this,A,"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)}},j.set(this,new p),I.set(this,new p),E.set(this,{}),this.getComponentsContext=()=>t(this,E,"f"),this.nextRequestStatus=new p({isLoading:!1}),L.set(this,void 0),U.set(this,{popstate:t(this,A,"m",D).bind(this),componentsContext:t(this,A,"m",T).bind(this)}),M.set(this,void 0),this.getConfig=()=>e(this,void 0,void 0,(function*(){return(yield this.config)||{isMissingConfig:!0}})),i(this,M,r,"f"),t(this,A,"m",O).call(this)}get flowId(){return this.getAttribute("flow-id")}get client(){try{return JSON.parse(this.getAttribute("client"))||{}}catch(t){return{}}}get tenantId(){return this.getAttribute("tenant")||void 0}get redirectUrl(){return this.getAttribute("redirect-url")||void 0}get debug(){return"true"===this.getAttribute("debug")}get locale(){return this.getAttribute("locale")||void 0}get autoFocus(){var t;const e=null!==(t=this.getAttribute("auto-focus"))&&void 0!==t?t:"true";return"skipFirstScreen"===e?e:"true"===e}get validateOnBlur(){return"true"===this.getAttribute("validate-on-blur")}get storeLastAuthenticatedUser(){var t;return"true"===(null!==(t=this.getAttribute("store-last-authenticated-user"))&&void 0!==t?t:"true")}get refreshCookieName(){return this.getAttribute("refresh-cookie-name")||""}get keepLastAuthenticatedUserAfterLogout(){return"true"===this.getAttribute("keep-last-authenticated-user-after-logout")}get storagePrefix(){return this.getAttribute("storage-prefix")||""}get preview(){return!!this.getAttribute("preview")}get formConfig(){return m(this.form)}get form(){return this.getAttribute("form")}get formConfigValues(){return b(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 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()))}))}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,I,"f").subscribe(t(this,A,"m",V).bind(this)),t(this,I,"f").update({isDebug:this.debug}),t(this,A,"m",W).call(this),yield t(this,A,"m",F).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");t(this,A,"m",H).call(this);const{executionId:s,stepId:n,token:u,code:a,isPopup:d,exchangeError:c,redirectAuthCallbackUrl:h,redirectAuthBackupCallbackUri:f,redirectAuthCodeChallenge:g,redirectAuthInitiator:p,ssoQueryParams:m}=l(this.flowId,this.loggerWrapper);window.addEventListener("popstate",t(this,U,"f").popstate),window.addEventListener("components-context",t(this,U,"f").componentsContext),t(this,j,"f").subscribe(t(this,A,"m",N).bind(this)),t(this,j,"f").update(Object.assign({projectId:this.projectId,flowId:this.flowId,baseUrl:this.baseUrl,tenant:this.tenantId,redirectUrl:this.redirectUrl,locale:this.locale,stepId:n,executionId:s,token:u,code:a,isPopup:d,exchangeError:c,redirectAuthCallbackUrl:h,redirectAuthBackupCallbackUri:f,redirectAuthCodeChallenge:g,redirectAuthInitiator:p},m)),i(this,y,!0,"f")}))}disconnectedCallback(){t(this,j,"f").unsubscribeAll(),t(this,I,"f").unsubscribeAll(),t(this,A,"m",B).call(this),window.removeEventListener("popstate",t(this,U,"f").popstate),window.removeEventListener("components-context",t(this,U,"f").componentsContext)}attributeChangedCallback(e,i,r){if(this.shadowRoot.isConnected&&t(this,y,"f")&&i!==r&&x.observedAttributes.includes(e)){t(this,A,"m",W).call(this);const o=null===i;t(this,j,"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,I,"f").update({isDebug:this.debug})}}}x=K,y=new WeakMap,j=new WeakMap,I=new WeakMap,E=new WeakMap,L=new WeakMap,U=new WeakMap,M=new WeakMap,A=new WeakSet,S=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 ")},O=function(){t(this,A,"m",S).call(this),this.slotElement=document.createElement("slot"),this.slotElement.classList.add("hidden"),this.rootElement.appendChild(this.slotElement)},W=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"];x.observedAttributes.forEach((e=>{if(!t.includes(e)&&!this[c(e)])throw Error(`${e} cannot be empty`)}))},D=function(){const{stepId:e,executionId:i}=h(this.flowId);t(this,j,"f").update({stepId:e,executionId:i})},P=function(t,i){this.sdk=u(Object.assign(Object.assign({persistTokens:!0,preview:this.preview,storagePrefix:this.storagePrefix,storeLastAuthenticatedUser:this.storeLastAuthenticatedUser,keepLastAuthenticatedUserAfterLogout:this.keepLastAuthenticatedUserAfterLogout,refreshCookieName:this.refreshCookieName},x.sdkConfigOverrides),{projectId:t,baseUrl:i})),["start","next"].forEach((t=>{const i=this.sdk.flow[t];this.sdk.flow[t]=(...t)=>e(this,void 0,void 0,(function*(){try{return yield i(...t)}catch(t){return{error:{errorCode:C,errorDescription:t.toString()}}}}))}))},N=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,A,"m",P).call(this,e,r)}t(this,M,"f").call(this,i)}))},F=function(){return e(this,void 0,void 0,(function*(){const e=yield this.getConfig();return"isMissingConfig"in e&&e.isMissingConfig&&(yield t(this,A,"m",R).call(this))}))},R=function(){return e(this,void 0,void 0,(function*(){const t=f({projectId:this.projectId,filename:w,assetsFolder:k,baseUrl:this.baseStaticUrl});try{return yield g(t,"json"),!0}catch(t){return!1}}))},T=function(e){i(this,E,Object.assign(Object.assign({},t(this,E,"f")),e.detail),"f")},B=function(){var e;null===(e=t(this,L,"f"))||void 0===e||e.remove(),i(this,L,null,"f")},V=function(r){return e(this,arguments,void 0,(function*({isDebug:e}){e?(i(this,L,document.createElement("descope-debugger"),"f"),Object.assign(t(this,L,"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,L,"f"))):t(this,A,"m",B).call(this)}))},q=function(e,i){var r;e&&this.debug&&(null===(r=t(this,L,"f"))||void 0===r||r.updateData({title:e,description:i}))},H=function(){this.rootElement.onkeydown=t=>{var e,i,r;const o=!!(null===(e=this.shadowRoot.activeElement)||void 0===e?void 0:e.getAttribute("href")),s=a.includes(null!==(r=null===(i=this.shadowRoot.activeElement)||void 0===i?void 0:i.localName)&&void 0!==r?r:"");if("Enter"!==t.key||o||s)return;t.preventDefault();const n=this.rootElement.querySelectorAll("descope-button");if(1===n.length&&"false"!==n[0].getAttribute("auto-submit"))return void n[0].click();const u=Array.from(n).filter((t=>"true"===t.getAttribute("auto-submit")));if(1===u.length)return void u[0].click();const l=Array.from(n).filter((t=>"button"===t.getAttribute("data-type")));if(1===l.length)"false"!==l[0].getAttribute("auto-submit")&&l[0].click();else if(0===l.length){const t=Array.from(n).filter((t=>"sso"===t.getAttribute("data-type")));1===t.length&&"false"!==t[0].getAttribute("auto-submit")&&t[0].click()}}},K.sdkConfigOverrides={baseHeaders:{"x-descope-sdk-name":"web-component","x-descope-sdk-version":"3.46.3"}};export{K 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 u from"@descope/web-js-sdk";import{ELEMENTS_TO_IGNORE_ENTER_KEY_ON as a}from"../constants/index.js";import{handleUrlParams as l,clearRunIdsFromUrl as d,camelCase as c,getRunIdsFromUrl as h,getContentUrl as f,fetchContent as g}from"../helpers/helpers.js";import p from"../helpers/state.js";import"@descope/escape-markdown";import"../helpers/webauthn.js";import{transformFlowInputFormData as m,extractNestedAttribute as b}from"../helpers/flowInputs.js";import{formMountMixin as v}from"../mixins/formMountMixin.js";import{CONFIG_FILENAME as w,PREV_VER_ASSETS_FOLDER as k}from"../constants/content.js";import{FETCH_EXCEPTION_ERROR_CODE as C}from"../constants/general.js";var A,x,y,j,I,E,L,U,M,S,O,W,D,P,N,F,R,T,B,V,q,H;const J=r(s,o,v,n)(HTMLElement);class K extends J{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(),A.add(this),y.set(this,!1),this.flowStatus="initial",this.loggerWrapper={error:(e,i="")=>{this.logger.error(e,i,new Error),t(this,A,"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)}},j.set(this,new p),I.set(this,new p),E.set(this,{}),this.getComponentsContext=()=>t(this,E,"f"),this.nextRequestStatus=new p({isLoading:!1}),L.set(this,void 0),U.set(this,{popstate:t(this,A,"m",D).bind(this),componentsContext:t(this,A,"m",T).bind(this)}),M.set(this,void 0),this.getConfig=()=>e(this,void 0,void 0,(function*(){return(yield this.config)||{isMissingConfig:!0}})),i(this,M,r,"f"),t(this,A,"m",O).call(this)}get flowId(){return this.getAttribute("flow-id")}get client(){try{return JSON.parse(this.getAttribute("client"))||{}}catch(t){return{}}}get tenantId(){return this.getAttribute("tenant")||void 0}get redirectUrl(){return this.getAttribute("redirect-url")||void 0}get debug(){return"true"===this.getAttribute("debug")}get locale(){return this.getAttribute("locale")||void 0}get autoFocus(){var t;const e=null!==(t=this.getAttribute("auto-focus"))&&void 0!==t?t:"true";return"skipFirstScreen"===e?e:"true"===e}get validateOnBlur(){return"true"===this.getAttribute("validate-on-blur")}get storeLastAuthenticatedUser(){var t;return"true"===(null!==(t=this.getAttribute("store-last-authenticated-user"))&&void 0!==t?t:"true")}get refreshCookieName(){return this.getAttribute("refresh-cookie-name")||""}get keepLastAuthenticatedUserAfterLogout(){return"true"===this.getAttribute("keep-last-authenticated-user-after-logout")}get storagePrefix(){return this.getAttribute("storage-prefix")||""}get preview(){return!!this.getAttribute("preview")}get formConfig(){return m(this.form)}get form(){return this.getAttribute("form")}get formConfigValues(){return b(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 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()))}))}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,I,"f").subscribe(t(this,A,"m",V).bind(this)),t(this,I,"f").update({isDebug:this.debug}),t(this,A,"m",W).call(this),yield t(this,A,"m",F).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");t(this,A,"m",H).call(this);const{executionId:s,stepId:n,token:u,code:a,isPopup:d,exchangeError:c,redirectAuthCallbackUrl:h,redirectAuthBackupCallbackUri:f,redirectAuthCodeChallenge:g,redirectAuthInitiator:p,ssoQueryParams:m}=l(this.flowId,this.loggerWrapper);window.addEventListener("popstate",t(this,U,"f").popstate),window.addEventListener("components-context",t(this,U,"f").componentsContext),t(this,j,"f").subscribe(t(this,A,"m",N).bind(this)),t(this,j,"f").update(Object.assign({projectId:this.projectId,flowId:this.flowId,baseUrl:this.baseUrl,tenant:this.tenantId,redirectUrl:this.redirectUrl,locale:this.locale,stepId:n,executionId:s,token:u,code:a,isPopup:d,exchangeError:c,redirectAuthCallbackUrl:h,redirectAuthBackupCallbackUri:f,redirectAuthCodeChallenge:g,redirectAuthInitiator:p},m)),i(this,y,!0,"f")}))}disconnectedCallback(){t(this,j,"f").unsubscribeAll(),t(this,I,"f").unsubscribeAll(),t(this,A,"m",B).call(this),window.removeEventListener("popstate",t(this,U,"f").popstate),window.removeEventListener("components-context",t(this,U,"f").componentsContext)}attributeChangedCallback(e,i,r){if(this.shadowRoot.isConnected&&t(this,y,"f")&&i!==r&&x.observedAttributes.includes(e)){t(this,A,"m",W).call(this);const o=null===i;t(this,j,"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,I,"f").update({isDebug:this.debug})}}}x=K,y=new WeakMap,j=new WeakMap,I=new WeakMap,E=new WeakMap,L=new WeakMap,U=new WeakMap,M=new WeakMap,A=new WeakSet,S=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 ")},O=function(){t(this,A,"m",S).call(this),this.slotElement=document.createElement("slot"),this.slotElement.classList.add("hidden"),this.rootElement.appendChild(this.slotElement)},W=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"];x.observedAttributes.forEach((e=>{if(!t.includes(e)&&!this[c(e)])throw Error(`${e} cannot be empty`)}))},D=function(){const{stepId:e,executionId:i}=h(this.flowId);t(this,j,"f").update({stepId:e,executionId:i})},P=function(t,i){this.sdk=u(Object.assign(Object.assign({persistTokens:!0,preview:this.preview,storagePrefix:this.storagePrefix,storeLastAuthenticatedUser:this.storeLastAuthenticatedUser,keepLastAuthenticatedUserAfterLogout:this.keepLastAuthenticatedUserAfterLogout,refreshCookieName:this.refreshCookieName},x.sdkConfigOverrides),{projectId:t,baseUrl:i})),["start","next"].forEach((t=>{const i=this.sdk.flow[t];this.sdk.flow[t]=(...t)=>e(this,void 0,void 0,(function*(){try{return yield i(...t)}catch(t){return{error:{errorCode:C,errorDescription:t.toString()}}}}))}))},N=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,A,"m",P).call(this,e,r)}t(this,M,"f").call(this,i)}))},F=function(){return e(this,void 0,void 0,(function*(){const e=yield this.getConfig();return"isMissingConfig"in e&&e.isMissingConfig&&(yield t(this,A,"m",R).call(this))}))},R=function(){return e(this,void 0,void 0,(function*(){const t=f({projectId:this.projectId,filename:w,assetsFolder:k,baseUrl:this.baseStaticUrl});try{return yield g(t,"json"),!0}catch(t){return!1}}))},T=function(e){i(this,E,Object.assign(Object.assign({},t(this,E,"f")),e.detail),"f")},B=function(){var e;null===(e=t(this,L,"f"))||void 0===e||e.remove(),i(this,L,null,"f")},V=function(r){return e(this,arguments,void 0,(function*({isDebug:e}){e?(i(this,L,document.createElement("descope-debugger"),"f"),Object.assign(t(this,L,"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,L,"f"))):t(this,A,"m",B).call(this)}))},q=function(e,i){var r;e&&this.debug&&(null===(r=t(this,L,"f"))||void 0===r||r.updateData({title:e,description:i}))},H=function(){this.rootElement.onkeydown=t=>{var e,i,r;const o=!!(null===(e=this.shadowRoot.activeElement)||void 0===e?void 0:e.getAttribute("href")),s=a.includes(null!==(r=null===(i=this.shadowRoot.activeElement)||void 0===i?void 0:i.localName)&&void 0!==r?r:"");if("Enter"!==t.key||o||s)return;t.preventDefault();const n=this.rootElement.querySelectorAll("descope-button");if(1===n.length&&"false"!==n[0].getAttribute("auto-submit"))return void n[0].click();const u=Array.from(n).filter((t=>"true"===t.getAttribute("auto-submit")));if(1===u.length)return void u[0].click();const l=Array.from(n).filter((t=>"button"===t.getAttribute("data-type")));if(1===l.length)"false"!==l[0].getAttribute("auto-submit")&&l[0].click();else if(0===l.length){const t=Array.from(n).filter((t=>"sso"===t.getAttribute("data-type")));1===t.length&&"false"!==t[0].getAttribute("auto-submit")&&t[0].click()}}},K.sdkConfigOverrides={baseHeaders:{"x-descope-sdk-name":"web-component","x-descope-sdk-version":"3.47.0"}};export{K as default};
|
|
2
2
|
//# sourceMappingURL=BaseDescopeWc.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{__classPrivateFieldGet as e,__classPrivateFieldSet as t,__awaiter as i,__rest as s}from"tslib";import{ensureFingerprintIds as o,clearFingerprintData as n}from"@descope/web-js-sdk";import{RESPONSE_ACTIONS as r,CUSTOM_INTERACTIONS as a,URL_CODE_PARAM_NAME as l,URL_TOKEN_PARAM_NAME as d,URL_RUN_IDS_PARAM_NAME as c,SDK_SCRIPTS_LOAD_TIMEOUT as h,DESCOPE_ATTRIBUTE_EXCLUDE_FIELD as p,ELEMENT_TYPE_ATTRIBUTE as u,DESCOPE_ATTRIBUTE_EXCLUDE_NEXT_BUTTON as g}from"../constants/index.js";import{timeoutPromise as v,withMemCache as m,leadingDebounce as f,getUserLocale as b,showFirstScreenOnExecutionInit as w,injectSamlIdpForm as S,openCenteredPopup as y,getAnimationDirection as I,handleAutoFocus as C,transformStepStateForCustomScreen as k,getElementDescopeAttributes as R,getScriptResultPath as W,submitForm as O,transformScreenInputs as E,handleReportValidityOnBlur as x,getFirstNonEmptyValue as A,clearPreviousExternalInputs as j}from"../helpers/helpers.js";import T from"../helpers/state.js";import{disableWebauthnButtons as L,updateTemplateFromScreenState as U,setPhoneAutoDetectDefaultCode as P,setTOTPVariable as N,setNOTPVariable as $,setCssVars as q,updateScreenFromScreenState as M,replaceElementMessage as F}from"../helpers/templates.js";import{isConditionalLoginSupported as V}from"../helpers/webauthn.js";import{getABTestingKey as D}from"../helpers/abTestingKey.js";import{calculateConditions as B,calculateCondition as K}from"../helpers/conditions.js";import{setLastAuth as H,getLastAuth as J}from"../helpers/lastAuth.js";import _ from"./BaseDescopeWc.js";import{FETCH_EXCEPTION_ERROR_CODE as G,FETCH_ERROR_RESPONSE_ERROR_CODE as z,FLOW_REQUESTED_IS_IN_OLD_VERSION_ERROR_CODE as Q,FLOW_TIMED_OUT_ERROR_CODE as X,POLLING_STATUS_NOT_FOUND_ERROR_CODE as Y}from"../constants/general.js";var Z,ee,te,ie,se,oe,ne,re,ae,le,de,ce,he,pe,ue,ge,ve,me,fe,be,we,Se,ye,Ie,Ce,ke,Re,We,Oe,Ee,xe,Ae,je,Te,Le;class Ue extends _{static set sdkConfigOverrides(e){_.sdkConfigOverrides=e}static get sdkConfigOverrides(){return _.sdkConfigOverrides}constructor(){const s=new T({deferredRedirect:!1});super(s.update.bind(s)),Z.add(this),this.stepState=new T({}),ee.set(this,void 0),te.set(this,null),ie.set(this,null),se.set(this,{visibilitychange:e(this,Z,"m",oe).bind(this)}),this.bridgeVersion=2,this.nativeCallbacks={},pe.set(this,!1),this.handleRedirect=e=>{window.location.assign(e)},ge.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,Z,"m",ve).call(this,i):i()})),me.set(this,((s,o,n,l,d=!1)=>{const c=[X,Y];if(this.flowState.current.action===r.poll){this.logger.debug("polling - Scheduling polling request");const r=Date.now(),h=d?500:2e3;t(this,ee,setTimeout((()=>i(this,void 0,void 0,(function*(){var t,i;this.logger.debug("polling - Calling next");const p=this.sdk.flow.next(s,o,a.polling,n,l,{}),u=document.hidden&&!d&&Date.now()-r>h+500;let g;u&&this.logger.debug("polling - The polling seems to be throttled");try{const e=u?1e3:6e3;g=yield v(e,p)}catch(t){return this.logger.warn(`polling - The ${u?"throttled fetch":"fetch"} call timed out or was aborted`),void e(this,me,"f").call(this,s,o,n,l,u)}if((null===(t=null==g?void 0:g.error)||void 0===t?void 0:t.errorCode)===G)return this.logger.debug("polling - Got a generic error due to exception in fetch call"),void e(this,me,"f").call(this,s,o,n,l);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,me,"f").call(this,s,o,n,l),e(this,be,"f").call(this,g)}))),h),"f")}})),fe.set(this,(()=>{clearTimeout(e(this,ee,"f")),t(this,ee,null,"f")})),be.set(this,(i=>{var s,o,n,a,l,d,c,h,p,u,g,v,m;if(!(null==i?void 0:i.ok)){const t=null===(s=null==i?void 0:i.response)||void 0===s?void 0:s.url,r=`${null===(o=null==i?void 0:i.response)||void 0===o?void 0:o.status} - ${null===(n=null==i?void 0:i.response)||void 0===n?void 0:n.statusText}`;e(this,Z,"m",Le).call(this,"error",(null==i?void 0:i.error)||{errorCode:z,errorDescription:r,errorMessage:t}),this.loggerWrapper.error((null===(a=null==i?void 0:i.error)||void 0===a?void 0:a.errorDescription)||t,(null===(l=null==i?void 0:i.error)||void 0===l?void 0:l.errorMessage)||r);const c=null===(d=null==i?void 0:i.error)||void 0===d?void 0:d.errorCode;return void(c!==Q&&c!==X||!this.isRestartOnError||e(this,Z,"m",he).call(this))}null===(h=null===(c=i.data)||void 0===c?void 0:c.runnerLogs)||void 0===h||h.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===(p=i.data)||void 0===p?void 0:p.screen)||void 0===u?void 0:u.state)||void 0===g?void 0:g.errorText;(null===(v=i.data)||void 0===v?void 0:v.error)?this.loggerWrapper.error(`[${i.data.error.code}]: ${i.data.error.description}`,`${f?`${f} - `:""}${i.data.error.message}`):f&&this.loggerWrapper.error(f);const{status:b,authInfo:w,lastAuth:S,action:y,openInNewTabUrl:I}=i.data;if(y!==r.poll&&e(this,fe,"f").call(this),"completed"===b)return this.storeLastAuthenticatedUser&&H(S),void e(this,Z,"m",Le).call(this,"success",w);I&&window.open(I,"_blank");const{executionId:C,stepId:k,stepName:R,screen:W,redirect:O,webauthn:E,error:x,samlIdpResponse:A,nativeResponse:j}=i.data,T=Date.now();y!==r.poll?(this.loggerWrapper.info(`Step "${R||`#${k}`}" is ${b}`,"",{screen:W,status:b,stepId:k,stepName:R,action:y,error:x}),(null===(m=W.state)||void 0===m?void 0:m.clientScripts)&&t(this,ie,this.loadSdkScripts(W.state.clientScripts),"f"),this.flowState.update({stepId:k,stepName:R,executionId:C,action:y,redirectTo:null==O?void 0:O.url,redirectIsPopup:null==O?void 0:O.isPopup,screenId:null==W?void 0:W.id,screenState:null==W?void 0:W.state,webauthnTransactionId:null==E?void 0:E.transactionId,webauthnOptions:null==E?void 0:E.options,samlIdpResponseUrl:null==A?void 0:A.url,samlIdpResponseSamlResponse:null==A?void 0:A.samlResponse,samlIdpResponseRelayState:null==A?void 0:A.relayState,nativeResponseType:null==j?void 0:j.type,nativePayload:null==j?void 0:j.payload,reqTimestamp:T})):this.flowState.update({action:y,reqTimestamp:T})})),we.set(this,m((()=>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)}}))))),Re.set(this,null),Ae.set(this,f(((t,s)=>i(this,void 0,void 0,(function*(){var i;if("true"===t.getAttribute("formnovalidate")||e(this,Z,"m",Ce).call(this)){const o=null==t?void 0:t.getAttribute("id");e(this,Z,"m",We).call(this,t);const n=yield e(this,Z,"m",ke).call(this),r=R(t);if(this.nextRequestStatus.update({isLoading:!0}),e(this,ie,"f")){this.loggerWrapper.debug("Waiting for sdk scripts to load");const t=Date.now();yield e(this,ie,"f"),this.loggerWrapper.debug("Sdk scripts loaded for",(Date.now()-t).toString())}const a=this.loadSdkScriptsModules();if(a.length>0){const e=a.filter((e=>"function"==typeof e.refresh)).map((e=>e.refresh()));e.length>0&&(yield v(h,Promise.all(e),null))}const l=this.getComponentsContext(),d=Object.assign(Object.assign(Object.assign(Object.assign({},l),r),n),{origin:(null===(i=this.nativeOptions)||void 0===i?void 0:i.origin)||window.location.origin});yield s(o,d),this.nextRequestStatus.update({isLoading:!1}),e(this,Z,"m",Oe).call(this,n)}}))))),this.flowState=s}nativeResume(t,i){var s,o,n,r,a;const h=JSON.parse(i);if("oauthWeb"===t||"sso"===t){let{exchangeCode:e}=h;if(!e){e=null===(s=new URL(h.url).searchParams)||void 0===s?void 0:s.get(l)}null===(n=(o=this.nativeCallbacks).complete)||void 0===n||n.call(o,{exchangeCode:e,idpInitiated:!0})}else if("magicLink"===t){const t=new URL(h.url),i=t.searchParams.get(d),s=t.searchParams.get(c).split("_").pop();e(this,fe,"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}=h;t||(this.nativeCallbacks.screenNext=null),null==e||e(t)}else if("resumeScreen"===t){const{interactionId:e,form:t}=h,{screenNext:i}=this.nativeCallbacks;this.nativeCallbacks.screenNext=null,null==i||i(e,t)}else null===(a=(r=this.nativeCallbacks).complete)||void 0===a||a.call(r,h)}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:{[W(e.id,e.resultKey)]:i},bubbles:!0,composed:!0})),t(e.id)};this.loggerWrapper.debug(`Preparing to load scripts: ${e.map((e=>e.id)).join(", ")}`);const s=Promise.all(null==e?void 0:e.map((e=>i(this,void 0,void 0,(function*(){var i,s;const o=this.shadowRoot.querySelector(`[data-script-id="${e.id}"]`);if(o){this.loggerWrapper.debug("Script already loaded",e.id);const{moduleRes:t}=o;return null===(i=null==t?void 0:t.start)||void 0===i||i.call(t),t}yield this.injectNpmLib("@descope/flow-scripts","1.0.11",`dist/${e.id}.js`);const n=null===(s=globalThis.descope)||void 0===s?void 0:s[e.id];return new Promise(((i,s)=>{try{const s=n(e.initArgs,{baseUrl:this.baseUrl,ref:this},t(e,i));if(s){const t=document.createElement("div");t.setAttribute("data-script-id",e.id),t.moduleRes=s,this.shadowRoot.appendChild(t),this.nextRequestStatus.subscribe((()=>{var t;this.loggerWrapper.debug("Unloading script",e.id),null===(t=s.stop)||void 0===t||t.call(s)}))}}catch(e){s(e)}}))}))))),o=new Promise((e=>{setTimeout((()=>{this.loggerWrapper.warn("SDK scripts loading timeout"),e(!0)}),h)}));return Promise.race([s,o])}get isDismissScreenErrorOnInput(){return"true"===this.getAttribute("dismiss-screen-error-on-input")}init(){if(!window.descopeBridge)return this._init();this.lazyInit=this._init}_init(){const t=Object.create(null,{init:{get:()=>super.init}});return i(this,void 0,void 0,(function*(){var i,s;this.shadowRoot.isConnected&&(null===(i=this.flowState)||void 0===i||i.subscribe(this.onFlowChange.bind(this)),e(this,Z,"m",de).call(this),window.addEventListener("visibilitychange",e(this,se,"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(),null===(i=e(this,te,"f"))||void 0===i||i.abort(),t(this,te,null,"f"),window.removeEventListener("visibilitychange",e(this,se,"f").visibilitychange)}getHtmlFilenameWithLocale(e,t){return i(this,void 0,void 0,(function*(){let i;const s=b(e),o=yield this.getTargetLocales();return o.includes(s.locale)?i=`${t}-${s.locale}.html`:o.includes(s.fallback)&&(i=`${t}-${s.fallback}.html`),i}))}getPageContent(e,t){return i(this,void 0,void 0,(function*(){if(t)try{const{body:e}=yield this.fetchStaticResource(t,"text");return e}catch(i){this.loggerWrapper.error(`Failed to fetch flow page from ${t}. Fallback to url ${e}`,i)}try{const{body:t}=yield this.fetchStaticResource(e,"text");return t}catch(e){this.loggerWrapper.error("Failed to fetch flow page",e.message)}return null}))}onFlowChange(l,d,c){return i(this,void 0,void 0,(function*(){var h,p;const{projectId:u,flowId:g,tenant:v,stepId:m,executionId:f,action:C,screenId:k,screenState:R,redirectTo:W,redirectIsPopup:x,redirectUrl:A,token:j,code:T,isPopup:L,exchangeError:U,webauthnTransactionId:P,webauthnOptions:N,redirectAuthCodeChallenge:$,redirectAuthCallbackUrl:q,redirectAuthBackupCallbackUri:M,redirectAuthInitiator:F,locale:V,samlIdpResponseUrl:H,samlIdpResponseSamlResponse:_,samlIdpResponseRelayState:G,nativeResponseType:z,nativePayload:Q,reqTimestamp:X}=l,Y=s(l,["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","nativeResponseType","nativePayload","reqTimestamp"]);let ee,se,oe;const ne=D(),{outboundAppId:re}=this,{outboundAppScopes:le}=this,de=this.sdk.getLastUserLoginId(),ce=yield this.getFlowConfig(),he=yield this.getProjectConfig(),pe=Object.entries(he.flows||{}).reduce(((e,[t,i])=>(e[t]=i.version,e)),{}),ge=q&&$?{callbackUrl:q,codeChallenge:$,backupCallbackUri:M}:void 0,ve=this.nativeOptions?{platform:this.nativeOptions.platform,bridgeVersion:this.nativeOptions.bridgeVersion,oauthProvider:this.nativeOptions.oauthProvider,oauthRedirect:this.nativeOptions.oauthRedirect,magicLinkRedirect:this.nativeOptions.magicLinkRedirect,ssoRedirect:this.nativeOptions.ssoRedirect}:void 0;let fe={};if(!f){const i=[...ce.clientScripts||[],...ce.sdkScripts||[]];if(ce.conditions){let e=[];({startScreenId:ee,conditionInteractionId:oe,startScreenName:se,clientScripts:e,componentsConfig:fe}=B({loginId:de,code:T,token:j,abTestingKey:ne},ce.conditions)),i.push(...e||[])}else ce.condition?({startScreenId:ee,conditionInteractionId:oe}=K(ce.condition,{loginId:de,code:T,token:j,abTestingKey:ne})):(se=ce.startScreenName,ee=ce.startScreenId);if(t(this,ie,this.loadSdkScripts(i),"f"),ce.fingerprintEnabled&&ce.fingerprintKey?yield o(ce.fingerprintKey,this.baseUrl):n(),!w(ee,Y)){const t=yield this.sdk.flow.start(g,Object.assign(Object.assign(Object.assign(Object.assign({tenant:v,redirectAuth:ge},Y),{client:this.client}),A&&{redirectUrl:A}),{lastAuth:J(de),abTestingKey:ne,locale:b(V).locale,nativeOptions:ve,outboundAppId:re,outboundAppScopes:le}),oe,"",he.componentsVersion,pe,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),T?{exchangeCode:T,idpInitiated:!0}:{}),Y.descopeIdpInitiated&&{idpInitiated:!0}),j?{token:j}:{}),Y.oidcLoginHint?{externalId:Y.oidcLoginHint}:{}));return e(this,be,"f").call(this,t),void("completed"!==(null===(h=null==t?void 0:t.data)||void 0===h?void 0:h.status)&&this.flowState.update({code:void 0,token:void 0}))}}if(this.loggerWrapper.debug("Before popup postmessage send",JSON.stringify({isPopup:L,code:T,exchangeError:U,isCodeChanged:c("code"),isExchangeErrorChanged:c("exchangeError")})),L&&(c("code")&&T||c("exchangeError")&&U)){this.loggerWrapper.debug("Creating popup channel",f);const e=new BroadcastChannel(f);return this.loggerWrapper.debug("Posting message to popup channel",JSON.stringify({code:T,exchangeError:U})),e.postMessage({data:{code:T,exchangeError:U},action:"code"}),this.loggerWrapper.debug("Popup channel message posted, closing channel"),e.close(),this.loggerWrapper.debug("Popup channel closed, closing window"),void window.close()}if(f&&(c("token")&&j||c("code")&&T||c("exchangeError")&&U)){const t=yield this.sdk.flow.next(f,m,a.submit,ce.version,he.componentsVersion,{token:j,exchangeCode:T,exchangeError:U});return e(this,be,"f").call(this,t),void this.flowState.update({token:void 0,code:void 0,exchangeError:void 0})}if(C===r.loadForm&&["samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState"].some((e=>c(e)))){if(!H||!_)return void this.loggerWrapper.error("Did not get saml idp params data to load");S(H,_,G||"",O)}if(C===r.redirect&&(c("redirectTo")||c("deferredRedirect"))){if(!W)return void this.loggerWrapper.error("Did not get redirect url");if("android"===F&&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=y(W,"?",598,700);this.loggerWrapper.debug("Creating broadcast channel");const i=new BroadcastChannel(f);this.loggerWrapper.debug("Starting popup closed detection");const s=setInterval((()=>{t.closed&&(this.loggerWrapper.debug("Popup closed, dispatching popupclosed event and clearing interval"),clearInterval(s),e(this,Z,"m",Le).call(this,"popupclosed",{}),this.loggerWrapper.debug("Closing channel"),i.close())}),1e3);this.loggerWrapper.debug("Listening for postMessage on channel");const o=e=>{if(this.loggerWrapper.debug("Received postMessage on channel",JSON.stringify(e)),this.loggerWrapper.debug("Comparing origins",JSON.stringify({eventOrigin:e.origin,windowLocationOrigin:window.location.origin})),e.origin!==window.location.origin)return;this.loggerWrapper.debug("PostMessage origin matches, processing message");const{action:t,data:i}=e.data;this.loggerWrapper.debug(`PostMessage action: ${t}, data: ${JSON.stringify(i)}`),"code"===t&&(this.loggerWrapper.debug("Updating flow state with code and exchangeError"),this.flowState.update({code:i.code,exchangeError:i.exchangeError}))};i.onmessage=o}else this.handleRedirect(W);return}if(C===r.webauthnCreate||C===r.webauthnGet){if(!P||!N)return void this.loggerWrapper.error("Did not get webauthn transaction id or options");let i,s;null===(p=e(this,te,"f"))||void 0===p||p.abort(),t(this,te,null,"f");try{i=C===r.webauthnCreate?yield this.sdk.webauthn.helpers.create(N):yield this.sdk.webauthn.helpers.get(N)}catch(e){"InvalidStateError"===e.name?this.loggerWrapper.warn("WebAuthn operation failed",e.message):"NotAllowedError"!==e.name&&this.loggerWrapper.error(e.message),s=e.name}const o=yield this.sdk.flow.next(f,m,a.submit,ce.version,he.componentsVersion,{transactionId:P,response:i,failure:s});e(this,be,"f").call(this,o)}if(C===r.nativeBridge)return this.nativeCallbacks.complete=t=>i(this,void 0,void 0,(function*(){const i=yield this.sdk.flow.next(f,m,a.submit,ce.version,he.componentsVersion,t);e(this,be,"f").call(this,i)})),void e(this,Z,"m",ae).call(this,z,Q);if(c("action")&&e(this,me,"f").call(this,f,m,ce.version,he.componentsVersion),!k&&!ee)return void this.loggerWrapper.warn("No screen was found to show");const we=ee||k,Se=yield this.getHtmlFilenameWithLocale(V,we),{oidcLoginHint:ye,oidcPrompt:Ie,oidcErrorRedirectUri:Ce,oidcResource:ke,samlIdpUsername:Re}=Y,We={direction:I(m,d.stepId),screenState:Object.assign(Object.assign({},R),{form:Object.assign(Object.assign({},this.formConfigValues),null==R?void 0:R.form),lastAuth:{loginId:de,name:this.sdk.getLastUserDisplayName()||de},componentsConfig:Object.assign(Object.assign(Object.assign({},ce.componentsConfig),fe),null==R?void 0:R.componentsConfig)}),htmlFilename:`${we}.html`,htmlLocaleFilename:Se,screenId:we,stepName:l.stepName||se,samlIdpUsername:Re,oidcLoginHint:ye,oidcPrompt:Ie,oidcErrorRedirectUri:Ce,oidcResource:ke,action:C},Oe=J(de);w(ee,Y)?We.next=(t,s)=>i(this,void 0,void 0,(function*(){const i=yield this.sdk.flow.start(g,Object.assign(Object.assign(Object.assign(Object.assign({tenant:v,redirectAuth:ge},Y),{lastAuth:Oe,preview:this.preview,abTestingKey:ne,client:this.client}),A&&{redirectUrl:A}),{locale:b(V).locale,nativeOptions:ve,outboundAppId:re,outboundAppScopes:le}),oe,t,he.componentsVersion,pe,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),E(s)),T&&{exchangeCode:T,idpInitiated:!0}),Y.descopeIdpInitiated&&{idpInitiated:!0}),j&&{token:j}));return e(this,be,"f").call(this,i),i})):(c("projectId")||c("baseUrl")||c("executionId")||c("stepId"))&&(We.next=(t,s)=>i(this,void 0,void 0,(function*(){const i=yield this.sdk.flow.next(f,m,t,ce.version,he.componentsVersion,E(s));return e(this,be,"f").call(this,i),i}))),this.loggerWrapper.debug("Got a screen with id",We.screenId),yield e(this,Z,"m",ue).call(this,We),this.stepState.update(We)}))}onStepChange(t,s){return i(this,void 0,void 0,(function*(){var o,n;const{htmlFilename:r,htmlLocaleFilename:l,direction:d,next:c,screenState:h}=t;this.loggerWrapper.debug("Rendering a flow screen");const p=document.createElement("template");p.innerHTML=yield this.getPageContent(r,l);const g=p.content.cloneNode(!0),v=this.loadDescopeUiComponents(p);this.sdk.webauthn.helpers.isSupported()?yield e(this,Z,"m",ye).call(this,g,c):L(g),!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),U(g,h,h.componentsConfig,this.formConfig,this.loggerWrapper);const{geo:m}=yield this.getExecutionContext();P(g,m);const f=()=>i(this,void 0,void 0,(function*(){var i,o;yield v;const n=this.contentRootElement;N(n,null===(i=null==h?void 0:h.totp)||void 0===i?void 0:i.image),$(n,null===(o=null==h?void 0:h.notp)||void 0===o?void 0:o.image),q(n,g,h.cssVars,this.loggerWrapper),n.replaceChildren(g);const r=!s.htmlFilename;setTimeout((()=>{e(this,Z,"m",Ee).call(this),this.validateOnBlur&&x(n),M(n,h),e(this,Z,"m",Ie).call(this,{isFirstScreen:r,isCustomScreen:!1,stepName:t.stepName}),C(n,this.autoFocus,r)})),e(this,Z,"m",Te).call(this,c);n.querySelector(`[${u}="polling"]`)&&c(a.polling,{})}));d?e(this,Z,"m",ve).call(this,f):f()}))}getInputs(){return Array.from(this.shadowRoot.querySelectorAll(`*:not(slot)[name]:not([${p}])`))}}ee=new WeakMap,te=new WeakMap,ie=new WeakMap,se=new WeakMap,pe=new WeakMap,ge=new WeakMap,me=new WeakMap,fe=new WeakMap,be=new WeakMap,we=new WeakMap,Re=new WeakMap,Ae=new WeakMap,Z=new WeakSet,oe=function(){document.hidden||setTimeout((()=>{this.flowState.update({deferredRedirect:!1})}),300)},ne=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,Z,"m",ae).call(this,"beforeScreen",{screen:t,context:s})}))}))},re=function(t){var i;(null===(i=this.nativeOptions)||void 0===i?void 0:i.bridgeVersion)>=2&&e(this,Z,"m",ae).call(this,"afterScreen",{screen:t})},ae=function(t,i){e(this,Z,"m",Le).call(this,"bridge",{type:t,payload:i})},le=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)}F(this.contentRootElement,"error-message",s)};this.addEventListener("screen-updated",i,{once:!0}),i()},de=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,Z,"m",le).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,Z,"m",ce).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})},ce=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=""}))})),C(this.contentRootElement,this.autoFocus,!1))},he=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")}))},ue=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:a}=n,l=s(n,["next","stepName"]),d=k(l);let c=yield e(this,Z,"m",ne).call(this,a,d,r);c||(c=Boolean(yield null===(i=this.onScreenUpdate)||void 0===i?void 0:i.call(this,a,d,r,this)));const h=!this.stepState.current.htmlFilename;if(e(this,ge,"f").call(this,c),e(this,pe,"f")!==c){const[i,s]=["flow","custom"].sort((()=>c?-1:1));this.loggerWrapper.debug(`Switching from ${s} screen to ${i} screen`),t(this,pe,c,"f"),c?this.stepState.unsubscribeAll():e(this,Z,"m",de).call(this)}c&&(this.loggerWrapper.debug("Showing a custom screen"),e(this,Z,"m",Ie).call(this,{isFirstScreen:h,isCustomScreen:c,stepName:o.stepName})),this.stepState.forceUpdate=c}))},ve=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")},Se=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)}))}},ye=function(s,o){return i(this,void 0,void 0,(function*(){var n;null===(n=e(this,te,"f"))||void 0===n||n.abort();const r=s.querySelector('*[autocomplete="webauthn"]');if(r&&(yield V())){const{options:s,transactionId:n}=(yield e(this,we,"f").call(this))||{};s&&n&&(e(this,Z,"m",Se).call(this,r),t(this,te,new AbortController,"f"),this.sdk.webauthn.helpers.conditional(s,e(this,te,"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)})))}}))},Ie=function({isFirstScreen:t,isCustomScreen:i,stepName:s}){t&&e(this,Z,"m",Le).call(this,"ready",{}),i||e(this,Z,"m",re).call(this,s),e(this,Z,"m",Le).call(this,"page-updated",{screenName:s}),e(this,Z,"m",Le).call(this,"screen-updated",{screenName:s})},Ce=function(){let e=!0;return Array.from(this.shadowRoot.querySelectorAll("*[name]")).reverse().forEach((t=>{var i,s;"slot"!==t.localName&&(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},ke=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})),{})}))},We=function(s){const o=Array.from(this.contentRootElement.querySelectorAll(':not([disabled]), [disabled="false"]')).filter((e=>e!==s)),n=()=>i(this,void 0,void 0,(function*(){this.loggerWrapper.debug("Restoring components state"),this.removeEventListener("popupclosed",n),s.removeAttribute("loading"),o.forEach((e=>{e.removeAttribute("disabled")}));const e=yield this.getFlowConfig(),t=[...e.clientScripts||[],...e.sdkScripts||[]];this.loadSdkScripts(t)})),r=()=>{var i;window.removeEventListener("pageshow",e(this,Re,"f")),t(this,Re,(e=>{e.persisted&&(this.logger.debug("Page was loaded from cache, restoring components state"),n())}),"f"),window.addEventListener("pageshow",e(this,Re,"f"),{once:!0});const s=null===(i=this.stepState)||void 0===i?void 0:i.subscribe(((e,t)=>{e===t&&n(),this.removeEventListener("popupclosed",n),this.stepState.unsubscribe(s)}),(e=>e.screenId),{forceUpdate:!0})},a=this.nextRequestStatus.subscribe((({isLoading:e})=>{e?(this.addEventListener("popupclosed",n,{once:!0}),s.setAttribute("loading","true"),o.forEach((e=>e.setAttribute("disabled","true")))):(this.nextRequestStatus.unsubscribe(a),r())}))},Oe=function(e={}){var t,i;const s=A(e,["externalId","email","phone"]),o=A(e,["newPassword","password"]);if(s&&o)try{if(!globalThis.PasswordCredential)return;const e=new globalThis.PasswordCredential({id:s,password:o});null===(i=null===(t=null===navigator||void 0===navigator?void 0:navigator.credentials)||void 0===t?void 0:t.store)||void 0===i||i.call(t,e)}catch(e){this.loggerWrapper.error("Could not store credentials",e.message)}},Ee=function(){j();this.contentRootElement.querySelectorAll('[external-input="true"]').forEach((t=>e(this,Z,"m",xe).call(this,t)))},xe=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)}))},je=function(t){this.contentRootElement.querySelectorAll('descope-passcode[data-auto-submit="true"]').forEach((i=>{i.addEventListener("input",(()=>{var s;(null===(s=i.checkValidity)||void 0===s?void 0:s.call(i))&&e(this,Ae,"f").call(this,i,t)}))}))},Te=function(t){this.contentRootElement.querySelectorAll(`descope-button:not([${g}]), [data-type="button"]:not([${g}]`).forEach((i=>{i.onclick=()=>{e(this,Ae,"f").call(this,i,t)}})),e(this,Z,"m",je).call(this,t),this.isDismissScreenErrorOnInput&&this.contentRootElement.querySelectorAll(`*[name]:not([${p}])`).forEach((e=>{e.addEventListener("input",(()=>{this.stepState.update((e=>Object.assign(Object.assign({},e),{screenState:Object.assign(Object.assign({},e.screenState),{errorText:"",errorType:""})})))}))}))},Le=function(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t}))};export{Ue as default};
|
|
1
|
+
import{__classPrivateFieldGet as e,__classPrivateFieldSet as t,__awaiter as i,__rest as s}from"tslib";import{ensureFingerprintIds as o,clearFingerprintData as n}from"@descope/web-js-sdk";import{RESPONSE_ACTIONS as r,CUSTOM_INTERACTIONS as a,URL_CODE_PARAM_NAME as l,URL_TOKEN_PARAM_NAME as d,URL_RUN_IDS_PARAM_NAME as c,SDK_SCRIPTS_LOAD_TIMEOUT as h,DESCOPE_ATTRIBUTE_EXCLUDE_FIELD as p,ELEMENT_TYPE_ATTRIBUTE as u,DESCOPE_ATTRIBUTE_EXCLUDE_NEXT_BUTTON as g}from"../constants/index.js";import{timeoutPromise as v,withMemCache as m,leadingDebounce as f,getUserLocale as b,showFirstScreenOnExecutionInit as w,injectSamlIdpForm as S,openCenteredPopup as y,getAnimationDirection as I,handleAutoFocus as C,transformStepStateForCustomScreen as k,getElementDescopeAttributes as R,getScriptResultPath as W,submitForm as O,transformScreenInputs as E,handleReportValidityOnBlur as x,getFirstNonEmptyValue as A,clearPreviousExternalInputs as j}from"../helpers/helpers.js";import T from"../helpers/state.js";import{disableWebauthnButtons as L,updateTemplateFromScreenState as U,setPhoneAutoDetectDefaultCode as P,setTOTPVariable as N,setNOTPVariable as $,setCssVars as q,updateScreenFromScreenState as M,replaceElementMessage as F}from"../helpers/templates.js";import{isConditionalLoginSupported as V}from"../helpers/webauthn.js";import{getABTestingKey as D}from"../helpers/abTestingKey.js";import{calculateConditions as B,calculateCondition as K}from"../helpers/conditions.js";import{setLastAuth as H,getLastAuth as J}from"../helpers/lastAuth.js";import _ from"./BaseDescopeWc.js";import{FETCH_EXCEPTION_ERROR_CODE as G,FETCH_ERROR_RESPONSE_ERROR_CODE as z,FLOW_REQUESTED_IS_IN_OLD_VERSION_ERROR_CODE as Q,FLOW_TIMED_OUT_ERROR_CODE as X,POLLING_STATUS_NOT_FOUND_ERROR_CODE as Y}from"../constants/general.js";var Z,ee,te,ie,se,oe,ne,re,ae,le,de,ce,he,pe,ue,ge,ve,me,fe,be,we,Se,ye,Ie,Ce,ke,Re,We,Oe,Ee,xe,Ae,je,Te,Le;class Ue extends _{static set sdkConfigOverrides(e){_.sdkConfigOverrides=e}static get sdkConfigOverrides(){return _.sdkConfigOverrides}constructor(){const s=new T({deferredRedirect:!1});super(s.update.bind(s)),Z.add(this),this.stepState=new T({}),ee.set(this,void 0),te.set(this,null),ie.set(this,null),se.set(this,{visibilitychange:e(this,Z,"m",oe).bind(this)}),this.bridgeVersion=2,this.nativeCallbacks={},pe.set(this,!1),this.handleRedirect=e=>{window.location.assign(e)},ge.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,Z,"m",ve).call(this,i):i()})),me.set(this,((s,o,n,l,d=!1)=>{const c=[X,Y];if(this.flowState.current.action===r.poll){this.logger.debug("polling - Scheduling polling request");const r=Date.now(),h=d?500:2e3;t(this,ee,setTimeout((()=>i(this,void 0,void 0,(function*(){var t,i;this.logger.debug("polling - Calling next");const p=this.sdk.flow.next(s,o,a.polling,n,l,{}),u=document.hidden&&!d&&Date.now()-r>h+500;let g;u&&this.logger.debug("polling - The polling seems to be throttled");try{const e=u?1e3:6e3;g=yield v(e,p)}catch(t){return this.logger.warn(`polling - The ${u?"throttled fetch":"fetch"} call timed out or was aborted`),void e(this,me,"f").call(this,s,o,n,l,u)}if((null===(t=null==g?void 0:g.error)||void 0===t?void 0:t.errorCode)===G)return this.logger.debug("polling - Got a generic error due to exception in fetch call"),void e(this,me,"f").call(this,s,o,n,l);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,me,"f").call(this,s,o,n,l),e(this,be,"f").call(this,g)}))),h),"f")}})),fe.set(this,(()=>{clearTimeout(e(this,ee,"f")),t(this,ee,null,"f")})),be.set(this,(i=>{var s,o,n,a,l,d,c,h,p,u,g,v,m;if(!(null==i?void 0:i.ok)){const t=null===(s=null==i?void 0:i.response)||void 0===s?void 0:s.url,r=`${null===(o=null==i?void 0:i.response)||void 0===o?void 0:o.status} - ${null===(n=null==i?void 0:i.response)||void 0===n?void 0:n.statusText}`;e(this,Z,"m",Le).call(this,"error",(null==i?void 0:i.error)||{errorCode:z,errorDescription:r,errorMessage:t}),this.loggerWrapper.error((null===(a=null==i?void 0:i.error)||void 0===a?void 0:a.errorDescription)||t,(null===(l=null==i?void 0:i.error)||void 0===l?void 0:l.errorMessage)||r);const c=null===(d=null==i?void 0:i.error)||void 0===d?void 0:d.errorCode;return void(c!==Q&&c!==X||!this.isRestartOnError||e(this,Z,"m",he).call(this))}null===(h=null===(c=i.data)||void 0===c?void 0:c.runnerLogs)||void 0===h||h.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===(p=i.data)||void 0===p?void 0:p.screen)||void 0===u?void 0:u.state)||void 0===g?void 0:g.errorText;(null===(v=i.data)||void 0===v?void 0:v.error)?this.loggerWrapper.error(`[${i.data.error.code}]: ${i.data.error.description}`,`${f?`${f} - `:""}${i.data.error.message}`):f&&this.loggerWrapper.error(f);const{status:b,authInfo:w,lastAuth:S,action:y,openInNewTabUrl:I}=i.data;if(y!==r.poll&&e(this,fe,"f").call(this),"completed"===b)return this.storeLastAuthenticatedUser&&H(S),void e(this,Z,"m",Le).call(this,"success",w);this.storeLastAuthenticatedUser&&H(S,!0),I&&window.open(I,"_blank");const{executionId:C,stepId:k,stepName:R,screen:W,redirect:O,webauthn:E,error:x,samlIdpResponse:A,nativeResponse:j}=i.data,T=Date.now();y!==r.poll?(this.loggerWrapper.info(`Step "${R||`#${k}`}" is ${b}`,"",{screen:W,status:b,stepId:k,stepName:R,action:y,error:x}),(null===(m=W.state)||void 0===m?void 0:m.clientScripts)&&t(this,ie,this.loadSdkScripts(W.state.clientScripts),"f"),this.flowState.update({stepId:k,stepName:R,executionId:C,action:y,redirectTo:null==O?void 0:O.url,redirectIsPopup:null==O?void 0:O.isPopup,screenId:null==W?void 0:W.id,screenState:null==W?void 0:W.state,webauthnTransactionId:null==E?void 0:E.transactionId,webauthnOptions:null==E?void 0:E.options,samlIdpResponseUrl:null==A?void 0:A.url,samlIdpResponseSamlResponse:null==A?void 0:A.samlResponse,samlIdpResponseRelayState:null==A?void 0:A.relayState,nativeResponseType:null==j?void 0:j.type,nativePayload:null==j?void 0:j.payload,reqTimestamp:T})):this.flowState.update({action:y,reqTimestamp:T})})),we.set(this,m((()=>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)}}))))),Re.set(this,null),Ae.set(this,f(((t,s)=>i(this,void 0,void 0,(function*(){var i;if("true"===t.getAttribute("formnovalidate")||e(this,Z,"m",Ce).call(this)){const o=null==t?void 0:t.getAttribute("id");e(this,Z,"m",We).call(this,t);const n=yield e(this,Z,"m",ke).call(this),r=R(t);if(this.nextRequestStatus.update({isLoading:!0}),e(this,ie,"f")){this.loggerWrapper.debug("Waiting for sdk scripts to load");const t=Date.now();yield e(this,ie,"f"),this.loggerWrapper.debug("Sdk scripts loaded for",(Date.now()-t).toString())}const a=this.loadSdkScriptsModules();if(a.length>0){const e=a.filter((e=>"function"==typeof e.refresh)).map((e=>e.refresh()));e.length>0&&(yield v(h,Promise.all(e),null))}const l=this.getComponentsContext(),d=Object.assign(Object.assign(Object.assign(Object.assign({},l),r),n),{origin:(null===(i=this.nativeOptions)||void 0===i?void 0:i.origin)||window.location.origin});yield s(o,d),this.nextRequestStatus.update({isLoading:!1}),e(this,Z,"m",Oe).call(this,n)}}))))),this.flowState=s}nativeResume(t,i){var s,o,n,r,a;const h=JSON.parse(i);if("oauthWeb"===t||"sso"===t){let{exchangeCode:e}=h;if(!e){e=null===(s=new URL(h.url).searchParams)||void 0===s?void 0:s.get(l)}null===(n=(o=this.nativeCallbacks).complete)||void 0===n||n.call(o,{exchangeCode:e,idpInitiated:!0})}else if("magicLink"===t){const t=new URL(h.url),i=t.searchParams.get(d),s=t.searchParams.get(c).split("_").pop();e(this,fe,"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}=h;t||(this.nativeCallbacks.screenNext=null),null==e||e(t)}else if("resumeScreen"===t){const{interactionId:e,form:t}=h,{screenNext:i}=this.nativeCallbacks;this.nativeCallbacks.screenNext=null,null==i||i(e,t)}else null===(a=(r=this.nativeCallbacks).complete)||void 0===a||a.call(r,h)}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:{[W(e.id,e.resultKey)]:i},bubbles:!0,composed:!0})),t(e.id)};this.loggerWrapper.debug(`Preparing to load scripts: ${e.map((e=>e.id)).join(", ")}`);const s=Promise.all(null==e?void 0:e.map((e=>i(this,void 0,void 0,(function*(){var i,s;const o=this.shadowRoot.querySelector(`[data-script-id="${e.id}"]`);if(o){this.loggerWrapper.debug("Script already loaded",e.id);const{moduleRes:t}=o;return null===(i=null==t?void 0:t.start)||void 0===i||i.call(t),t}yield this.injectNpmLib("@descope/flow-scripts","1.0.11",`dist/${e.id}.js`);const n=null===(s=globalThis.descope)||void 0===s?void 0:s[e.id];return new Promise(((i,s)=>{try{const s=n(e.initArgs,{baseUrl:this.baseUrl,ref:this},t(e,i));if(s){const t=document.createElement("div");t.setAttribute("data-script-id",e.id),t.moduleRes=s,this.shadowRoot.appendChild(t),this.nextRequestStatus.subscribe((()=>{var t;this.loggerWrapper.debug("Unloading script",e.id),null===(t=s.stop)||void 0===t||t.call(s)}))}}catch(e){s(e)}}))}))))),o=new Promise((e=>{setTimeout((()=>{this.loggerWrapper.warn("SDK scripts loading timeout"),e(!0)}),h)}));return Promise.race([s,o])}get isDismissScreenErrorOnInput(){return"true"===this.getAttribute("dismiss-screen-error-on-input")}init(){if(!window.descopeBridge)return this._init();this.lazyInit=this._init}_init(){const t=Object.create(null,{init:{get:()=>super.init}});return i(this,void 0,void 0,(function*(){var i,s;this.shadowRoot.isConnected&&(null===(i=this.flowState)||void 0===i||i.subscribe(this.onFlowChange.bind(this)),e(this,Z,"m",de).call(this),window.addEventListener("visibilitychange",e(this,se,"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(),null===(i=e(this,te,"f"))||void 0===i||i.abort(),t(this,te,null,"f"),window.removeEventListener("visibilitychange",e(this,se,"f").visibilitychange)}getHtmlFilenameWithLocale(e,t){return i(this,void 0,void 0,(function*(){let i;const s=b(e),o=yield this.getTargetLocales();return o.includes(s.locale)?i=`${t}-${s.locale}.html`:o.includes(s.fallback)&&(i=`${t}-${s.fallback}.html`),i}))}getPageContent(e,t){return i(this,void 0,void 0,(function*(){if(t)try{const{body:e}=yield this.fetchStaticResource(t,"text");return e}catch(i){this.loggerWrapper.error(`Failed to fetch flow page from ${t}. Fallback to url ${e}`,i)}try{const{body:t}=yield this.fetchStaticResource(e,"text");return t}catch(e){this.loggerWrapper.error("Failed to fetch flow page",e.message)}return null}))}onFlowChange(l,d,c){return i(this,void 0,void 0,(function*(){var h,p;const{projectId:u,flowId:g,tenant:v,stepId:m,executionId:f,action:C,screenId:k,screenState:R,redirectTo:W,redirectIsPopup:x,redirectUrl:A,token:j,code:T,isPopup:L,exchangeError:U,webauthnTransactionId:P,webauthnOptions:N,redirectAuthCodeChallenge:$,redirectAuthCallbackUrl:q,redirectAuthBackupCallbackUri:M,redirectAuthInitiator:F,locale:V,samlIdpResponseUrl:H,samlIdpResponseSamlResponse:_,samlIdpResponseRelayState:G,nativeResponseType:z,nativePayload:Q,reqTimestamp:X}=l,Y=s(l,["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","nativeResponseType","nativePayload","reqTimestamp"]);let ee,se,oe;const ne=D(),{outboundAppId:re}=this,{outboundAppScopes:le}=this,de=this.sdk.getLastUserLoginId(),ce=yield this.getFlowConfig(),he=yield this.getProjectConfig(),pe=Object.entries(he.flows||{}).reduce(((e,[t,i])=>(e[t]=i.version,e)),{}),ge=q&&$?{callbackUrl:q,codeChallenge:$,backupCallbackUri:M}:void 0,ve=this.nativeOptions?{platform:this.nativeOptions.platform,bridgeVersion:this.nativeOptions.bridgeVersion,oauthProvider:this.nativeOptions.oauthProvider,oauthRedirect:this.nativeOptions.oauthRedirect,magicLinkRedirect:this.nativeOptions.magicLinkRedirect,ssoRedirect:this.nativeOptions.ssoRedirect}:void 0;let fe={};if(!f){const i=[...ce.clientScripts||[],...ce.sdkScripts||[]];if(ce.conditions){let e=[];({startScreenId:ee,conditionInteractionId:oe,startScreenName:se,clientScripts:e,componentsConfig:fe}=B({loginId:de,code:T,token:j,abTestingKey:ne,lastAuth:J(de)},ce.conditions)),i.push(...e||[])}else ce.condition?({startScreenId:ee,conditionInteractionId:oe}=K(ce.condition,{loginId:de,code:T,token:j,abTestingKey:ne,lastAuth:J(de)})):(se=ce.startScreenName,ee=ce.startScreenId);if(t(this,ie,this.loadSdkScripts(i),"f"),ce.fingerprintEnabled&&ce.fingerprintKey?yield o(ce.fingerprintKey,this.baseUrl):n(),!w(ee,Y)){const t=yield this.sdk.flow.start(g,Object.assign(Object.assign(Object.assign(Object.assign({tenant:v,redirectAuth:ge},Y),{client:this.client}),A&&{redirectUrl:A}),{lastAuth:J(de),abTestingKey:ne,locale:b(V).locale,nativeOptions:ve,outboundAppId:re,outboundAppScopes:le}),oe,"",he.componentsVersion,pe,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),T?{exchangeCode:T,idpInitiated:!0}:{}),Y.descopeIdpInitiated&&{idpInitiated:!0}),j?{token:j}:{}),Y.oidcLoginHint?{externalId:Y.oidcLoginHint}:{}));return e(this,be,"f").call(this,t),void("completed"!==(null===(h=null==t?void 0:t.data)||void 0===h?void 0:h.status)&&this.flowState.update({code:void 0,token:void 0}))}}if(this.loggerWrapper.debug("Before popup postmessage send",JSON.stringify({isPopup:L,code:T,exchangeError:U,isCodeChanged:c("code"),isExchangeErrorChanged:c("exchangeError")})),L&&(c("code")&&T||c("exchangeError")&&U)){this.loggerWrapper.debug("Creating popup channel",f);const e=new BroadcastChannel(f);return this.loggerWrapper.debug("Posting message to popup channel",JSON.stringify({code:T,exchangeError:U})),e.postMessage({data:{code:T,exchangeError:U},action:"code"}),this.loggerWrapper.debug("Popup channel message posted, closing channel"),e.close(),this.loggerWrapper.debug("Popup channel closed, closing window"),void window.close()}if(f&&(c("token")&&j||c("code")&&T||c("exchangeError")&&U)){const t=yield this.sdk.flow.next(f,m,a.submit,ce.version,he.componentsVersion,{token:j,exchangeCode:T,exchangeError:U});return e(this,be,"f").call(this,t),void this.flowState.update({token:void 0,code:void 0,exchangeError:void 0})}if(C===r.loadForm&&["samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState"].some((e=>c(e)))){if(!H||!_)return void this.loggerWrapper.error("Did not get saml idp params data to load");S(H,_,G||"",O)}if(C===r.redirect&&(c("redirectTo")||c("deferredRedirect"))){if(!W)return void this.loggerWrapper.error("Did not get redirect url");if("android"===F&&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=y(W,"?",598,700);this.loggerWrapper.debug("Creating broadcast channel");const i=new BroadcastChannel(f);this.loggerWrapper.debug("Starting popup closed detection");const s=setInterval((()=>{t.closed&&(this.loggerWrapper.debug("Popup closed, dispatching popupclosed event and clearing interval"),clearInterval(s),e(this,Z,"m",Le).call(this,"popupclosed",{}),this.loggerWrapper.debug("Closing channel"),i.close())}),1e3);this.loggerWrapper.debug("Listening for postMessage on channel");const o=e=>{if(this.loggerWrapper.debug("Received postMessage on channel",JSON.stringify(e)),this.loggerWrapper.debug("Comparing origins",JSON.stringify({eventOrigin:e.origin,windowLocationOrigin:window.location.origin})),e.origin!==window.location.origin)return;this.loggerWrapper.debug("PostMessage origin matches, processing message");const{action:t,data:i}=e.data;this.loggerWrapper.debug(`PostMessage action: ${t}, data: ${JSON.stringify(i)}`),"code"===t&&(this.loggerWrapper.debug("Updating flow state with code and exchangeError"),this.flowState.update({code:i.code,exchangeError:i.exchangeError}))};i.onmessage=o}else this.handleRedirect(W);return}if(C===r.webauthnCreate||C===r.webauthnGet){if(!P||!N)return void this.loggerWrapper.error("Did not get webauthn transaction id or options");let i,s;null===(p=e(this,te,"f"))||void 0===p||p.abort(),t(this,te,null,"f");try{i=C===r.webauthnCreate?yield this.sdk.webauthn.helpers.create(N):yield this.sdk.webauthn.helpers.get(N)}catch(e){"InvalidStateError"===e.name?this.loggerWrapper.warn("WebAuthn operation failed",e.message):"NotAllowedError"!==e.name&&this.loggerWrapper.error(e.message),s=e.name}const o=yield this.sdk.flow.next(f,m,a.submit,ce.version,he.componentsVersion,{transactionId:P,response:i,failure:s});e(this,be,"f").call(this,o)}if(C===r.nativeBridge)return this.nativeCallbacks.complete=t=>i(this,void 0,void 0,(function*(){const i=yield this.sdk.flow.next(f,m,a.submit,ce.version,he.componentsVersion,t);e(this,be,"f").call(this,i)})),void e(this,Z,"m",ae).call(this,z,Q);if(c("action")&&e(this,me,"f").call(this,f,m,ce.version,he.componentsVersion),!k&&!ee)return void this.loggerWrapper.warn("No screen was found to show");const we=ee||k,Se=yield this.getHtmlFilenameWithLocale(V,we),{oidcLoginHint:ye,oidcPrompt:Ie,oidcErrorRedirectUri:Ce,oidcResource:ke,samlIdpUsername:Re}=Y,We={direction:I(m,d.stepId),screenState:Object.assign(Object.assign({},R),{form:Object.assign(Object.assign({},this.formConfigValues),null==R?void 0:R.form),lastAuth:{loginId:de,name:this.sdk.getLastUserDisplayName()||de},componentsConfig:Object.assign(Object.assign(Object.assign({},ce.componentsConfig),fe),null==R?void 0:R.componentsConfig)}),htmlFilename:`${we}.html`,htmlLocaleFilename:Se,screenId:we,stepName:l.stepName||se,samlIdpUsername:Re,oidcLoginHint:ye,oidcPrompt:Ie,oidcErrorRedirectUri:Ce,oidcResource:ke,action:C},Oe=J(de);w(ee,Y)?We.next=(t,s)=>i(this,void 0,void 0,(function*(){const i=yield this.sdk.flow.start(g,Object.assign(Object.assign(Object.assign(Object.assign({tenant:v,redirectAuth:ge},Y),{lastAuth:Oe,preview:this.preview,abTestingKey:ne,client:this.client}),A&&{redirectUrl:A}),{locale:b(V).locale,nativeOptions:ve,outboundAppId:re,outboundAppScopes:le}),oe,t,he.componentsVersion,pe,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),E(s)),T&&{exchangeCode:T,idpInitiated:!0}),Y.descopeIdpInitiated&&{idpInitiated:!0}),j&&{token:j}));return e(this,be,"f").call(this,i),i})):(c("projectId")||c("baseUrl")||c("executionId")||c("stepId"))&&(We.next=(t,s)=>i(this,void 0,void 0,(function*(){const i=yield this.sdk.flow.next(f,m,t,ce.version,he.componentsVersion,E(s));return e(this,be,"f").call(this,i),i}))),this.loggerWrapper.debug("Got a screen with id",We.screenId),yield e(this,Z,"m",ue).call(this,We),this.stepState.update(We)}))}onStepChange(t,s){return i(this,void 0,void 0,(function*(){var o,n;const{htmlFilename:r,htmlLocaleFilename:l,direction:d,next:c,screenState:h}=t;this.loggerWrapper.debug("Rendering a flow screen");const p=document.createElement("template");p.innerHTML=yield this.getPageContent(r,l);const g=p.content.cloneNode(!0),v=this.loadDescopeUiComponents(p);this.sdk.webauthn.helpers.isSupported()?yield e(this,Z,"m",ye).call(this,g,c):L(g),!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),U(g,h,h.componentsConfig,this.formConfig,this.loggerWrapper);const{geo:m}=yield this.getExecutionContext();P(g,m);const f=()=>i(this,void 0,void 0,(function*(){var i,o;yield v;const n=this.contentRootElement;N(n,null===(i=null==h?void 0:h.totp)||void 0===i?void 0:i.image),$(n,null===(o=null==h?void 0:h.notp)||void 0===o?void 0:o.image),q(n,g,h.cssVars,this.loggerWrapper),n.replaceChildren(g);const r=!s.htmlFilename;setTimeout((()=>{e(this,Z,"m",Ee).call(this),this.validateOnBlur&&x(n),M(n,h),e(this,Z,"m",Ie).call(this,{isFirstScreen:r,isCustomScreen:!1,stepName:t.stepName}),C(n,this.autoFocus,r)})),e(this,Z,"m",Te).call(this,c);n.querySelector(`[${u}="polling"]`)&&c(a.polling,{})}));d?e(this,Z,"m",ve).call(this,f):f()}))}getInputs(){return Array.from(this.shadowRoot.querySelectorAll(`*:not(slot)[name]:not([${p}])`))}}ee=new WeakMap,te=new WeakMap,ie=new WeakMap,se=new WeakMap,pe=new WeakMap,ge=new WeakMap,me=new WeakMap,fe=new WeakMap,be=new WeakMap,we=new WeakMap,Re=new WeakMap,Ae=new WeakMap,Z=new WeakSet,oe=function(){document.hidden||setTimeout((()=>{this.flowState.update({deferredRedirect:!1})}),300)},ne=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,Z,"m",ae).call(this,"beforeScreen",{screen:t,context:s})}))}))},re=function(t){var i;(null===(i=this.nativeOptions)||void 0===i?void 0:i.bridgeVersion)>=2&&e(this,Z,"m",ae).call(this,"afterScreen",{screen:t})},ae=function(t,i){e(this,Z,"m",Le).call(this,"bridge",{type:t,payload:i})},le=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)}F(this.contentRootElement,"error-message",s)};this.addEventListener("screen-updated",i,{once:!0}),i()},de=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,Z,"m",le).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,Z,"m",ce).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})},ce=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=""}))})),C(this.contentRootElement,this.autoFocus,!1))},he=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")}))},ue=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:a}=n,l=s(n,["next","stepName"]),d=k(l);let c=yield e(this,Z,"m",ne).call(this,a,d,r);c||(c=Boolean(yield null===(i=this.onScreenUpdate)||void 0===i?void 0:i.call(this,a,d,r,this)));const h=!this.stepState.current.htmlFilename;if(e(this,ge,"f").call(this,c),e(this,pe,"f")!==c){const[i,s]=["flow","custom"].sort((()=>c?-1:1));this.loggerWrapper.debug(`Switching from ${s} screen to ${i} screen`),t(this,pe,c,"f"),c?this.stepState.unsubscribeAll():e(this,Z,"m",de).call(this)}c&&(this.loggerWrapper.debug("Showing a custom screen"),e(this,Z,"m",Ie).call(this,{isFirstScreen:h,isCustomScreen:c,stepName:o.stepName})),this.stepState.forceUpdate=c}))},ve=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")},Se=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)}))}},ye=function(s,o){return i(this,void 0,void 0,(function*(){var n;null===(n=e(this,te,"f"))||void 0===n||n.abort();const r=s.querySelector('*[autocomplete="webauthn"]');if(r&&(yield V())){const{options:s,transactionId:n}=(yield e(this,we,"f").call(this))||{};s&&n&&(e(this,Z,"m",Se).call(this,r),t(this,te,new AbortController,"f"),this.sdk.webauthn.helpers.conditional(s,e(this,te,"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)})))}}))},Ie=function({isFirstScreen:t,isCustomScreen:i,stepName:s}){t&&e(this,Z,"m",Le).call(this,"ready",{}),i||e(this,Z,"m",re).call(this,s),e(this,Z,"m",Le).call(this,"page-updated",{screenName:s}),e(this,Z,"m",Le).call(this,"screen-updated",{screenName:s})},Ce=function(){let e=!0;return Array.from(this.shadowRoot.querySelectorAll("*[name]")).reverse().forEach((t=>{var i,s;"slot"!==t.localName&&(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},ke=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})),{})}))},We=function(s){const o=Array.from(this.contentRootElement.querySelectorAll(':not([disabled]), [disabled="false"]')).filter((e=>e!==s)),n=()=>i(this,void 0,void 0,(function*(){this.loggerWrapper.debug("Restoring components state"),this.removeEventListener("popupclosed",n),s.removeAttribute("loading"),o.forEach((e=>{e.removeAttribute("disabled")}));const e=yield this.getFlowConfig(),t=[...e.clientScripts||[],...e.sdkScripts||[]];this.loadSdkScripts(t)})),r=()=>{var i;window.removeEventListener("pageshow",e(this,Re,"f")),t(this,Re,(e=>{e.persisted&&(this.logger.debug("Page was loaded from cache, restoring components state"),n())}),"f"),window.addEventListener("pageshow",e(this,Re,"f"),{once:!0});const s=null===(i=this.stepState)||void 0===i?void 0:i.subscribe(((e,t)=>{e===t&&n(),this.removeEventListener("popupclosed",n),this.stepState.unsubscribe(s)}),(e=>e.screenId),{forceUpdate:!0})},a=this.nextRequestStatus.subscribe((({isLoading:e})=>{e?(this.addEventListener("popupclosed",n,{once:!0}),s.setAttribute("loading","true"),o.forEach((e=>e.setAttribute("disabled","true")))):(this.nextRequestStatus.unsubscribe(a),r())}))},Oe=function(e={}){var t,i;const s=A(e,["externalId","email","phone"]),o=A(e,["newPassword","password"]);if(s&&o)try{if(!globalThis.PasswordCredential)return;const e=new globalThis.PasswordCredential({id:s,password:o});null===(i=null===(t=null===navigator||void 0===navigator?void 0:navigator.credentials)||void 0===t?void 0:t.store)||void 0===i||i.call(t,e)}catch(e){this.loggerWrapper.error("Could not store credentials",e.message)}},Ee=function(){j();this.contentRootElement.querySelectorAll('[external-input="true"]').forEach((t=>e(this,Z,"m",xe).call(this,t)))},xe=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)}))},je=function(t){this.contentRootElement.querySelectorAll('descope-passcode[data-auto-submit="true"]').forEach((i=>{i.addEventListener("input",(()=>{var s;(null===(s=i.checkValidity)||void 0===s?void 0:s.call(i))&&e(this,Ae,"f").call(this,i,t)}))}))},Te=function(t){this.contentRootElement.querySelectorAll(`descope-button:not([${g}]), [data-type="button"]:not([${g}]`).forEach((i=>{i.onclick=()=>{e(this,Ae,"f").call(this,i,t)}})),e(this,Z,"m",je).call(this,t),this.isDismissScreenErrorOnInput&&this.contentRootElement.querySelectorAll(`*[name]:not([${p}])`).forEach((e=>{e.addEventListener("input",(()=>{this.stepState.update((e=>Object.assign(Object.assign({},e),{screenState:Object.assign(Object.assign({},e.screenState),{errorText:"",errorType:""})})))}))}))},Le=function(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t}))};export{Ue as default};
|
|
2
2
|
//# sourceMappingURL=DescopeWc.js.map
|