@descope/web-component 4.7.4 → 4.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- "use strict";var e=require("tslib"),t=require("@descope/escape-markdown"),o=require("../constants/index.js"),r=require("./helpers.js");const s=["disabled"],c=(e,t)=>{Object.entries(t||{}).forEach((([t,r])=>{Array.from(e.querySelectorAll(`*[name="${t}"]:not([${o.DESCOPE_ATTRIBUTE_EXCLUDE_FIELD}])`)).forEach((e=>{e.value=r}))}))},n=(e,t)=>t.split(".").reduce(((e,t)=>(null==e?void 0:e[t])||""),e),l=(e,o,r)=>e.replace(/{{(.+?)}}/g,((e,s)=>r?t.escapeMarkdown(n(o,s)):n(o,s))),a=(e,t,r)=>{e.querySelectorAll(`[${o.ELEMENT_TYPE_ATTRIBUTE}="${t}"]`).forEach((e=>{e.setAttribute("href",r)}))},i=(e,t,o)=>{var r,s;const c=null===(r=customElements.get(t))||void 0===r?void 0:r.cssVarList.url;o&&c&&(null===(s=null==e?void 0:e.style)||void 0===s||s.setProperty(c,`url(data:image/jpg;base64,${o})`))};exports.disableWebauthnButtons=e=>{e.querySelectorAll(`descope-button[${o.ELEMENT_TYPE_ATTRIBUTE}="biometrics"]`).forEach((e=>e.setAttribute("disabled","true")))},exports.replaceElementMessage=(e,t,r="")=>{e.querySelectorAll(`[${o.ELEMENT_TYPE_ATTRIBUTE}="${t}"]`).forEach((e=>{e.textContent=r,e.classList[r?"remove":"add"]("hide")}))},exports.setComponentsAutoDetectByGeo=(e,t)=>{Object.entries({"default-code":"autoDetect","default-country":"autoDetect"}).forEach((([o,r])=>{Array.from(e.querySelectorAll(`[${o}="${r}"]`)).forEach((e=>{e.setAttribute(o,t||r)}))}))},exports.setComponentsAutoDetectByLocale=(e,t)=>{let o=t;if(t)try{const[e]=Intl.getCanonicalLocales(t);e&&(o=e)}catch(e){}Object.entries({lang:"autoDetect"}).forEach((([t,r])=>{Array.from(e.querySelectorAll(`[${t}="${r}"]`)).forEach((e=>{e.setAttribute(t,o||r)}))}))},exports.setCssVars=(e,t,o,r)=>{o&&Object.keys(o).forEach((s=>{if(!t.querySelector(s))return void r.debug(`Skipping css vars for component "${s}"`,`Got css vars for component ${s} but Could not find it on next page`);const c=customElements.get(s);c?Object.keys(o[s]).forEach((t=>{var n;const l=o[s],a=null===(n=null==c?void 0:c.cssVarList)||void 0===n?void 0:n[t];if(!a)return void r.info(`Could not find css variable name for ${t} in ${s}`,"Check if the css variable is defined in the component");const i=l[t];e.style.setProperty(a,i)})):r.debug(`Could not find component class for ${s}`,"Check if the component is registered")}))},exports.setNOTPVariable=(e,t)=>{i(e,"descope-notp-image",t)},exports.setTOTPVariable=(e,t)=>{i(e,"descope-totp-image",t)},exports.updateScreenFromScreenState=(e,t)=>{c(e,null==t?void 0:t.inputs),c(e,null==t?void 0:t.form)},exports.updateTemplateFromScreenState=(t,c,n,i)=>{var u,d;a(t,"totp-link",null===(u=null==c?void 0:c.totp)||void 0===u?void 0:u.provisionUrl),a(t,"notp-link",null===(d=null==c?void 0:c.notp)||void 0===d?void 0:d.redirectUrl),((e,t)=>{e.querySelectorAll("descope-text,descope-link,descope-enriched-text,descope-code-snippet").forEach((e=>{const o=r.shouldHandleMarkdown(e.localName);e.textContent=l(e.textContent,t,o);const s=e.getAttribute("href");s&&e.setAttribute("href",l(s,t))}))})(t,c),((t,o,r)=>{if(!o)return;const{componentsDynamicAttrs:s}=o,c=e.__rest(o,["componentsDynamicAttrs"]),n=Object.keys(c).reduce(((e,t)=>(e[`[name=${t}]`]=c[t],e)),{});s&&Object.keys(s).forEach((e=>{const t=s[e];if(t){const{attributes:o}=t;o&&Object.keys(o).length&&(n[e]=o)}})),Object.keys(n).forEach((e=>{t.querySelectorAll(e).forEach((t=>{const o=n[e];Object.keys(o).forEach((e=>{let s=o[e];if("string"!=typeof s)try{s=JSON.stringify(s)}catch(t){r.error(`Could not stringify value "${s}" for "${e}"`,t.message),s=""}t.setAttribute(e,s)}))}))}))})(t,null==c?void 0:c.componentsConfig,i),((e,t)=>{e.querySelectorAll(`[${o.HAS_DYNAMIC_VALUES_ATTR_NAME}]`).forEach((e=>{Array.from(e.attributes).forEach((e=>{e.value=l(e.value,t)}))}))})(t,c),((e,t)=>{Object.entries(t).forEach((([t,o])=>{e.querySelectorAll(`[name="${t}"]`).forEach((e=>{Object.entries(o).forEach((([t,o])=>{s.includes(t)&&e.setAttribute(t,o)}))}))}))})(t,n)};
1
+ "use strict";var e=require("tslib"),t=require("@descope/escape-markdown"),o=require("../constants/index.js"),r=require("./helpers.js");const s=["disabled"],n=(e,t)=>{Object.entries(t||{}).forEach((([t,r])=>{Array.from(e.querySelectorAll(`*[name="${t}"]:not([${o.DESCOPE_ATTRIBUTE_EXCLUDE_FIELD}])`)).forEach((e=>{e.value=r}))}))},c=(e,t)=>t.split(".").reduce(((e,t)=>(null==e?void 0:e[t])||""),e),l=(e,o,r)=>e.replace(/{{(.+?)}}/g,((e,s)=>r?t.escapeMarkdown(String(c(o,s))):c(o,s))),i=(e,t,r)=>{e.querySelectorAll(`[${o.ELEMENT_TYPE_ATTRIBUTE}="${t}"]`).forEach((e=>{e.setAttribute("href",r)}))},a=(e,t,o)=>{var r,s;const n=null===(r=customElements.get(t))||void 0===r?void 0:r.cssVarList.url;o&&n&&(null===(s=null==e?void 0:e.style)||void 0===s||s.setProperty(n,`url(data:image/jpg;base64,${o})`))};exports.disableWebauthnButtons=e=>{e.querySelectorAll(`descope-button[${o.ELEMENT_TYPE_ATTRIBUTE}="biometrics"]`).forEach((e=>e.setAttribute("disabled","true")))},exports.replaceElementMessage=(e,t,r="")=>{e.querySelectorAll(`[${o.ELEMENT_TYPE_ATTRIBUTE}="${t}"]`).forEach((e=>{e.textContent=r,e.classList[r?"remove":"add"]("hide")}))},exports.setComponentsAutoDetectByGeo=(e,t)=>{Object.entries({"default-code":"autoDetect","default-country":"autoDetect"}).forEach((([o,r])=>{Array.from(e.querySelectorAll(`[${o}="${r}"]`)).forEach((e=>{e.setAttribute(o,t||r)}))}))},exports.setComponentsAutoDetectByLocale=(e,t)=>{let o=t;if(t)try{const[e]=Intl.getCanonicalLocales(t);e&&(o=e)}catch(e){}Object.entries({lang:"autoDetect"}).forEach((([t,r])=>{Array.from(e.querySelectorAll(`[${t}="${r}"]`)).forEach((e=>{e.setAttribute(t,o||r)}))}))},exports.setCssVars=(e,t,o,r)=>{o&&Object.keys(o).forEach((s=>{if(!t.querySelector(s))return void r.debug(`Skipping css vars for component "${s}"`,`Got css vars for component ${s} but Could not find it on next page`);const n=customElements.get(s);n?Object.keys(o[s]).forEach((t=>{var c;const l=o[s],i=null===(c=null==n?void 0:n.cssVarList)||void 0===c?void 0:c[t];if(!i)return void r.info(`Could not find css variable name for ${t} in ${s}`,"Check if the css variable is defined in the component");const a=l[t];e.style.setProperty(i,a)})):r.debug(`Could not find component class for ${s}`,"Check if the component is registered")}))},exports.setNOTPVariable=(e,t)=>{a(e,"descope-notp-image",t)},exports.setTOTPVariable=(e,t)=>{a(e,"descope-totp-image",t)},exports.updateScreenFromScreenState=(e,t)=>{n(e,null==t?void 0:t.inputs),n(e,null==t?void 0:t.form)},exports.updateTemplateFromScreenState=(t,n,c,a)=>{var u,d;i(t,"totp-link",null===(u=null==n?void 0:n.totp)||void 0===u?void 0:u.provisionUrl),i(t,"notp-link",null===(d=null==n?void 0:n.notp)||void 0===d?void 0:d.redirectUrl),((e,t)=>{e.querySelectorAll("descope-text,descope-link,descope-enriched-text,descope-code-snippet").forEach((e=>{const o=r.shouldHandleMarkdown(e.localName);e.textContent=l(e.textContent,t,o);const s=e.getAttribute("href");s&&e.setAttribute("href",l(s,t))}))})(t,n),((t,o,r)=>{if(!o)return;const{componentsDynamicAttrs:s}=o,n=e.__rest(o,["componentsDynamicAttrs"]),c=Object.keys(n).reduce(((e,t)=>(e[`[name=${t}]`]=n[t],e)),{});s&&Object.keys(s).forEach((e=>{const t=s[e];if(t){const{attributes:o}=t;o&&Object.keys(o).length&&(c[e]=o)}})),Object.keys(c).forEach((e=>{t.querySelectorAll(e).forEach((t=>{const o=c[e];Object.keys(o).forEach((e=>{let s=o[e];if("string"!=typeof s)try{s=JSON.stringify(s)}catch(t){r.error(`Could not stringify value "${s}" for "${e}"`,t.message),s=""}t.setAttribute(e,s)}))}))}))})(t,null==n?void 0:n.componentsConfig,a),((e,t)=>{e.querySelectorAll(`[${o.HAS_DYNAMIC_VALUES_ATTR_NAME}]`).forEach((e=>{Array.from(e.attributes).forEach((e=>{e.value=l(e.value,t)}))}))})(t,n),((e,t)=>{Object.entries(t).forEach((([t,o])=>{e.querySelectorAll(`[name="${t}"]`).forEach((e=>{Object.entries(o).forEach((([t,o])=>{s.includes(t)&&e.setAttribute(t,o)}))}))}))})(t,c)};
2
2
  //# sourceMappingURL=templates.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"templates.js","sources":["../../../src/lib/helpers/templates.ts"],"sourcesContent":["import { escapeMarkdown } from '@descope/escape-markdown';\nimport {\n ELEMENT_TYPE_ATTRIBUTE,\n DESCOPE_ATTRIBUTE_EXCLUDE_FIELD,\n HAS_DYNAMIC_VALUES_ATTR_NAME,\n} from '../constants';\nimport { ComponentsConfig, CssVars, ScreenState } from '../types';\nimport { shouldHandleMarkdown } from './helpers';\n\nconst ALLOWED_INPUT_CONFIG_ATTRS = ['disabled'];\n\nexport const replaceElementMessage = (\n baseEle: HTMLElement,\n eleType: string,\n message = '',\n) => {\n const eleList = baseEle.querySelectorAll(\n `[${ELEMENT_TYPE_ATTRIBUTE}=\"${eleType}\"]`,\n );\n eleList.forEach((ele: HTMLElement) => {\n // eslint-disable-next-line no-param-reassign\n ele.textContent = message;\n ele.classList[message ? 'remove' : 'add']('hide');\n });\n};\n\n/**\n * Replace the 'value' attribute of screen inputs with screen state's inputs.\n * For example: if base element contains '<input name=\"key1\" ...>' and screen input is in form of { key1: 'val1' },\n * it will add 'val1' as the input value\n */\nconst replaceElementInputs = (\n baseEle: HTMLElement,\n screenInputs: Record<string, string>,\n) => {\n Object.entries(screenInputs || {}).forEach(([name, value]) => {\n const inputEls = Array.from(\n baseEle.querySelectorAll(\n `*[name=\"${name}\"]:not([${DESCOPE_ATTRIBUTE_EXCLUDE_FIELD}])`,\n ),\n ) as HTMLInputElement[];\n inputEls.forEach((inputEle) => {\n // eslint-disable-next-line no-param-reassign\n inputEle.value = value;\n });\n });\n};\n\n/**\n * Get object nested path.\n * Examples:\n * - getByPath({ { a { b: 'rob' } }, 'a.b') => 'hey rob'\n * - getByPath({}, 'a.b') => ''\n */\nconst getByPath = (obj: Record<string, any>, path: string) =>\n path.split('.').reduce((prev, next) => prev?.[next] || '', obj);\n\n/**\n * Apply template language on text, based on screen state.\n * Examples:\n * - 'hey {{a.b}}', { a { b: 'rob' }} => 'hey rob'\n * - 'hey {{not.exists}}', {} => 'hey '\n */\nconst applyTemplates = (\n text: string,\n screenState?: Record<string, any>,\n handleMarkdown?: boolean,\n): string =>\n text.replace(/{{(.+?)}}/g, (_, match) =>\n handleMarkdown\n ? escapeMarkdown(getByPath(screenState, match))\n : getByPath(screenState, match),\n );\n\n/**\n * Replace the templates of content of inner text/link elements with screen state data\n */\nconst replaceElementTemplates = (\n baseEle: DocumentFragment,\n screenState?: Record<string, any>,\n) => {\n const eleList = baseEle.querySelectorAll(\n 'descope-text,descope-link,descope-enriched-text,descope-code-snippet',\n );\n eleList.forEach((inEle: HTMLElement) => {\n const handleMarkdown = shouldHandleMarkdown(inEle.localName);\n // eslint-disable-next-line no-param-reassign\n inEle.textContent = applyTemplates(\n inEle.textContent,\n screenState,\n handleMarkdown,\n );\n const href = inEle.getAttribute('href');\n if (href) {\n inEle.setAttribute('href', applyTemplates(href, screenState));\n }\n });\n};\n\nconst replaceTemplateDynamicAttrValues = (\n baseEle: DocumentFragment,\n screenState?: Record<string, any>,\n) => {\n const eleList = baseEle.querySelectorAll(`[${HAS_DYNAMIC_VALUES_ATTR_NAME}]`);\n eleList.forEach((ele: HTMLElement) => {\n Array.from(ele.attributes).forEach((attr) => {\n // eslint-disable-next-line no-param-reassign\n attr.value = applyTemplates(attr.value, screenState);\n });\n });\n};\n\nconst replaceHrefByDataType = (\n baseEle: DocumentFragment,\n dataType: string,\n provisionUrl?: string,\n) => {\n const eleList = baseEle.querySelectorAll(\n `[${ELEMENT_TYPE_ATTRIBUTE}=\"${dataType}\"]`,\n );\n eleList.forEach((ele: HTMLLinkElement) => {\n // eslint-disable-next-line no-param-reassign\n ele.setAttribute('href', provisionUrl);\n });\n};\n\nconst setFormConfigValues = (\n baseEle: DocumentFragment,\n formData: Record<string, string>,\n) => {\n Object.entries(formData).forEach(([name, config]) => {\n const eles = baseEle.querySelectorAll(`[name=\"${name}\"]`);\n\n eles.forEach((ele) => {\n Object.entries(config).forEach(([attrName, attrValue]) => {\n if (ALLOWED_INPUT_CONFIG_ATTRS.includes(attrName)) {\n ele.setAttribute(attrName, attrValue);\n }\n });\n });\n });\n};\n\nexport const setCssVars = (\n rootEle: HTMLElement,\n nextPageTemplate: DocumentFragment,\n cssVars: CssVars,\n logger: {\n error: (message: string, description: string) => void;\n info: (message: string, description: string) => void;\n debug: (message: string, description: string) => void;\n },\n) => {\n if (!cssVars) {\n return;\n }\n\n Object.keys(cssVars).forEach((componentName) => {\n if (!nextPageTemplate.querySelector(componentName)) {\n logger.debug(\n `Skipping css vars for component \"${componentName}\"`,\n `Got css vars for component ${componentName} but Could not find it on next page`,\n );\n\n return;\n }\n const componentClass:\n | (CustomElementConstructor & { cssVarList: CssVars })\n | undefined = customElements.get(componentName) as any;\n\n if (!componentClass) {\n logger.debug(\n `Could not find component class for ${componentName}`,\n 'Check if the component is registered',\n );\n\n return;\n }\n\n Object.keys(cssVars[componentName]).forEach((cssVarKey) => {\n const componentCssVars = cssVars[componentName];\n const varName = componentClass?.cssVarList?.[cssVarKey];\n\n if (!varName) {\n logger.info(\n `Could not find css variable name for ${cssVarKey} in ${componentName}`,\n 'Check if the css variable is defined in the component',\n );\n return;\n }\n\n const value = componentCssVars[cssVarKey];\n\n rootEle.style.setProperty(varName, value);\n });\n });\n};\n\nconst setElementConfig = (\n baseEle: DocumentFragment,\n componentsConfig: ComponentsConfig,\n logger?: { error: (message: string, description: string) => void },\n) => {\n if (!componentsConfig) {\n return;\n }\n const { componentsDynamicAttrs, ...rest } = componentsConfig;\n\n const configMap = Object.keys(rest).reduce((acc, componentName) => {\n acc[`[name=${componentName}]`] = rest[componentName];\n return acc;\n }, {});\n\n if (componentsDynamicAttrs) {\n Object.keys(componentsDynamicAttrs).forEach((componentSelector) => {\n const componentDynamicAttrs = componentsDynamicAttrs[componentSelector];\n if (componentDynamicAttrs) {\n const { attributes } = componentDynamicAttrs;\n if (attributes && Object.keys(attributes).length) {\n configMap[componentSelector] = attributes;\n }\n }\n });\n }\n\n // collect components that needs configuration from DOM\n Object.keys(configMap).forEach((componentsSelector) => {\n baseEle.querySelectorAll(componentsSelector).forEach((comp) => {\n const config = configMap[componentsSelector];\n\n Object.keys(config).forEach((attr) => {\n let value = config[attr];\n\n if (typeof value !== 'string') {\n try {\n value = JSON.stringify(value);\n } catch (e) {\n logger.error(\n `Could not stringify value \"${value}\" for \"${attr}\"`,\n e.message,\n );\n value = '';\n }\n }\n\n comp.setAttribute(attr, value);\n });\n });\n });\n};\n\nconst setImageVariable = (\n rootEle: HTMLElement,\n name: string,\n image?: string,\n) => {\n const imageVarName = (\n customElements.get(name) as CustomElementConstructor & {\n cssVarList: Record<string, string>;\n }\n )?.cssVarList.url;\n\n if (image && imageVarName) {\n rootEle?.style?.setProperty(\n imageVarName,\n `url(data:image/jpg;base64,${image})`,\n );\n }\n};\n\n/**\n * Update a screen template based on the screen state\n * - Show/hide error messages\n * - Replace element templates ({{...}} syntax) with screen state object\n *\n * Note: applying `screenState.componentsState` (the server-applied baseline\n * hide/disable/read-only map) is owned by the `componentConditionsMixin`. The\n * host calls `this.applyComponentsState(...)` after this function returns and\n * before the fragment is mounted.\n */\nexport const updateTemplateFromScreenState = (\n baseEle: DocumentFragment,\n screenState?: ScreenState,\n flowInputs?: Record<string, string>,\n logger?: { error: (message: string, description: string) => void },\n) => {\n replaceHrefByDataType(baseEle, 'totp-link', screenState?.totp?.provisionUrl);\n replaceHrefByDataType(baseEle, 'notp-link', screenState?.notp?.redirectUrl);\n replaceElementTemplates(baseEle, screenState);\n setElementConfig(baseEle, screenState?.componentsConfig, logger);\n replaceTemplateDynamicAttrValues(baseEle, screenState);\n setFormConfigValues(baseEle, flowInputs);\n};\n\n/**\n * Update a screen based on a screen state\n * - Replace values of element inputs with screen state's inputs\n */\nexport const updateScreenFromScreenState = (\n baseEle: HTMLElement,\n screenState?: ScreenState,\n) => {\n replaceElementInputs(baseEle, screenState?.inputs);\n replaceElementInputs(baseEle, screenState?.form);\n};\n\nexport const setTOTPVariable = (rootEle: HTMLElement, image?: string) => {\n setImageVariable(rootEle, 'descope-totp-image', image);\n};\n\nexport const setNOTPVariable = (rootEle: HTMLElement, image?: string) => {\n setImageVariable(rootEle, 'descope-notp-image', image);\n};\n\nexport const setComponentsAutoDetectByGeo = (\n fragment: DocumentFragment,\n countryCodeIso2?: string, // e.g. 'US', 'IL', 'FR'\n) => {\n const config = {\n // phone\n 'default-code': 'autoDetect',\n // country-subdivision-city\n 'default-country': 'autoDetect',\n };\n Object.entries(config).forEach(([key, value]) => {\n Array.from(fragment.querySelectorAll(`[${key}=\"${value}\"]`)).forEach(\n (ele) => {\n ele.setAttribute(key, countryCodeIso2 || value);\n },\n );\n });\n};\n\nexport const setComponentsAutoDetectByLocale = (\n fragment: DocumentFragment,\n locale?: string, // e.g. 'en-US', 'fr-FR'\n) => {\n const config = {\n // country-subdivision-city\n lang: 'autoDetect',\n };\n\n let canonicalLocale = locale;\n if (locale) {\n try {\n const [canonical] = Intl.getCanonicalLocales(locale);\n if (canonical) {\n canonicalLocale = canonical;\n }\n } catch {\n // locale is not valid, keep original value\n }\n }\n\n Object.entries(config).forEach(([key, value]) => {\n Array.from(fragment.querySelectorAll(`[${key}=\"${value}\"]`)).forEach(\n (ele) => {\n ele.setAttribute(key, canonicalLocale || value);\n },\n );\n });\n};\n\nexport const disableWebauthnButtons = (fragment: DocumentFragment) => {\n const webauthnButtons = fragment.querySelectorAll(\n `descope-button[${ELEMENT_TYPE_ATTRIBUTE}=\"biometrics\"]`,\n );\n webauthnButtons.forEach((button) => button.setAttribute('disabled', 'true'));\n};\n\nexport const getDescopeUiComponentsList = (clone: DocumentFragment) => [\n ...Array.from(clone.querySelectorAll('*')).reduce<Set<string>>(\n (acc, el: HTMLElement) =>\n el.tagName.startsWith('DESCOPE-')\n ? acc.add(el.tagName.toLocaleLowerCase())\n : acc,\n new Set(),\n ),\n];\n"],"names":["ALLOWED_INPUT_CONFIG_ATTRS","replaceElementInputs","baseEle","screenInputs","Object","entries","forEach","name","value","Array","from","querySelectorAll","DESCOPE_ATTRIBUTE_EXCLUDE_FIELD","inputEle","getByPath","obj","path","split","reduce","prev","next","applyTemplates","text","screenState","handleMarkdown","replace","_","match","escapeMarkdown","replaceHrefByDataType","dataType","provisionUrl","ELEMENT_TYPE_ATTRIBUTE","ele","setAttribute","setImageVariable","rootEle","image","imageVarName","_a","customElements","get","cssVarList","url","_b","style","setProperty","fragment","button","eleType","message","textContent","classList","countryCodeIso2","key","locale","canonicalLocale","canonical","Intl","getCanonicalLocales","lang","nextPageTemplate","cssVars","logger","keys","componentName","querySelector","debug","componentClass","cssVarKey","componentCssVars","varName","info","inputs","form","flowInputs","totp","notp","redirectUrl","inEle","shouldHandleMarkdown","localName","href","getAttribute","replaceElementTemplates","componentsConfig","componentsDynamicAttrs","rest","__rest","configMap","acc","componentSelector","componentDynamicAttrs","attributes","length","componentsSelector","comp","config","attr","JSON","stringify","e","error","setElementConfig","HAS_DYNAMIC_VALUES_ATTR_NAME","replaceTemplateDynamicAttrValues","formData","attrName","attrValue","includes","setFormConfigValues"],"mappings":"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"}
1
+ {"version":3,"file":"templates.js","sources":["../../../src/lib/helpers/templates.ts"],"sourcesContent":["import { escapeMarkdown } from '@descope/escape-markdown';\nimport {\n ELEMENT_TYPE_ATTRIBUTE,\n DESCOPE_ATTRIBUTE_EXCLUDE_FIELD,\n HAS_DYNAMIC_VALUES_ATTR_NAME,\n} from '../constants';\nimport { ComponentsConfig, CssVars, ScreenState } from '../types';\nimport { shouldHandleMarkdown } from './helpers';\n\nconst ALLOWED_INPUT_CONFIG_ATTRS = ['disabled'];\n\nexport const replaceElementMessage = (\n baseEle: HTMLElement,\n eleType: string,\n message = '',\n) => {\n const eleList = baseEle.querySelectorAll(\n `[${ELEMENT_TYPE_ATTRIBUTE}=\"${eleType}\"]`,\n );\n eleList.forEach((ele: HTMLElement) => {\n // eslint-disable-next-line no-param-reassign\n ele.textContent = message;\n ele.classList[message ? 'remove' : 'add']('hide');\n });\n};\n\n/**\n * Replace the 'value' attribute of screen inputs with screen state's inputs.\n * For example: if base element contains '<input name=\"key1\" ...>' and screen input is in form of { key1: 'val1' },\n * it will add 'val1' as the input value\n */\nconst replaceElementInputs = (\n baseEle: HTMLElement,\n screenInputs: Record<string, string>,\n) => {\n Object.entries(screenInputs || {}).forEach(([name, value]) => {\n const inputEls = Array.from(\n baseEle.querySelectorAll(\n `*[name=\"${name}\"]:not([${DESCOPE_ATTRIBUTE_EXCLUDE_FIELD}])`,\n ),\n ) as HTMLInputElement[];\n inputEls.forEach((inputEle) => {\n // eslint-disable-next-line no-param-reassign\n inputEle.value = value;\n });\n });\n};\n\n/**\n * Get object nested path.\n * Examples:\n * - getByPath({ { a { b: 'rob' } }, 'a.b') => 'hey rob'\n * - getByPath({}, 'a.b') => ''\n */\nconst getByPath = (obj: Record<string, any>, path: string) =>\n path.split('.').reduce((prev, next) => prev?.[next] || '', obj);\n\n/**\n * Apply template language on text, based on screen state.\n * Examples:\n * - 'hey {{a.b}}', { a { b: 'rob' }} => 'hey rob'\n * - 'hey {{not.exists}}', {} => 'hey '\n */\nconst applyTemplates = (\n text: string,\n screenState?: Record<string, any>,\n handleMarkdown?: boolean,\n): string =>\n text.replace(/{{(.+?)}}/g, (_, match) =>\n handleMarkdown\n ? escapeMarkdown(String(getByPath(screenState, match)))\n : getByPath(screenState, match),\n );\n\n/**\n * Replace the templates of content of inner text/link elements with screen state data\n */\nconst replaceElementTemplates = (\n baseEle: DocumentFragment,\n screenState?: Record<string, any>,\n) => {\n const eleList = baseEle.querySelectorAll(\n 'descope-text,descope-link,descope-enriched-text,descope-code-snippet',\n );\n eleList.forEach((inEle: HTMLElement) => {\n const handleMarkdown = shouldHandleMarkdown(inEle.localName);\n // eslint-disable-next-line no-param-reassign\n inEle.textContent = applyTemplates(\n inEle.textContent,\n screenState,\n handleMarkdown,\n );\n const href = inEle.getAttribute('href');\n if (href) {\n inEle.setAttribute('href', applyTemplates(href, screenState));\n }\n });\n};\n\nconst replaceTemplateDynamicAttrValues = (\n baseEle: DocumentFragment,\n screenState?: Record<string, any>,\n) => {\n const eleList = baseEle.querySelectorAll(`[${HAS_DYNAMIC_VALUES_ATTR_NAME}]`);\n eleList.forEach((ele: HTMLElement) => {\n Array.from(ele.attributes).forEach((attr) => {\n // eslint-disable-next-line no-param-reassign\n attr.value = applyTemplates(attr.value, screenState);\n });\n });\n};\n\nconst replaceHrefByDataType = (\n baseEle: DocumentFragment,\n dataType: string,\n provisionUrl?: string,\n) => {\n const eleList = baseEle.querySelectorAll(\n `[${ELEMENT_TYPE_ATTRIBUTE}=\"${dataType}\"]`,\n );\n eleList.forEach((ele: HTMLLinkElement) => {\n // eslint-disable-next-line no-param-reassign\n ele.setAttribute('href', provisionUrl);\n });\n};\n\nconst setFormConfigValues = (\n baseEle: DocumentFragment,\n formData: Record<string, string>,\n) => {\n Object.entries(formData).forEach(([name, config]) => {\n const eles = baseEle.querySelectorAll(`[name=\"${name}\"]`);\n\n eles.forEach((ele) => {\n Object.entries(config).forEach(([attrName, attrValue]) => {\n if (ALLOWED_INPUT_CONFIG_ATTRS.includes(attrName)) {\n ele.setAttribute(attrName, attrValue);\n }\n });\n });\n });\n};\n\nexport const setCssVars = (\n rootEle: HTMLElement,\n nextPageTemplate: DocumentFragment,\n cssVars: CssVars,\n logger: {\n error: (message: string, description: string) => void;\n info: (message: string, description: string) => void;\n debug: (message: string, description: string) => void;\n },\n) => {\n if (!cssVars) {\n return;\n }\n\n Object.keys(cssVars).forEach((componentName) => {\n if (!nextPageTemplate.querySelector(componentName)) {\n logger.debug(\n `Skipping css vars for component \"${componentName}\"`,\n `Got css vars for component ${componentName} but Could not find it on next page`,\n );\n\n return;\n }\n const componentClass:\n | (CustomElementConstructor & { cssVarList: CssVars })\n | undefined = customElements.get(componentName) as any;\n\n if (!componentClass) {\n logger.debug(\n `Could not find component class for ${componentName}`,\n 'Check if the component is registered',\n );\n\n return;\n }\n\n Object.keys(cssVars[componentName]).forEach((cssVarKey) => {\n const componentCssVars = cssVars[componentName];\n const varName = componentClass?.cssVarList?.[cssVarKey];\n\n if (!varName) {\n logger.info(\n `Could not find css variable name for ${cssVarKey} in ${componentName}`,\n 'Check if the css variable is defined in the component',\n );\n return;\n }\n\n const value = componentCssVars[cssVarKey];\n\n rootEle.style.setProperty(varName, value);\n });\n });\n};\n\nconst setElementConfig = (\n baseEle: DocumentFragment,\n componentsConfig: ComponentsConfig,\n logger?: { error: (message: string, description: string) => void },\n) => {\n if (!componentsConfig) {\n return;\n }\n const { componentsDynamicAttrs, ...rest } = componentsConfig;\n\n const configMap = Object.keys(rest).reduce((acc, componentName) => {\n acc[`[name=${componentName}]`] = rest[componentName];\n return acc;\n }, {});\n\n if (componentsDynamicAttrs) {\n Object.keys(componentsDynamicAttrs).forEach((componentSelector) => {\n const componentDynamicAttrs = componentsDynamicAttrs[componentSelector];\n if (componentDynamicAttrs) {\n const { attributes } = componentDynamicAttrs;\n if (attributes && Object.keys(attributes).length) {\n configMap[componentSelector] = attributes;\n }\n }\n });\n }\n\n // collect components that needs configuration from DOM\n Object.keys(configMap).forEach((componentsSelector) => {\n baseEle.querySelectorAll(componentsSelector).forEach((comp) => {\n const config = configMap[componentsSelector];\n\n Object.keys(config).forEach((attr) => {\n let value = config[attr];\n\n if (typeof value !== 'string') {\n try {\n value = JSON.stringify(value);\n } catch (e) {\n logger.error(\n `Could not stringify value \"${value}\" for \"${attr}\"`,\n e.message,\n );\n value = '';\n }\n }\n\n comp.setAttribute(attr, value);\n });\n });\n });\n};\n\nconst setImageVariable = (\n rootEle: HTMLElement,\n name: string,\n image?: string,\n) => {\n const imageVarName = (\n customElements.get(name) as CustomElementConstructor & {\n cssVarList: Record<string, string>;\n }\n )?.cssVarList.url;\n\n if (image && imageVarName) {\n rootEle?.style?.setProperty(\n imageVarName,\n `url(data:image/jpg;base64,${image})`,\n );\n }\n};\n\n/**\n * Update a screen template based on the screen state\n * - Show/hide error messages\n * - Replace element templates ({{...}} syntax) with screen state object\n *\n * Note: applying `screenState.componentsState` (the server-applied baseline\n * hide/disable/read-only map) is owned by the `componentConditionsMixin`. The\n * host calls `this.applyComponentsState(...)` after this function returns and\n * before the fragment is mounted.\n */\nexport const updateTemplateFromScreenState = (\n baseEle: DocumentFragment,\n screenState?: ScreenState,\n flowInputs?: Record<string, string>,\n logger?: { error: (message: string, description: string) => void },\n) => {\n replaceHrefByDataType(baseEle, 'totp-link', screenState?.totp?.provisionUrl);\n replaceHrefByDataType(baseEle, 'notp-link', screenState?.notp?.redirectUrl);\n replaceElementTemplates(baseEle, screenState);\n setElementConfig(baseEle, screenState?.componentsConfig, logger);\n replaceTemplateDynamicAttrValues(baseEle, screenState);\n setFormConfigValues(baseEle, flowInputs);\n};\n\n/**\n * Update a screen based on a screen state\n * - Replace values of element inputs with screen state's inputs\n */\nexport const updateScreenFromScreenState = (\n baseEle: HTMLElement,\n screenState?: ScreenState,\n) => {\n replaceElementInputs(baseEle, screenState?.inputs);\n replaceElementInputs(baseEle, screenState?.form);\n};\n\nexport const setTOTPVariable = (rootEle: HTMLElement, image?: string) => {\n setImageVariable(rootEle, 'descope-totp-image', image);\n};\n\nexport const setNOTPVariable = (rootEle: HTMLElement, image?: string) => {\n setImageVariable(rootEle, 'descope-notp-image', image);\n};\n\nexport const setComponentsAutoDetectByGeo = (\n fragment: DocumentFragment,\n countryCodeIso2?: string, // e.g. 'US', 'IL', 'FR'\n) => {\n const config = {\n // phone\n 'default-code': 'autoDetect',\n // country-subdivision-city\n 'default-country': 'autoDetect',\n };\n Object.entries(config).forEach(([key, value]) => {\n Array.from(fragment.querySelectorAll(`[${key}=\"${value}\"]`)).forEach(\n (ele) => {\n ele.setAttribute(key, countryCodeIso2 || value);\n },\n );\n });\n};\n\nexport const setComponentsAutoDetectByLocale = (\n fragment: DocumentFragment,\n locale?: string, // e.g. 'en-US', 'fr-FR'\n) => {\n const config = {\n // country-subdivision-city\n lang: 'autoDetect',\n };\n\n let canonicalLocale = locale;\n if (locale) {\n try {\n const [canonical] = Intl.getCanonicalLocales(locale);\n if (canonical) {\n canonicalLocale = canonical;\n }\n } catch {\n // locale is not valid, keep original value\n }\n }\n\n Object.entries(config).forEach(([key, value]) => {\n Array.from(fragment.querySelectorAll(`[${key}=\"${value}\"]`)).forEach(\n (ele) => {\n ele.setAttribute(key, canonicalLocale || value);\n },\n );\n });\n};\n\nexport const disableWebauthnButtons = (fragment: DocumentFragment) => {\n const webauthnButtons = fragment.querySelectorAll(\n `descope-button[${ELEMENT_TYPE_ATTRIBUTE}=\"biometrics\"]`,\n );\n webauthnButtons.forEach((button) => button.setAttribute('disabled', 'true'));\n};\n\nexport const getDescopeUiComponentsList = (clone: DocumentFragment) => [\n ...Array.from(clone.querySelectorAll('*')).reduce<Set<string>>(\n (acc, el: HTMLElement) =>\n el.tagName.startsWith('DESCOPE-')\n ? acc.add(el.tagName.toLocaleLowerCase())\n : acc,\n new Set(),\n ),\n];\n"],"names":["ALLOWED_INPUT_CONFIG_ATTRS","replaceElementInputs","baseEle","screenInputs","Object","entries","forEach","name","value","Array","from","querySelectorAll","DESCOPE_ATTRIBUTE_EXCLUDE_FIELD","inputEle","getByPath","obj","path","split","reduce","prev","next","applyTemplates","text","screenState","handleMarkdown","replace","_","match","escapeMarkdown","String","replaceHrefByDataType","dataType","provisionUrl","ELEMENT_TYPE_ATTRIBUTE","ele","setAttribute","setImageVariable","rootEle","image","imageVarName","_a","customElements","get","cssVarList","url","_b","style","setProperty","fragment","button","eleType","message","textContent","classList","countryCodeIso2","key","locale","canonicalLocale","canonical","Intl","getCanonicalLocales","lang","nextPageTemplate","cssVars","logger","keys","componentName","querySelector","debug","componentClass","cssVarKey","componentCssVars","varName","info","inputs","form","flowInputs","totp","notp","redirectUrl","inEle","shouldHandleMarkdown","localName","href","getAttribute","replaceElementTemplates","componentsConfig","componentsDynamicAttrs","rest","__rest","configMap","acc","componentSelector","componentDynamicAttrs","attributes","length","componentsSelector","comp","config","attr","JSON","stringify","e","error","setElementConfig","HAS_DYNAMIC_VALUES_ATTR_NAME","replaceTemplateDynamicAttrValues","formData","attrName","attrValue","includes","setFormConfigValues"],"mappings":"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"}
@@ -1,2 +1,2 @@
1
- export{ASSETS_FOLDER,BASE_CONTENT_URL,CONFIG_FILENAME,OVERRIDE_CONTENT_URL,PREV_VER_ASSETS_FOLDER}from"./content.js";export{UI_COMPONENTS_URL_KEY}from"./uiComponents.js";const e="descope-login-flow",t="t",a="code",_="redirect_mode",d="err",i="popup_opener_origin",o="ra-challenge",s="ra-callback",r="ra-backup-callback",p="ra-initiator",l="data-descope-",c="data-exclude-field",n="data-exclude-next",u="dls_last_auth",m="dls_last_submitted_login_id",h="dls_sso_query_params",E=6e5,b=864e5,g="dls_sso_run_",R="data-opt-in-last-used-auth",S="state_id",x="saml_idp_state_id",N="wsfed_idp_state_id",O="saml_idp_username",C="descope_idp_initiated",T="sso_app_id",f="custom_app_id",w="third_party_app_id",y="third_party_app_state_id",F="oidc_login_hint",L="oidc_prompt",k="oidc_resource",A="oidc_error_redirect_uri",I="application_scopes",U="data-type",v="sdkScriptsResults",B={redirect:"redirect",poll:"poll",webauthnCreate:"webauthnCreate",webauthnGet:"webauthnGet",nativeBridge:"nativeBridge",loadForm:"loadForm"},D={submit:"submit",polling:"polling"},G="data-has-dynamic-attr-values",V=["descope-multi-select-combo-box","descope-text-area"],j=5e3,M=9e4,P='descope-attachment[data-type="last-auth-badge"]',q="dls_last_auth_in_flight";export{I as APPLICATION_SCOPES_PARAM_NAME,f as CUSTOM_APP_ID_PARAM_NAME,D as CUSTOM_INTERACTIONS,c as DESCOPE_ATTRIBUTE_EXCLUDE_FIELD,n as DESCOPE_ATTRIBUTE_EXCLUDE_NEXT_BUTTON,R as DESCOPE_ATTRIBUTE_OPT_IN_LAST_USED,l as DESCOPE_ATTRIBUTE_PREFIX,C as DESCOPE_IDP_INITIATED_PARAM_NAME,P as DESCOPE_LAST_AUTH_BADGE_COMPONENT,q as DESCOPE_LAST_AUTH_IN_FLIGHT_LOCAL_STORAGE_KEY,u as DESCOPE_LAST_AUTH_LOCAL_STORAGE_KEY,m as DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY,h as DESCOPE_SSO_QUERY_PARAMS_SESSION_STORAGE_KEY_PREFIX,g as DESCOPE_SSO_RUN_STORAGE_KEY_PREFIX,V as ELEMENTS_TO_IGNORE_ENTER_KEY_ON,U as ELEMENT_TYPE_ATTRIBUTE,G as HAS_DYNAMIC_VALUES_ATTR_NAME,A as OIDC_ERROR_REDIRECT_URI_PARAM_NAME,S as OIDC_IDP_STATE_ID_PARAM_NAME,F as OIDC_LOGIN_HINT_PARAM_NAME,L as OIDC_PROMPT_PARAM_NAME,k as OIDC_RESOURCE_PARAM_NAME,B as RESPONSE_ACTIONS,x as SAML_IDP_STATE_ID_PARAM_NAME,O as SAML_IDP_USERNAME_PARAM_NAME,j as SDK_SCRIPTS_LOAD_TIMEOUT,v as SDK_SCRIPT_RESULTS_KEY,T as SSO_APP_ID_PARAM_NAME,E as SSO_QUERY_PARAMS_MAX_AGE_MS,b as SSO_QUERY_PARAMS_WITH_ERROR_REDIRECT_MAX_AGE_MS,w as THIRD_PARTY_APP_ID_PARAM_NAME,y as THIRD_PARTY_APP_STATE_ID_PARAM_NAME,a as URL_CODE_PARAM_NAME,d as URL_ERR_PARAM_NAME,i as URL_POPUP_OPENER_ORIGIN_PARAM_NAME,r as URL_REDIRECT_AUTH_BACKUP_CALLBACK_PARAM_NAME,s as URL_REDIRECT_AUTH_CALLBACK_PARAM_NAME,o as URL_REDIRECT_AUTH_CHALLENGE_PARAM_NAME,p as URL_REDIRECT_AUTH_INITIATOR_PARAM_NAME,_ as URL_REDIRECT_MODE_PARAM_NAME,e as URL_RUN_IDS_PARAM_NAME,t as URL_TOKEN_PARAM_NAME,M as WEBAUTHN_TIMEOUT,N as WSFED_IDP_STATE_ID_PARAM_NAME};
1
+ export{ASSETS_FOLDER,BASE_CONTENT_URL,CONFIG_FILENAME,OVERRIDE_CONTENT_URL,PREV_VER_ASSETS_FOLDER}from"./content.js";export{UI_COMPONENTS_URL_KEY}from"./uiComponents.js";const e="descope-login-flow",t="t",a="code",_="redirect_mode",d="err",i="popup_opener_origin",s="ra-challenge",o="ra-callback",r="ra-backup-callback",l="ra-initiator",p="data-descope-",c="data-exclude-field",n="data-exclude-next",u="dls_last_auth",m="dls_last_submitted_login_id",h="dls_sso_query_params",E=6e5,b=864e5,g="dls_sso_run_",R="data-opt-in-last-used-auth",S="state_id",x="saml_idp_state_id",N="wsfed_idp_state_id",O="saml_idp_username",C="descope_idp_initiated",T="sso_app_id",f="custom_app_id",w="third_party_app_id",y="third_party_app_state_id",F="oidc_login_hint",L="oidc_prompt",k="oidc_resource",A="oidc_error_redirect_uri",I="application_scopes",U="data-type",v="sdkScriptsResults",B={redirect:"redirect",poll:"poll",webauthnCreate:"webauthnCreate",webauthnGet:"webauthnGet",nativeBridge:"nativeBridge",loadForm:"loadForm"},D={submit:"submit",polling:"polling"},G="data-has-dynamic-attr-values",V=["descope-multi-select-combo-box","descope-text-area"],j=5e3,M="clientSignals",P=9e4,q='descope-attachment[data-type="last-auth-badge"]',K="dls_last_auth_in_flight";export{I as APPLICATION_SCOPES_PARAM_NAME,M as CLIENT_SIGNALS_SCRIPT_ID,f as CUSTOM_APP_ID_PARAM_NAME,D as CUSTOM_INTERACTIONS,c as DESCOPE_ATTRIBUTE_EXCLUDE_FIELD,n as DESCOPE_ATTRIBUTE_EXCLUDE_NEXT_BUTTON,R as DESCOPE_ATTRIBUTE_OPT_IN_LAST_USED,p as DESCOPE_ATTRIBUTE_PREFIX,C as DESCOPE_IDP_INITIATED_PARAM_NAME,q as DESCOPE_LAST_AUTH_BADGE_COMPONENT,K as DESCOPE_LAST_AUTH_IN_FLIGHT_LOCAL_STORAGE_KEY,u as DESCOPE_LAST_AUTH_LOCAL_STORAGE_KEY,m as DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY,h as DESCOPE_SSO_QUERY_PARAMS_SESSION_STORAGE_KEY_PREFIX,g as DESCOPE_SSO_RUN_STORAGE_KEY_PREFIX,V as ELEMENTS_TO_IGNORE_ENTER_KEY_ON,U as ELEMENT_TYPE_ATTRIBUTE,G as HAS_DYNAMIC_VALUES_ATTR_NAME,A as OIDC_ERROR_REDIRECT_URI_PARAM_NAME,S as OIDC_IDP_STATE_ID_PARAM_NAME,F as OIDC_LOGIN_HINT_PARAM_NAME,L as OIDC_PROMPT_PARAM_NAME,k as OIDC_RESOURCE_PARAM_NAME,B as RESPONSE_ACTIONS,x as SAML_IDP_STATE_ID_PARAM_NAME,O as SAML_IDP_USERNAME_PARAM_NAME,j as SDK_SCRIPTS_LOAD_TIMEOUT,v as SDK_SCRIPT_RESULTS_KEY,T as SSO_APP_ID_PARAM_NAME,E as SSO_QUERY_PARAMS_MAX_AGE_MS,b as SSO_QUERY_PARAMS_WITH_ERROR_REDIRECT_MAX_AGE_MS,w as THIRD_PARTY_APP_ID_PARAM_NAME,y as THIRD_PARTY_APP_STATE_ID_PARAM_NAME,a as URL_CODE_PARAM_NAME,d as URL_ERR_PARAM_NAME,i as URL_POPUP_OPENER_ORIGIN_PARAM_NAME,r as URL_REDIRECT_AUTH_BACKUP_CALLBACK_PARAM_NAME,o as URL_REDIRECT_AUTH_CALLBACK_PARAM_NAME,s as URL_REDIRECT_AUTH_CHALLENGE_PARAM_NAME,l as URL_REDIRECT_AUTH_INITIATOR_PARAM_NAME,_ as URL_REDIRECT_MODE_PARAM_NAME,e as URL_RUN_IDS_PARAM_NAME,t as URL_TOKEN_PARAM_NAME,P as WEBAUTHN_TIMEOUT,N as WSFED_IDP_STATE_ID_PARAM_NAME};
2
2
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../../../src/lib/constants/index.ts"],"sourcesContent":["export * from './general';\nexport * from './content';\nexport * from './uiComponents';\n\nexport const URL_RUN_IDS_PARAM_NAME = 'descope-login-flow';\nexport const URL_TOKEN_PARAM_NAME = 't';\nexport const URL_CODE_PARAM_NAME = 'code';\nexport const URL_REDIRECT_MODE_PARAM_NAME = 'redirect_mode';\nexport const URL_ERR_PARAM_NAME = 'err';\nexport const URL_POPUP_OPENER_ORIGIN_PARAM_NAME = 'popup_opener_origin';\nexport const URL_REDIRECT_AUTH_CHALLENGE_PARAM_NAME = 'ra-challenge';\nexport const URL_REDIRECT_AUTH_CALLBACK_PARAM_NAME = 'ra-callback';\nexport const URL_REDIRECT_AUTH_BACKUP_CALLBACK_PARAM_NAME =\n 'ra-backup-callback';\nexport const URL_REDIRECT_AUTH_INITIATOR_PARAM_NAME = 'ra-initiator';\nexport const DESCOPE_ATTRIBUTE_PREFIX = 'data-descope-';\nexport const DESCOPE_ATTRIBUTE_EXCLUDE_FIELD = 'data-exclude-field';\nexport const DESCOPE_ATTRIBUTE_EXCLUDE_NEXT_BUTTON = 'data-exclude-next';\nexport const DESCOPE_LAST_AUTH_LOCAL_STORAGE_KEY = 'dls_last_auth';\nexport const DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY =\n 'dls_last_submitted_login_id';\n// prefix only, the project and flow are appended so two flows on one page do\n// not overwrite each other\nexport const DESCOPE_SSO_QUERY_PARAMS_SESSION_STORAGE_KEY_PREFIX =\n 'dls_sso_query_params';\n// matches the server side state lifetime\nexport const SSO_QUERY_PARAMS_MAX_AGE_MS = 10 * 60 * 1000;\n// an OIDC context that carries the app's error redirect is still worth\n// restoring after the state expired: the server then sends the user back to the\n// app with \"session expired\" instead of leaving them on the login page\nexport const SSO_QUERY_PARAMS_WITH_ERROR_REDIRECT_MAX_AGE_MS =\n 24 * 60 * 60 * 1000;\n// prefix only, the id part of the execution id is appended. Shared by all tabs\n// of the origin, so a page opened from a magic link can find the OIDC context\n// of the run it continues\nexport const DESCOPE_SSO_RUN_STORAGE_KEY_PREFIX = 'dls_sso_run_';\nexport const DESCOPE_ATTRIBUTE_OPT_IN_LAST_USED = 'data-opt-in-last-used-auth';\n\n// SSO query params\nexport const OIDC_IDP_STATE_ID_PARAM_NAME = 'state_id';\nexport const SAML_IDP_STATE_ID_PARAM_NAME = 'saml_idp_state_id';\nexport const WSFED_IDP_STATE_ID_PARAM_NAME = 'wsfed_idp_state_id';\nexport const SAML_IDP_USERNAME_PARAM_NAME = 'saml_idp_username';\nexport const DESCOPE_IDP_INITIATED_PARAM_NAME = 'descope_idp_initiated';\nexport const SSO_APP_ID_PARAM_NAME = 'sso_app_id';\nexport const CUSTOM_APP_ID_PARAM_NAME = 'custom_app_id';\nexport const THIRD_PARTY_APP_ID_PARAM_NAME = 'third_party_app_id';\nexport const THIRD_PARTY_APP_STATE_ID_PARAM_NAME = 'third_party_app_state_id';\nexport const OIDC_LOGIN_HINT_PARAM_NAME = 'oidc_login_hint';\nexport const OIDC_PROMPT_PARAM_NAME = 'oidc_prompt';\nexport const OIDC_RESOURCE_PARAM_NAME = 'oidc_resource';\nexport const OIDC_ERROR_REDIRECT_URI_PARAM_NAME = 'oidc_error_redirect_uri';\nexport const APPLICATION_SCOPES_PARAM_NAME = 'application_scopes';\n\nexport const ELEMENT_TYPE_ATTRIBUTE = 'data-type';\n\nexport const SDK_SCRIPT_RESULTS_KEY = 'sdkScriptsResults';\n\nexport const RESPONSE_ACTIONS = {\n redirect: 'redirect',\n poll: 'poll',\n webauthnCreate: 'webauthnCreate',\n webauthnGet: 'webauthnGet',\n nativeBridge: 'nativeBridge',\n loadForm: 'loadForm',\n};\n\nexport const CUSTOM_INTERACTIONS = {\n submit: 'submit',\n polling: 'polling',\n};\n\nexport const HAS_DYNAMIC_VALUES_ATTR_NAME = 'data-has-dynamic-attr-values';\n\nexport const ELEMENTS_TO_IGNORE_ENTER_KEY_ON = [\n 'descope-multi-select-combo-box',\n 'descope-text-area',\n];\n\nexport const SDK_SCRIPTS_LOAD_TIMEOUT = 5000;\n\n// Password manager extensions can leave navigator.credentials.get/create\n// pending for minutes after their prompt is dismissed, with no signal we can\n// observe. Long on purpose, so a slow but genuine passkey is not cut off.\nexport const WEBAUTHN_TIMEOUT = 90000;\n\nexport const DESCOPE_LAST_AUTH_BADGE_COMPONENT =\n 'descope-attachment[data-type=\"last-auth-badge\"]';\n\nexport const DESCOPE_LAST_AUTH_IN_FLIGHT_LOCAL_STORAGE_KEY =\n 'dls_last_auth_in_flight';\n"],"names":["URL_RUN_IDS_PARAM_NAME","URL_TOKEN_PARAM_NAME","URL_CODE_PARAM_NAME","URL_REDIRECT_MODE_PARAM_NAME","URL_ERR_PARAM_NAME","URL_POPUP_OPENER_ORIGIN_PARAM_NAME","URL_REDIRECT_AUTH_CHALLENGE_PARAM_NAME","URL_REDIRECT_AUTH_CALLBACK_PARAM_NAME","URL_REDIRECT_AUTH_BACKUP_CALLBACK_PARAM_NAME","URL_REDIRECT_AUTH_INITIATOR_PARAM_NAME","DESCOPE_ATTRIBUTE_PREFIX","DESCOPE_ATTRIBUTE_EXCLUDE_FIELD","DESCOPE_ATTRIBUTE_EXCLUDE_NEXT_BUTTON","DESCOPE_LAST_AUTH_LOCAL_STORAGE_KEY","DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY","DESCOPE_SSO_QUERY_PARAMS_SESSION_STORAGE_KEY_PREFIX","SSO_QUERY_PARAMS_MAX_AGE_MS","SSO_QUERY_PARAMS_WITH_ERROR_REDIRECT_MAX_AGE_MS","DESCOPE_SSO_RUN_STORAGE_KEY_PREFIX","DESCOPE_ATTRIBUTE_OPT_IN_LAST_USED","OIDC_IDP_STATE_ID_PARAM_NAME","SAML_IDP_STATE_ID_PARAM_NAME","WSFED_IDP_STATE_ID_PARAM_NAME","SAML_IDP_USERNAME_PARAM_NAME","DESCOPE_IDP_INITIATED_PARAM_NAME","SSO_APP_ID_PARAM_NAME","CUSTOM_APP_ID_PARAM_NAME","THIRD_PARTY_APP_ID_PARAM_NAME","THIRD_PARTY_APP_STATE_ID_PARAM_NAME","OIDC_LOGIN_HINT_PARAM_NAME","OIDC_PROMPT_PARAM_NAME","OIDC_RESOURCE_PARAM_NAME","OIDC_ERROR_REDIRECT_URI_PARAM_NAME","APPLICATION_SCOPES_PARAM_NAME","ELEMENT_TYPE_ATTRIBUTE","SDK_SCRIPT_RESULTS_KEY","RESPONSE_ACTIONS","redirect","poll","webauthnCreate","webauthnGet","nativeBridge","loadForm","CUSTOM_INTERACTIONS","submit","polling","HAS_DYNAMIC_VALUES_ATTR_NAME","ELEMENTS_TO_IGNORE_ENTER_KEY_ON","SDK_SCRIPTS_LOAD_TIMEOUT","WEBAUTHN_TIMEOUT","DESCOPE_LAST_AUTH_BADGE_COMPONENT","DESCOPE_LAST_AUTH_IN_FLIGHT_LOCAL_STORAGE_KEY"],"mappings":"0KAIO,MAAMA,EAAyB,qBACzBC,EAAuB,IACvBC,EAAsB,OACtBC,EAA+B,gBAC/BC,EAAqB,MACrBC,EAAqC,sBACrCC,EAAyC,eACzCC,EAAwC,cACxCC,EACX,qBACWC,EAAyC,eACzCC,EAA2B,gBAC3BC,EAAkC,qBAClCC,EAAwC,oBACxCC,EAAsC,gBACtCC,EACX,8BAGWC,EACX,uBAEWC,EAA8B,IAI9BC,EACX,MAIWC,EAAqC,eACrCC,EAAqC,6BAGrCC,EAA+B,WAC/BC,EAA+B,oBAC/BC,EAAgC,qBAChCC,EAA+B,oBAC/BC,EAAmC,wBACnCC,EAAwB,aACxBC,EAA2B,gBAC3BC,EAAgC,qBAChCC,EAAsC,2BACtCC,EAA6B,kBAC7BC,EAAyB,cACzBC,EAA2B,gBAC3BC,EAAqC,0BACrCC,EAAgC,qBAEhCC,EAAyB,YAEzBC,EAAyB,oBAEzBC,EAAmB,CAC9BC,SAAU,WACVC,KAAM,OACNC,eAAgB,iBAChBC,YAAa,cACbC,aAAc,eACdC,SAAU,YAGCC,EAAsB,CACjCC,OAAQ,SACRC,QAAS,WAGEC,EAA+B,+BAE/BC,EAAkC,CAC7C,iCACA,qBAGWC,EAA2B,IAK3BC,EAAmB,IAEnBC,EACX,kDAEWC,EACX"}
1
+ {"version":3,"file":"index.js","sources":["../../../src/lib/constants/index.ts"],"sourcesContent":["export * from './general';\nexport * from './content';\nexport * from './uiComponents';\n\nexport const URL_RUN_IDS_PARAM_NAME = 'descope-login-flow';\nexport const URL_TOKEN_PARAM_NAME = 't';\nexport const URL_CODE_PARAM_NAME = 'code';\nexport const URL_REDIRECT_MODE_PARAM_NAME = 'redirect_mode';\nexport const URL_ERR_PARAM_NAME = 'err';\nexport const URL_POPUP_OPENER_ORIGIN_PARAM_NAME = 'popup_opener_origin';\nexport const URL_REDIRECT_AUTH_CHALLENGE_PARAM_NAME = 'ra-challenge';\nexport const URL_REDIRECT_AUTH_CALLBACK_PARAM_NAME = 'ra-callback';\nexport const URL_REDIRECT_AUTH_BACKUP_CALLBACK_PARAM_NAME =\n 'ra-backup-callback';\nexport const URL_REDIRECT_AUTH_INITIATOR_PARAM_NAME = 'ra-initiator';\nexport const DESCOPE_ATTRIBUTE_PREFIX = 'data-descope-';\nexport const DESCOPE_ATTRIBUTE_EXCLUDE_FIELD = 'data-exclude-field';\nexport const DESCOPE_ATTRIBUTE_EXCLUDE_NEXT_BUTTON = 'data-exclude-next';\nexport const DESCOPE_LAST_AUTH_LOCAL_STORAGE_KEY = 'dls_last_auth';\nexport const DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY =\n 'dls_last_submitted_login_id';\n// prefix only, the project and flow are appended so two flows on one page do\n// not overwrite each other\nexport const DESCOPE_SSO_QUERY_PARAMS_SESSION_STORAGE_KEY_PREFIX =\n 'dls_sso_query_params';\n// matches the server side state lifetime\nexport const SSO_QUERY_PARAMS_MAX_AGE_MS = 10 * 60 * 1000;\n// an OIDC context that carries the app's error redirect is still worth\n// restoring after the state expired: the server then sends the user back to the\n// app with \"session expired\" instead of leaving them on the login page\nexport const SSO_QUERY_PARAMS_WITH_ERROR_REDIRECT_MAX_AGE_MS =\n 24 * 60 * 60 * 1000;\n// prefix only, the id part of the execution id is appended. Shared by all tabs\n// of the origin, so a page opened from a magic link can find the OIDC context\n// of the run it continues\nexport const DESCOPE_SSO_RUN_STORAGE_KEY_PREFIX = 'dls_sso_run_';\nexport const DESCOPE_ATTRIBUTE_OPT_IN_LAST_USED = 'data-opt-in-last-used-auth';\n\n// SSO query params\nexport const OIDC_IDP_STATE_ID_PARAM_NAME = 'state_id';\nexport const SAML_IDP_STATE_ID_PARAM_NAME = 'saml_idp_state_id';\nexport const WSFED_IDP_STATE_ID_PARAM_NAME = 'wsfed_idp_state_id';\nexport const SAML_IDP_USERNAME_PARAM_NAME = 'saml_idp_username';\nexport const DESCOPE_IDP_INITIATED_PARAM_NAME = 'descope_idp_initiated';\nexport const SSO_APP_ID_PARAM_NAME = 'sso_app_id';\nexport const CUSTOM_APP_ID_PARAM_NAME = 'custom_app_id';\nexport const THIRD_PARTY_APP_ID_PARAM_NAME = 'third_party_app_id';\nexport const THIRD_PARTY_APP_STATE_ID_PARAM_NAME = 'third_party_app_state_id';\nexport const OIDC_LOGIN_HINT_PARAM_NAME = 'oidc_login_hint';\nexport const OIDC_PROMPT_PARAM_NAME = 'oidc_prompt';\nexport const OIDC_RESOURCE_PARAM_NAME = 'oidc_resource';\nexport const OIDC_ERROR_REDIRECT_URI_PARAM_NAME = 'oidc_error_redirect_uri';\nexport const APPLICATION_SCOPES_PARAM_NAME = 'application_scopes';\n\nexport const ELEMENT_TYPE_ATTRIBUTE = 'data-type';\n\nexport const SDK_SCRIPT_RESULTS_KEY = 'sdkScriptsResults';\n\nexport const RESPONSE_ACTIONS = {\n redirect: 'redirect',\n poll: 'poll',\n webauthnCreate: 'webauthnCreate',\n webauthnGet: 'webauthnGet',\n nativeBridge: 'nativeBridge',\n loadForm: 'loadForm',\n};\n\nexport const CUSTOM_INTERACTIONS = {\n submit: 'submit',\n polling: 'polling',\n};\n\nexport const HAS_DYNAMIC_VALUES_ATTR_NAME = 'data-has-dynamic-attr-values';\n\nexport const ELEMENTS_TO_IGNORE_ENTER_KEY_ON = [\n 'descope-multi-select-combo-box',\n 'descope-text-area',\n];\n\nexport const SDK_SCRIPTS_LOAD_TIMEOUT = 5000;\n\n// The script id of the client-signals connector (content repo,\n// connectors/templates/client-signals/metadata.json). Not loaded in preview.\nexport const CLIENT_SIGNALS_SCRIPT_ID = 'clientSignals';\n\n// Password manager extensions can leave navigator.credentials.get/create\n// pending for minutes after their prompt is dismissed, with no signal we can\n// observe. Long on purpose, so a slow but genuine passkey is not cut off.\nexport const WEBAUTHN_TIMEOUT = 90000;\n\nexport const DESCOPE_LAST_AUTH_BADGE_COMPONENT =\n 'descope-attachment[data-type=\"last-auth-badge\"]';\n\nexport const DESCOPE_LAST_AUTH_IN_FLIGHT_LOCAL_STORAGE_KEY =\n 'dls_last_auth_in_flight';\n"],"names":["URL_RUN_IDS_PARAM_NAME","URL_TOKEN_PARAM_NAME","URL_CODE_PARAM_NAME","URL_REDIRECT_MODE_PARAM_NAME","URL_ERR_PARAM_NAME","URL_POPUP_OPENER_ORIGIN_PARAM_NAME","URL_REDIRECT_AUTH_CHALLENGE_PARAM_NAME","URL_REDIRECT_AUTH_CALLBACK_PARAM_NAME","URL_REDIRECT_AUTH_BACKUP_CALLBACK_PARAM_NAME","URL_REDIRECT_AUTH_INITIATOR_PARAM_NAME","DESCOPE_ATTRIBUTE_PREFIX","DESCOPE_ATTRIBUTE_EXCLUDE_FIELD","DESCOPE_ATTRIBUTE_EXCLUDE_NEXT_BUTTON","DESCOPE_LAST_AUTH_LOCAL_STORAGE_KEY","DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY","DESCOPE_SSO_QUERY_PARAMS_SESSION_STORAGE_KEY_PREFIX","SSO_QUERY_PARAMS_MAX_AGE_MS","SSO_QUERY_PARAMS_WITH_ERROR_REDIRECT_MAX_AGE_MS","DESCOPE_SSO_RUN_STORAGE_KEY_PREFIX","DESCOPE_ATTRIBUTE_OPT_IN_LAST_USED","OIDC_IDP_STATE_ID_PARAM_NAME","SAML_IDP_STATE_ID_PARAM_NAME","WSFED_IDP_STATE_ID_PARAM_NAME","SAML_IDP_USERNAME_PARAM_NAME","DESCOPE_IDP_INITIATED_PARAM_NAME","SSO_APP_ID_PARAM_NAME","CUSTOM_APP_ID_PARAM_NAME","THIRD_PARTY_APP_ID_PARAM_NAME","THIRD_PARTY_APP_STATE_ID_PARAM_NAME","OIDC_LOGIN_HINT_PARAM_NAME","OIDC_PROMPT_PARAM_NAME","OIDC_RESOURCE_PARAM_NAME","OIDC_ERROR_REDIRECT_URI_PARAM_NAME","APPLICATION_SCOPES_PARAM_NAME","ELEMENT_TYPE_ATTRIBUTE","SDK_SCRIPT_RESULTS_KEY","RESPONSE_ACTIONS","redirect","poll","webauthnCreate","webauthnGet","nativeBridge","loadForm","CUSTOM_INTERACTIONS","submit","polling","HAS_DYNAMIC_VALUES_ATTR_NAME","ELEMENTS_TO_IGNORE_ENTER_KEY_ON","SDK_SCRIPTS_LOAD_TIMEOUT","CLIENT_SIGNALS_SCRIPT_ID","WEBAUTHN_TIMEOUT","DESCOPE_LAST_AUTH_BADGE_COMPONENT","DESCOPE_LAST_AUTH_IN_FLIGHT_LOCAL_STORAGE_KEY"],"mappings":"0KAIO,MAAMA,EAAyB,qBACzBC,EAAuB,IACvBC,EAAsB,OACtBC,EAA+B,gBAC/BC,EAAqB,MACrBC,EAAqC,sBACrCC,EAAyC,eACzCC,EAAwC,cACxCC,EACX,qBACWC,EAAyC,eACzCC,EAA2B,gBAC3BC,EAAkC,qBAClCC,EAAwC,oBACxCC,EAAsC,gBACtCC,EACX,8BAGWC,EACX,uBAEWC,EAA8B,IAI9BC,EACX,MAIWC,EAAqC,eACrCC,EAAqC,6BAGrCC,EAA+B,WAC/BC,EAA+B,oBAC/BC,EAAgC,qBAChCC,EAA+B,oBAC/BC,EAAmC,wBACnCC,EAAwB,aACxBC,EAA2B,gBAC3BC,EAAgC,qBAChCC,EAAsC,2BACtCC,EAA6B,kBAC7BC,EAAyB,cACzBC,EAA2B,gBAC3BC,EAAqC,0BACrCC,EAAgC,qBAEhCC,EAAyB,YAEzBC,EAAyB,oBAEzBC,EAAmB,CAC9BC,SAAU,WACVC,KAAM,OACNC,eAAgB,iBAChBC,YAAa,cACbC,aAAc,eACdC,SAAU,YAGCC,EAAsB,CACjCC,OAAQ,SACRC,QAAS,WAGEC,EAA+B,+BAE/BC,EAAkC,CAC7C,iCACA,qBAGWC,EAA2B,IAI3BC,EAA2B,gBAK3BC,EAAmB,IAEnBC,EACX,kDAEWC,EACX"}
@@ -1,2 +1,2 @@
1
- import{__classPrivateFieldGet as t,__awaiter as e,__classPrivateFieldSet as i}from"tslib";import{compose as s}from"@descope/sdk-helpers";import{staticResourcesMixin as r}from"@descope/sdk-mixins/static-resources-mixin";import{themeMixin as o}from"@descope/sdk-mixins/theme-mixin";import{injectStyleMixin as n}from"@descope/sdk-mixins/inject-style-mixin";import{telemetryMixin as a}from"@descope/sdk-mixins/telemetry-mixin";import{createSdk as u,getSessionToken as l}from"@descope/web-js-sdk";import{ELEMENTS_TO_IGNORE_ENTER_KEY_ON as d}from"../constants/index.js";import{handleUrlParams as h,clearRunIdsFromUrl as c,camelCase as f,getRunIdsFromUrl as g,getContentUrl as p,fetchContent as m,withRetry as v}from"../helpers/helpers.js";import b from"../helpers/state.js";import"@descope/escape-markdown";import"../helpers/webauthn.js";import{setCustomStorage as w}from"../helpers/storage.js";import{transformFlowInputFormData as k,extractNestedAttribute as y}from"../helpers/flowInputs.js";import{formMountMixin as C}from"../mixins/formMountMixin.js";import{componentConditionsMixin as x}from"../mixins/componentConditionsMixin.js";import{duplicateFlowWarningMixin as A}from"../mixins/duplicateFlowWarningMixin.js";import{passwordManagerMixin as j}from"../mixins/passwordManagerMixin.js";import{emailVerificationMixin as I}from"../mixins/emailVerificationMixin.js";import{validationTrackingMixin as E}from"../mixins/validationTrackingMixin.js";import{CONFIG_FILENAME as M,PREV_VER_ASSETS_FOLDER as S}from"../constants/content.js";import{FETCH_EXCEPTION_ERROR_CODE as L}from"../constants/general.js";var U,O,P,W,D,N,T,F,K,R,V,z,J,B,H,Q,q,$,G,X,Y,Z,_,tt,et,it,st;const rt=s(o,r,C,x,A,j,I,n,a,E)(HTMLElement);class ot extends rt{static get observedAttributes(){return["project-id","flow-id","base-url","tenant","locale","debug","storage-prefix","preview","redirect-url","auto-focus","store-last-authenticated-user","refresh-cookie-name","keep-last-authenticated-user-after-logout","validate-on-blur","send-session-token","style-id"]}get adoptedSsoQueryParams(){return t(this,D,"f")}constructor(s){super(),U.add(this),this.sdkVersion="4.7.4",P.set(this,!1),W.set(this,void 0),D.set(this,null),this.flowStatus="initial",this.loggerWrapper={error:(e,i="")=>{this.logger.error(e,i,new Error),t(this,U,"m",st).call(this,e,i)},warn:(t,e="")=>{this.logger.warn(t,e)},info:(t,e="",i={})=>{this.logger.info(t,e,i)},debug:(t,e="")=>{this.logger.debug(t,e)}},N.set(this,new b),T.set(this,new b),F.set(this,{}),this.getComponentsContext=()=>t(this,F,"f"),this.nextRequestStatus=new b({isLoading:!1}),K.set(this,void 0),R.set(this,{popstate:t(this,U,"m",H).bind(this),componentsContext:t(this,U,"m",Y).bind(this)}),V.set(this,void 0),this.getConfig=()=>e(this,void 0,void 0,(function*(){return(yield this.config)||{isMissingConfig:!0}})),Z.set(this,void 0),_.set(this,void 0),i(this,V,s,"f"),t(this,U,"m",J).call(this)}get client(){try{return JSON.parse(this.getAttribute("client"))||{}}catch(t){return{}}}get redirectUrl(){return this.getAttribute("redirect-url")||void 0}get debug(){return"true"===this.getAttribute("debug")}get locale(){return this.getAttribute("locale")||void 0}get autoFocus(){var t;const e=null!==(t=this.getAttribute("auto-focus"))&&void 0!==t?t:"true";return"skipFirstScreen"===e?e:"true"===e}get validateOnBlur(){return"true"===this.getAttribute("validate-on-blur")}get storeLastAuthenticatedUser(){var t;return"true"===(null!==(t=this.getAttribute("store-last-authenticated-user"))&&void 0!==t?t:"true")}get refreshCookieName(){return this.getAttribute("refresh-cookie-name")||""}get keepLastAuthenticatedUserAfterLogout(){return"true"===this.getAttribute("keep-last-authenticated-user-after-logout")}get storagePrefix(){return this.getAttribute("storage-prefix")||""}get sendSessionToken(){return"true"===this.getAttribute("send-session-token")}get preview(){return!!this.getAttribute("preview")}get formConfig(){return k(this.form)}get form(){return this.getAttribute("form")}get formConfigValues(){return y(this.formConfig,"value")}get outboundAppId(){return this.getAttribute("outbound-app-id")}get outboundAppScopes(){try{const t=JSON.parse(this.getAttribute("outbound-app-scopes"));return t||null}catch(t){return null}}get popupOrigin(){return this.getAttribute("popup-origin")}get customStorage(){return t(this,W,"f")}set customStorage(t){if(t&&"function"!=typeof t.getItem)throw new Error("Custom storage must have a getItem method");if(t&&"function"!=typeof t.setItem)throw new Error("Custom storage must have a setItem method");if(t&&"function"!=typeof t.removeItem)throw new Error("Custom storage must have a removeItem method");i(this,W,t,"f"),w(t)}get lazyStart(){return"true"===this.getAttribute("lazy-start")}start(){var e;null===(e=t(this,_,"f"))||void 0===e||e.call(this),i(this,Z,Promise.resolve(),"f")}get isRestartOnError(){return"true"===this.getAttribute("restart-on-error")}getExecutionContext(){return e(this,void 0,void 0,(function*(){const t=yield this.getConfig();return"executionContext"in t?t.executionContext:void 0}))}getProjectConfig(){return e(this,void 0,void 0,(function*(){const t=yield this.getConfig();return"projectConfig"in t?t.projectConfig:void 0}))}getFlowConfig(){return e(this,void 0,void 0,(function*(){var t,e;const i=yield this.getProjectConfig(),s=(null===(t=null==i?void 0:i.flows)||void 0===t?void 0:t[this.flowId])||{};return null!==(e=s.version)&&void 0!==e||(s.version=0),s}))}getTargetLocales(){return e(this,void 0,void 0,(function*(){const t=yield this.getFlowConfig();return((null==t?void 0:t.targetLocales)||[]).map((t=>t.toLowerCase()))}))}handleKeyPress(){this.logger.debug("Enable key press handler"),this.rootElement.onkeydown=t=>{var e,i,s;const r=!!(null===(e=this.shadowRoot.activeElement)||void 0===e?void 0:e.getAttribute("href")),o=d.includes(null!==(s=null===(i=this.shadowRoot.activeElement)||void 0===i?void 0:i.localName)&&void 0!==s?s:"");if("Enter"!==t.key||t.defaultPrevented||r||o)return;t.preventDefault();const n=this.rootElement.querySelectorAll("descope-button");if(1===n.length&&"false"!==n[0].getAttribute("auto-submit"))return void n[0].click();const a=Array.from(n).filter((t=>"true"===t.getAttribute("auto-submit")));if(1===a.length)return void a[0].click();const u=Array.from(n).filter((t=>"button"===t.getAttribute("data-type")));if(1===u.length)"false"!==u[0].getAttribute("auto-submit")&&u[0].click();else if(0===u.length){const t=Array.from(n).filter((t=>"sso"===t.getAttribute("data-type")));1===t.length&&"false"!==t[0].getAttribute("auto-submit")&&t[0].click()}}}disableKeyPressHandler(){this.logger.debug("Disable key press handler"),this.rootElement.onkeydown=null}getComponentsVersion(){return e(this,void 0,void 0,(function*(){var t;const e=yield this.getConfig(),i="projectConfig"in e?null===(t=e.projectConfig)||void 0===t?void 0:t.componentsVersion:{};return i||(this.logger.error("Did not get components version, using latest version"),"latest")}))}init(){const s=Object.create(null,{init:{get:()=>super.init}});return e(this,void 0,void 0,(function*(){var e;if(this.flowStatus="loading",["ready","error","success"].forEach((t=>this.addEventListener(t,(()=>{this.flowStatus=t})))),yield null===(e=s.init)||void 0===e?void 0:e.call(this),t(this,T,"f").subscribe(t(this,U,"m",it).bind(this)),t(this,T,"f").update({isDebug:this.debug}),t(this,U,"m",B).call(this),yield t(this,U,"m",G).call(this))return void this.loggerWrapper.error("This SDK version does not support your flows version","Make sure to upgrade your flows to the latest version or use an older SDK version");const r=yield this.getConfig();if("isMissingConfig"in r&&r.isMissingConfig)return void this.loggerWrapper.error("Cannot get config file","Make sure that your projectId & flowId are correct");const{executionId:o,stepId:n,token:a,code:u,isPopup:l,exchangeError:d,redirectAuthCallbackUrl:c,redirectAuthBackupCallbackUri:f,redirectAuthCodeChallenge:g,redirectAuthInitiator:p,ssoQueryParams:m,adoptedSsoQueryParams:v}=h(this.flowId,this.projectId,this.loggerWrapper);i(this,D,null!=v?v:null,"f"),window.addEventListener("popstate",t(this,R,"f").popstate),window.addEventListener("components-context",t(this,R,"f").componentsContext),t(this,N,"f").subscribe(t(this,U,"m",$).bind(this)),t(this,N,"f").update(Object.assign({projectId:this.projectId,flowId:this.flowId,baseUrl:this.baseUrl,tenant:this.tenantId,redirectUrl:this.redirectUrl,locale:this.locale,stepId:n,executionId:o,token:a,code:u,isPopup:l,exchangeError:d,redirectAuthCallbackUrl:c,redirectAuthBackupCallbackUri:f,redirectAuthCodeChallenge:g,redirectAuthInitiator:p},m)),i(this,P,!0,"f")}))}disconnectedCallback(){var e;t(this,N,"f").unsubscribeAll(),t(this,T,"f").unsubscribeAll(),t(this,U,"m",et).call(this),window.removeEventListener("popstate",t(this,R,"f").popstate),window.removeEventListener("components-context",t(this,R,"f").componentsContext),null===(e=super.disconnectedCallback)||void 0===e||e.call(this)}attributeChangedCallback(e,i,s){var r;if(null===(r=super.attributeChangedCallback)||void 0===r||r.call(this,e,i,s),this.shadowRoot.isConnected&&t(this,P,"f")&&i!==s&&O.observedAttributes.includes(e)){t(this,U,"m",B).call(this);const r=null===i;t(this,N,"f").update((({stepId:t,executionId:i})=>{let o=t,n=i;return r||(n=null,o=null,c()),{[f(e)]:s,stepId:o,executionId:n}})),t(this,T,"f").update({isDebug:this.debug})}}}O=ot,P=new WeakMap,W=new WeakMap,D=new WeakMap,N=new WeakMap,T=new WeakMap,F=new WeakMap,K=new WeakMap,R=new WeakMap,V=new WeakMap,Z=new WeakMap,_=new WeakMap,U=new WeakSet,z=function(){this.injectStyle("\n :host {\n\t\t\twidth: 100%;\n display: block;\n\t\t}\n\n\t\t#root {\n\t\t\theight: 100%;\n display: flex;\n flex-direction: column;\n\t\t}\n\n #content-root {\n all: initial;\n transition: opacity 200ms ease-in-out;\n }\n\n\t\t#root[data-theme] {\n\t\t\tbackground-color: transparent;\n\t\t}\n\n\t\t.fade-out {\n\t\t\topacity: 0.1!important;\n\t\t}\n\n .hidden {\n display: none;\n }\n ")},J=function(){t(this,U,"m",z).call(this),this.slotElement=document.createElement("slot"),this.slotElement.classList.add("hidden"),this.rootElement.appendChild(this.slotElement)},B=function(){const t=["base-url","tenant","locale","debug","redirect-url","auto-focus","store-last-authenticated-user","refresh-cookie-name","keep-last-authenticated-user-after-logout","preview","storage-prefix","form","client","validate-on-blur","send-session-token","style-id","outbound-app-id","outbound-app-scopes","theme-override"];O.observedAttributes.forEach((e=>{if(!t.includes(e)&&!this[f(e)])throw Error(`${e} cannot be empty`)}))},H=function(){const{stepId:e,executionId:i}=g(this.flowId);i&&t(this,N,"f").update({stepId:e,executionId:i})},Q=function(i,s){u&&"function"==typeof u||this.logger.error("SDK was not loaded properly",u,JSON.stringify(u));const r=Object.assign(Object.assign({persistTokens:!0,preview:this.preview,storagePrefix:this.storagePrefix,storeLastAuthenticatedUser:this.storeLastAuthenticatedUser,keepLastAuthenticatedUserAfterLogout:this.keepLastAuthenticatedUserAfterLogout,refreshCookieName:this.refreshCookieName},O.sdkConfigOverrides),{projectId:i,baseUrl:s});t(this,W,"f")&&(r.customStorage=t(this,W,"f")),this.sdk=u(r);const o={start:1,next:7};["start","next"].forEach((i=>{const s=this.sdk.flow[i],r=v(s,1e3,3);this.sdk.flow[i]=(...s)=>e(this,void 0,void 0,(function*(){const e=[...s],n=o[i],a=t(this,U,"m",q).call(this,e[n]);void 0!==a&&(e[n]=a);try{return yield r(...e)}catch(t){return this.logger.error(`Error in sdk flow ${i} function`,t),{error:{errorCode:L,errorDescription:t.toString()}}}}))}));const n=this.sdk.flow.start;this.sdk.flow.start=(...i)=>e(this,void 0,void 0,(function*(){return yield t(this,U,"m",tt).call(this),n.apply(this.sdk.flow,i)}))},q=function(t){if(!this.sendSessionToken)return t;const e=null==l?void 0:l(this.storagePrefix);return e?Object.assign(Object.assign({},null!=t?t:{}),{sessionJwt:e}):t},$=function(i,s,r){return e(this,void 0,void 0,(function*(){const{projectId:e,baseUrl:s}=i;if(r("projectId")||r("baseUrl")){if(!e)return;t(this,U,"m",Q).call(this,e,s)}t(this,V,"f").call(this,i)}))},G=function(){return e(this,void 0,void 0,(function*(){const e=yield this.getConfig();return"isMissingConfig"in e&&e.isMissingConfig&&(yield t(this,U,"m",X).call(this))}))},X=function(){return e(this,void 0,void 0,(function*(){const t=p({projectId:this.projectId,filename:M,assetsFolder:S,baseUrl:this.baseStaticUrl});try{return yield m(t,"json"),!0}catch(t){return!1}}))},Y=function(e){i(this,F,Object.assign(Object.assign({},t(this,F,"f")),e.detail),"f")},tt=function(){return this.lazyStart?(t(this,Z,"f")||i(this,Z,new Promise((t=>{i(this,_,t,"f")})),"f"),t(this,Z,"f")):Promise.resolve()},et=function(){var e;null===(e=t(this,K,"f"))||void 0===e||e.remove(),i(this,K,null,"f")},it=function(s){return e(this,arguments,void 0,(function*({isDebug:e}){e?(i(this,K,document.createElement("descope-debugger"),"f"),Object.assign(t(this,K,"f").style,{position:"fixed",top:"0",right:"0",height:"100vh",width:"100vw",pointerEvents:"none",zIndex:99999}),yield import("../debugger-wc.js"),document.body.appendChild(t(this,K,"f"))):t(this,U,"m",et).call(this)}))},st=function(e,i){var s;e&&this.debug&&(null===(s=t(this,K,"f"))||void 0===s||s.updateData({title:e,description:i}))},ot.sdkConfigOverrides={baseHeaders:{"x-descope-sdk-name":"web-component","x-descope-sdk-version":"4.7.4"}};export{ot as default};
1
+ import{__classPrivateFieldGet as t,__awaiter as e,__classPrivateFieldSet as i}from"tslib";import{compose as s}from"@descope/sdk-helpers";import{staticResourcesMixin as r}from"@descope/sdk-mixins/static-resources-mixin";import{themeMixin as o}from"@descope/sdk-mixins/theme-mixin";import{injectStyleMixin as n}from"@descope/sdk-mixins/inject-style-mixin";import{telemetryMixin as a}from"@descope/sdk-mixins/telemetry-mixin";import{createSdk as u,getSessionToken as l}from"@descope/web-js-sdk";import{ELEMENTS_TO_IGNORE_ENTER_KEY_ON as d}from"../constants/index.js";import{handleUrlParams as h,clearRunIdsFromUrl as c,camelCase as f,getRunIdsFromUrl as g,getContentUrl as p,fetchContent as m,withRetry as v}from"../helpers/helpers.js";import b from"../helpers/state.js";import"@descope/escape-markdown";import"../helpers/webauthn.js";import{setCustomStorage as w}from"../helpers/storage.js";import{transformFlowInputFormData as k,extractNestedAttribute as y}from"../helpers/flowInputs.js";import{formMountMixin as C}from"../mixins/formMountMixin.js";import{componentConditionsMixin as x}from"../mixins/componentConditionsMixin.js";import{duplicateFlowWarningMixin as A}from"../mixins/duplicateFlowWarningMixin.js";import{passwordManagerMixin as j}from"../mixins/passwordManagerMixin.js";import{emailVerificationMixin as I}from"../mixins/emailVerificationMixin.js";import{validationTrackingMixin as E}from"../mixins/validationTrackingMixin.js";import{CONFIG_FILENAME as M,PREV_VER_ASSETS_FOLDER as S}from"../constants/content.js";import{FETCH_EXCEPTION_ERROR_CODE as L}from"../constants/general.js";var U,O,P,W,D,N,T,F,K,R,V,z,J,B,H,Q,q,$,G,X,Y,Z,_,tt,et,it,st;const rt=s(o,r,C,x,A,j,I,n,a,E)(HTMLElement);class ot extends rt{static get observedAttributes(){return["project-id","flow-id","base-url","tenant","locale","debug","storage-prefix","preview","redirect-url","auto-focus","store-last-authenticated-user","refresh-cookie-name","keep-last-authenticated-user-after-logout","validate-on-blur","send-session-token","style-id"]}get adoptedSsoQueryParams(){return t(this,D,"f")}constructor(s){super(),U.add(this),this.sdkVersion="4.8.0",P.set(this,!1),W.set(this,void 0),D.set(this,null),this.flowStatus="initial",this.loggerWrapper={error:(e,i="")=>{this.logger.error(e,i,new Error),t(this,U,"m",st).call(this,e,i)},warn:(t,e="")=>{this.logger.warn(t,e)},info:(t,e="",i={})=>{this.logger.info(t,e,i)},debug:(t,e="")=>{this.logger.debug(t,e)}},N.set(this,new b),T.set(this,new b),F.set(this,{}),this.getComponentsContext=()=>t(this,F,"f"),this.nextRequestStatus=new b({isLoading:!1}),K.set(this,void 0),R.set(this,{popstate:t(this,U,"m",H).bind(this),componentsContext:t(this,U,"m",Y).bind(this)}),V.set(this,void 0),this.getConfig=()=>e(this,void 0,void 0,(function*(){return(yield this.config)||{isMissingConfig:!0}})),Z.set(this,void 0),_.set(this,void 0),i(this,V,s,"f"),t(this,U,"m",J).call(this)}get client(){try{return JSON.parse(this.getAttribute("client"))||{}}catch(t){return{}}}get redirectUrl(){return this.getAttribute("redirect-url")||void 0}get debug(){return"true"===this.getAttribute("debug")}get locale(){return this.getAttribute("locale")||void 0}get autoFocus(){var t;const e=null!==(t=this.getAttribute("auto-focus"))&&void 0!==t?t:"true";return"skipFirstScreen"===e?e:"true"===e}get validateOnBlur(){return"true"===this.getAttribute("validate-on-blur")}get storeLastAuthenticatedUser(){var t;return"true"===(null!==(t=this.getAttribute("store-last-authenticated-user"))&&void 0!==t?t:"true")}get refreshCookieName(){return this.getAttribute("refresh-cookie-name")||""}get keepLastAuthenticatedUserAfterLogout(){return"true"===this.getAttribute("keep-last-authenticated-user-after-logout")}get storagePrefix(){return this.getAttribute("storage-prefix")||""}get sendSessionToken(){return"true"===this.getAttribute("send-session-token")}get preview(){return!!this.getAttribute("preview")}get formConfig(){return k(this.form)}get form(){return this.getAttribute("form")}get formConfigValues(){return y(this.formConfig,"value")}get outboundAppId(){return this.getAttribute("outbound-app-id")}get outboundAppScopes(){try{const t=JSON.parse(this.getAttribute("outbound-app-scopes"));return t||null}catch(t){return null}}get popupOrigin(){return this.getAttribute("popup-origin")}get customStorage(){return t(this,W,"f")}set customStorage(t){if(t&&"function"!=typeof t.getItem)throw new Error("Custom storage must have a getItem method");if(t&&"function"!=typeof t.setItem)throw new Error("Custom storage must have a setItem method");if(t&&"function"!=typeof t.removeItem)throw new Error("Custom storage must have a removeItem method");i(this,W,t,"f"),w(t)}get lazyStart(){return"true"===this.getAttribute("lazy-start")}start(){var e;null===(e=t(this,_,"f"))||void 0===e||e.call(this),i(this,Z,Promise.resolve(),"f")}get isRestartOnError(){return"true"===this.getAttribute("restart-on-error")}getExecutionContext(){return e(this,void 0,void 0,(function*(){const t=yield this.getConfig();return"executionContext"in t?t.executionContext:void 0}))}getProjectConfig(){return e(this,void 0,void 0,(function*(){const t=yield this.getConfig();return"projectConfig"in t?t.projectConfig:void 0}))}getFlowConfig(){return e(this,void 0,void 0,(function*(){var t,e;const i=yield this.getProjectConfig(),s=(null===(t=null==i?void 0:i.flows)||void 0===t?void 0:t[this.flowId])||{};return null!==(e=s.version)&&void 0!==e||(s.version=0),s}))}getTargetLocales(){return e(this,void 0,void 0,(function*(){const t=yield this.getFlowConfig();return((null==t?void 0:t.targetLocales)||[]).map((t=>t.toLowerCase()))}))}handleKeyPress(){this.logger.debug("Enable key press handler"),this.rootElement.onkeydown=t=>{var e,i,s;const r=!!(null===(e=this.shadowRoot.activeElement)||void 0===e?void 0:e.getAttribute("href")),o=d.includes(null!==(s=null===(i=this.shadowRoot.activeElement)||void 0===i?void 0:i.localName)&&void 0!==s?s:"");if("Enter"!==t.key||t.defaultPrevented||r||o)return;t.preventDefault();const n=this.rootElement.querySelectorAll("descope-button");if(1===n.length&&"false"!==n[0].getAttribute("auto-submit"))return void n[0].click();const a=Array.from(n).filter((t=>"true"===t.getAttribute("auto-submit")));if(1===a.length)return void a[0].click();const u=Array.from(n).filter((t=>"button"===t.getAttribute("data-type")));if(1===u.length)"false"!==u[0].getAttribute("auto-submit")&&u[0].click();else if(0===u.length){const t=Array.from(n).filter((t=>"sso"===t.getAttribute("data-type")));1===t.length&&"false"!==t[0].getAttribute("auto-submit")&&t[0].click()}}}disableKeyPressHandler(){this.logger.debug("Disable key press handler"),this.rootElement.onkeydown=null}getComponentsVersion(){return e(this,void 0,void 0,(function*(){var t;const e=yield this.getConfig(),i="projectConfig"in e?null===(t=e.projectConfig)||void 0===t?void 0:t.componentsVersion:{};return i||(this.logger.error("Did not get components version, using latest version"),"latest")}))}init(){const s=Object.create(null,{init:{get:()=>super.init}});return e(this,void 0,void 0,(function*(){var e;if(this.flowStatus="loading",["ready","error","success"].forEach((t=>this.addEventListener(t,(()=>{this.flowStatus=t})))),yield null===(e=s.init)||void 0===e?void 0:e.call(this),t(this,T,"f").subscribe(t(this,U,"m",it).bind(this)),t(this,T,"f").update({isDebug:this.debug}),t(this,U,"m",B).call(this),yield t(this,U,"m",G).call(this))return void this.loggerWrapper.error("This SDK version does not support your flows version","Make sure to upgrade your flows to the latest version or use an older SDK version");const r=yield this.getConfig();if("isMissingConfig"in r&&r.isMissingConfig)return void this.loggerWrapper.error("Cannot get config file","Make sure that your projectId & flowId are correct");const{executionId:o,stepId:n,token:a,code:u,isPopup:l,exchangeError:d,redirectAuthCallbackUrl:c,redirectAuthBackupCallbackUri:f,redirectAuthCodeChallenge:g,redirectAuthInitiator:p,ssoQueryParams:m,adoptedSsoQueryParams:v}=h(this.flowId,this.projectId,this.loggerWrapper);i(this,D,null!=v?v:null,"f"),window.addEventListener("popstate",t(this,R,"f").popstate),window.addEventListener("components-context",t(this,R,"f").componentsContext),t(this,N,"f").subscribe(t(this,U,"m",$).bind(this)),t(this,N,"f").update(Object.assign({projectId:this.projectId,flowId:this.flowId,baseUrl:this.baseUrl,tenant:this.tenantId,redirectUrl:this.redirectUrl,locale:this.locale,stepId:n,executionId:o,token:a,code:u,isPopup:l,exchangeError:d,redirectAuthCallbackUrl:c,redirectAuthBackupCallbackUri:f,redirectAuthCodeChallenge:g,redirectAuthInitiator:p},m)),i(this,P,!0,"f")}))}disconnectedCallback(){var e;t(this,N,"f").unsubscribeAll(),t(this,T,"f").unsubscribeAll(),t(this,U,"m",et).call(this),window.removeEventListener("popstate",t(this,R,"f").popstate),window.removeEventListener("components-context",t(this,R,"f").componentsContext),null===(e=super.disconnectedCallback)||void 0===e||e.call(this)}attributeChangedCallback(e,i,s){var r;if(null===(r=super.attributeChangedCallback)||void 0===r||r.call(this,e,i,s),this.shadowRoot.isConnected&&t(this,P,"f")&&i!==s&&O.observedAttributes.includes(e)){t(this,U,"m",B).call(this);const r=null===i;t(this,N,"f").update((({stepId:t,executionId:i})=>{let o=t,n=i;return r||(n=null,o=null,c()),{[f(e)]:s,stepId:o,executionId:n}})),t(this,T,"f").update({isDebug:this.debug})}}}O=ot,P=new WeakMap,W=new WeakMap,D=new WeakMap,N=new WeakMap,T=new WeakMap,F=new WeakMap,K=new WeakMap,R=new WeakMap,V=new WeakMap,Z=new WeakMap,_=new WeakMap,U=new WeakSet,z=function(){this.injectStyle("\n :host {\n\t\t\twidth: 100%;\n display: block;\n\t\t}\n\n\t\t#root {\n\t\t\theight: 100%;\n display: flex;\n flex-direction: column;\n\t\t}\n\n #content-root {\n all: initial;\n transition: opacity 200ms ease-in-out;\n }\n\n\t\t#root[data-theme] {\n\t\t\tbackground-color: transparent;\n\t\t}\n\n\t\t.fade-out {\n\t\t\topacity: 0.1!important;\n\t\t}\n\n .hidden {\n display: none;\n }\n ")},J=function(){t(this,U,"m",z).call(this),this.slotElement=document.createElement("slot"),this.slotElement.classList.add("hidden"),this.rootElement.appendChild(this.slotElement)},B=function(){const t=["base-url","tenant","locale","debug","redirect-url","auto-focus","store-last-authenticated-user","refresh-cookie-name","keep-last-authenticated-user-after-logout","preview","storage-prefix","form","client","validate-on-blur","send-session-token","style-id","outbound-app-id","outbound-app-scopes","theme-override"];O.observedAttributes.forEach((e=>{if(!t.includes(e)&&!this[f(e)])throw Error(`${e} cannot be empty`)}))},H=function(){const{stepId:e,executionId:i}=g(this.flowId);i&&t(this,N,"f").update({stepId:e,executionId:i})},Q=function(i,s){u&&"function"==typeof u||this.logger.error("SDK was not loaded properly",u,JSON.stringify(u));const r=Object.assign(Object.assign({persistTokens:!0,preview:this.preview,storagePrefix:this.storagePrefix,storeLastAuthenticatedUser:this.storeLastAuthenticatedUser,keepLastAuthenticatedUserAfterLogout:this.keepLastAuthenticatedUserAfterLogout,refreshCookieName:this.refreshCookieName},O.sdkConfigOverrides),{projectId:i,baseUrl:s});t(this,W,"f")&&(r.customStorage=t(this,W,"f")),this.sdk=u(r);const o={start:1,next:7};["start","next"].forEach((i=>{const s=this.sdk.flow[i],r=v(s,1e3,3);this.sdk.flow[i]=(...s)=>e(this,void 0,void 0,(function*(){const e=[...s],n=o[i],a=t(this,U,"m",q).call(this,e[n]);void 0!==a&&(e[n]=a);try{return yield r(...e)}catch(t){return this.logger.error(`Error in sdk flow ${i} function`,t),{error:{errorCode:L,errorDescription:t.toString()}}}}))}));const n=this.sdk.flow.start;this.sdk.flow.start=(...i)=>e(this,void 0,void 0,(function*(){return yield t(this,U,"m",tt).call(this),n.apply(this.sdk.flow,i)}))},q=function(t){if(!this.sendSessionToken)return t;const e=null==l?void 0:l(this.storagePrefix);return e?Object.assign(Object.assign({},null!=t?t:{}),{sessionJwt:e}):t},$=function(i,s,r){return e(this,void 0,void 0,(function*(){const{projectId:e,baseUrl:s}=i;if(r("projectId")||r("baseUrl")){if(!e)return;t(this,U,"m",Q).call(this,e,s)}t(this,V,"f").call(this,i)}))},G=function(){return e(this,void 0,void 0,(function*(){const e=yield this.getConfig();return"isMissingConfig"in e&&e.isMissingConfig&&(yield t(this,U,"m",X).call(this))}))},X=function(){return e(this,void 0,void 0,(function*(){const t=p({projectId:this.projectId,filename:M,assetsFolder:S,baseUrl:this.baseStaticUrl});try{return yield m(t,"json"),!0}catch(t){return!1}}))},Y=function(e){i(this,F,Object.assign(Object.assign({},t(this,F,"f")),e.detail),"f")},tt=function(){return this.lazyStart?(t(this,Z,"f")||i(this,Z,new Promise((t=>{i(this,_,t,"f")})),"f"),t(this,Z,"f")):Promise.resolve()},et=function(){var e;null===(e=t(this,K,"f"))||void 0===e||e.remove(),i(this,K,null,"f")},it=function(s){return e(this,arguments,void 0,(function*({isDebug:e}){e?(i(this,K,document.createElement("descope-debugger"),"f"),Object.assign(t(this,K,"f").style,{position:"fixed",top:"0",right:"0",height:"100vh",width:"100vw",pointerEvents:"none",zIndex:99999}),yield import("../debugger-wc.js"),document.body.appendChild(t(this,K,"f"))):t(this,U,"m",et).call(this)}))},st=function(e,i){var s;e&&this.debug&&(null===(s=t(this,K,"f"))||void 0===s||s.updateData({title:e,description:i}))},ot.sdkConfigOverrides={baseHeaders:{"x-descope-sdk-name":"web-component","x-descope-sdk-version":"4.8.0"}};export{ot as default};
2
2
  //# sourceMappingURL=BaseDescopeWc.js.map
@@ -1,2 +1,2 @@
1
- import{__classPrivateFieldGet as e,__classPrivateFieldSet as t,__awaiter as i,__rest as s}from"tslib";import{getUserLocale as o}from"@descope/sdk-helpers";import{ensureFingerprintIds as n,clearFingerprintData as r}from"@descope/web-js-sdk";import{RESPONSE_ACTIONS as l,CUSTOM_INTERACTIONS as a,URL_CODE_PARAM_NAME as d,URL_ERR_PARAM_NAME as c,URL_TOKEN_PARAM_NAME as p,URL_RUN_IDS_PARAM_NAME as h,SDK_SCRIPTS_LOAD_TIMEOUT as u,DESCOPE_ATTRIBUTE_EXCLUDE_FIELD as g,ELEMENT_TYPE_ATTRIBUTE as v,WEBAUTHN_TIMEOUT as m,DESCOPE_ATTRIBUTE_OPT_IN_LAST_USED as f,DESCOPE_LAST_AUTH_BADGE_COMPONENT as b,DESCOPE_ATTRIBUTE_EXCLUDE_NEXT_BUTTON as w}from"../constants/index.js";import{timeoutPromise as S,withMemCache as y,leadingDebounce as I,getIdFromExecId as k,showFirstScreenOnExecutionInit as R,injectSamlIdpForm as W,injectWsFedIdpForm as C,openCenteredPopup as x,getAnimationDirection as E,transformScreenInputs as O,handleReportValidityOnBlur as A,handleAutoFocus as j,getScriptResultPath as T,getElementDescopeAttributes as P,submitForm as U,transformStepStateForCustomScreen as L,clearPreviousExternalInputs as F,getTrustedPopupOpenerOrigin as $}from"../helpers/helpers.js";import N from"../helpers/state.js";import{disableWebauthnButtons as V,updateTemplateFromScreenState as M,setComponentsAutoDetectByGeo as q,setComponentsAutoDetectByLocale as D,setTOTPVariable as B,setNOTPVariable as _,setCssVars as K,updateScreenFromScreenState as H,replaceElementMessage as G}from"../helpers/templates.js";import{isConditionalLoginSupported as J}from"../helpers/webauthn.js";import{clearSsoQueryParams as Q,linkRunToSsoContext as z,pickSsoQueryParams as X,clearSsoContextOnAppRedirect as Y}from"../helpers/oidcSession.js";import{getABTestingKey as Z}from"../helpers/abTestingKey.js";import{calculateConditions as ee,calculateCondition as te}from"../helpers/conditions.js";import{setLastAuth as ie,getInFlightLastUsedPerScreen as se,clearInFlightLastAuth as oe,getLastAuth as ne,updateLastUsedPerScreen as re}from"../helpers/lastAuth.js";import{isHiddenByCondition as le}from"../helpers/realtime-conditions/applier.js";import ae from"./BaseDescopeWc.js";import{FETCH_EXCEPTION_ERROR_CODE as de,FLOW_TIMED_OUT_ERROR_CODE as ce,POLLING_STATUS_NOT_FOUND_ERROR_CODE as pe,NONCE_VALIDATION_ERROR_CODE as he,FETCH_ERROR_RESPONSE_ERROR_CODE as ue,FLOW_REQUESTED_IS_IN_OLD_VERSION_ERROR_CODE as ge}from"../constants/general.js";var ve,me,fe,be,we,Se,ye,Ie,ke,Re,We,Ce,xe,Ee,Oe,Ae,je,Te,Pe,Ue,Le,Fe,$e,Ne,Ve,Me,qe,De,Be,_e,Ke,He,Ge,Je,Qe,ze,Xe,Ye,Ze,et,tt,it,st,ot,nt,rt;const lt="__descope_webauthn_timed_out__";class at extends ae{static set sdkConfigOverrides(e){ae.sdkConfigOverrides=e}static get sdkConfigOverrides(){return ae.sdkConfigOverrides}constructor(){const s=new N({deferredRedirect:!1,deferredPolling:!1});super(s.update.bind(s)),ve.add(this),this.stepState=new N({}),me.set(this,void 0),fe.set(this,null),be.set(this,null),we.set(this,{visibilitychange:e(this,ve,"m",Se).bind(this)}),this.bridgeVersion=at.bridgeVersion,ye.set(this,void 0),this.nativeCallbacks={},Oe.set(this,!1),this.handleRedirect=e=>{window.location.assign(e)},Te.set(this,(t=>{t&&this.clearEmailVerification();const i=()=>{this.contentRootElement.classList.toggle("hidden",t),this.slotElement.classList.toggle("hidden",!t),t&&(this.contentRootElement.innerHTML="")};t&&this.contentRootElement.hasChildNodes()?e(this,ve,"m",Pe).call(this,i):i()})),Ue.set(this,((s,o,n,r,d=!1)=>{const c=[ce,pe,he];if(this.flowState.current.action===l.poll){if(e(this,Fe,"f").call(this)&&document.hidden)return this.logger.debug("polling - Deferring polling until in foreground"),void this.flowState.update({deferredPolling:!0});this.logger.debug("polling - Scheduling polling request");const l=Date.now(),p=d?500:2e3;t(this,me,setTimeout((()=>i(this,void 0,void 0,(function*(){var t,i;this.logger.debug("polling - Calling next");const h=this.sdk.flow.next(s,o,a.polling,n,r,{}),u=document.hidden&&!d&&Date.now()-l>p+500;let g;u&&this.logger.debug("polling - The polling seems to be throttled");try{const e=u?1e3:6e3;g=yield S(e,h)}catch(t){return this.logger.warn(`polling - The ${u?"throttled fetch":"fetch"} call timed out or was aborted`),void e(this,Ue,"f").call(this,s,o,n,r,u)}if((null===(t=null==g?void 0:g.error)||void 0===t?void 0:t.errorCode)===de)return this.logger.debug("polling - Got a generic error due to exception in fetch call"),void e(this,Ue,"f").call(this,s,o,n,r);this.logger.debug("polling - Got a response"),(null==g?void 0:g.error)&&this.logger.debug("polling - Response has an error",JSON.stringify(g.error,null,4)),(null===(i=null==g?void 0:g.error)||void 0===i?void 0:i.errorCode)&&c.includes(g.error.errorCode)?this.logger.debug("polling - Stopping polling due to error"):e(this,Ue,"f").call(this,s,o,n,r),e(this,$e,"f").call(this,g)}))),p),"f")}})),Le.set(this,(()=>{clearTimeout(e(this,me,"f")),t(this,me,null,"f")})),Fe.set(this,(()=>!!window.descopeBridge||/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent))),$e.set(this,(i=>{var s,o,n,r,a,d,c,p,h,u,g,v,m;if(!(null==i?void 0:i.ok)){const t=null===(s=null==i?void 0:i.response)||void 0===s?void 0:s.url,l=`${null===(o=null==i?void 0:i.response)||void 0===o?void 0:o.status} - ${null===(n=null==i?void 0:i.response)||void 0===n?void 0:n.statusText}`;e(this,ve,"m",nt).call(this,"error",(null==i?void 0:i.error)||{errorCode:ue,errorDescription:l,errorMessage:t}),this.loggerWrapper.error((null===(r=null==i?void 0:i.error)||void 0===r?void 0:r.errorDescription)||t,(null===(a=null==i?void 0:i.error)||void 0===a?void 0:a.errorMessage)||l);const c=null===(d=null==i?void 0:i.error)||void 0===d?void 0:d.errorCode;return void(c!==ge&&c!==ce&&c!==he||!this.isRestartOnError||e(this,ve,"m",Ee).call(this))}null===(p=null===(c=i.data)||void 0===c?void 0:c.runnerLogs)||void 0===p||p.forEach((e=>{const{level:t,title:i,log:s}=e;t&&this.loggerWrapper[t]?this.loggerWrapper[t](i,s):this.loggerWrapper.info(i,s)}));const f=null===(g=null===(u=null===(h=i.data)||void 0===h?void 0:h.screen)||void 0===u?void 0:u.state)||void 0===g?void 0:g.errorText;(null===(v=i.data)||void 0===v?void 0:v.error)?this.loggerWrapper.error(`[${i.data.error.code}]: ${i.data.error.description}`,`${f?`${f} - `:""}${i.data.error.message}`):f&&this.loggerWrapper.error(f);const{status:b,authInfo:w,lastAuth:S,action:y,openInNewTabUrl:I}=i.data;if(y!==l.poll&&e(this,Le,"f").call(this),"completed"===b){this.storeLastAuthenticatedUser&&ie(Object.assign(Object.assign({},S),{lastUsedPerScreen:se()})),oe(this.loggerWrapper);const t=Object.assign({},w);return i.data.output&&Object.keys(i.data.output).length>0&&(t.flowOutput=i.data.output),this.setValidationTrackingExecution(i.data.executionId),Q(this.projectId,this.flowId),void e(this,ve,"m",nt).call(this,"success",t)}this.storeLastAuthenticatedUser&&ie(S,!0),I&&window.open(I,"_blank");const{executionId:k,stepId:R,stepName:W,screen:C,redirect:x,webauthn:E,error:O,samlIdpResponse:A,wsFedIdpResponse:j,nativeResponse:T}=i.data,P=Date.now();y!==l.poll?(this.loggerWrapper.info(`Step "${W||`#${R}`}" is ${b}`,"",{screen:C,status:b,stepId:R,stepName:W,action:y,error:O}),(null===(m=C.state)||void 0===m?void 0:m.clientScripts)&&t(this,be,this.loadSdkScripts(C.state.clientScripts),"f"),this.flowState.update({stepId:R,stepName:W,executionId:k,action:y,redirectTo:null==x?void 0:x.url,redirectIsPopup:null==x?void 0:x.isPopup,screenId:null==C?void 0:C.id,screenState:null==C?void 0:C.state,webauthnTransactionId:null==E?void 0:E.transactionId,webauthnOptions:null==E?void 0:E.options,samlIdpResponseUrl:null==A?void 0:A.url,samlIdpResponseSamlResponse:null==A?void 0:A.samlResponse,samlIdpResponseRelayState:null==A?void 0:A.relayState,wsFedIdpResponseUrl:null==j?void 0:j.url,wsFedIdpResponseWresult:null==j?void 0:j.wresult,wsFedIdpResponseWctx:null==j?void 0:j.wctx,nativeResponseType:null==T?void 0:T.type,nativePayload:null==T?void 0:T.payload,reqTimestamp:P})):this.flowState.update({action:y,reqTimestamp:P})})),Ne.set(this,y((()=>i(this,void 0,void 0,(function*(){var e;try{const t=yield this.sdk.webauthn.signIn.start("",window.location.origin);return t.ok||this.loggerWrapper.warn("Webauthn start failed",null===(e=null==t?void 0:t.error)||void 0===e?void 0:e.errorMessage),t.data}catch(e){this.loggerWrapper.warn("Webauthn start failed",e.message)}}))))),De.set(this,void 0),Be.set(this,void 0),Qe.set(this,null),Ze.set(this,I(((t,s,o)=>i(this,void 0,void 0,(function*(){var i;if("true"!==t.getAttribute("loading")&&"true"!==t.getAttribute("disabled")){if("true"===t.getAttribute("formnovalidate")||e(this,ve,"m",Ge).call(this)){const n=null==t?void 0:t.getAttribute("id");e(this,ve,"m",it).call(this,t,n,o);const r=e(this,ve,"m",ze).call(this,t);try{const o=yield e(this,ve,"m",Je).call(this),r=P(t);this.nextRequestStatus.update({isLoading:!0});const l=yield this.emailVerificationToken(t),a=Object.assign(Object.assign(Object.assign(Object.assign({},r),o),{origin:e(this,ve,"a",He)}),l&&{evpToken:l}),d=yield s(n,a);this.nextRequestStatus.update({isLoading:!1}),this.captureLastSubmittedLoginId(o,null===(i=null==d?void 0:d.data)||void 0===i?void 0:i.executionId),this.storeCredentials(o)}catch(e){throw r(),e}}}else this.loggerWrapper.debug("Submit already in flight, ignoring")}))))),this.flowState=s,this.setValidationTrackingSender(((e,t)=>i(this,[e,t],void 0,(function*({executionId:e,events:t},{keepalive:i}){const s=yield this.sdk.flow.event(e,t,i);return{ok:s.ok,retryable:s.code>=500||429===s.code}}))))}nativeResume(t,i){var s,o,n,r,l,a;const u=JSON.parse(i);if("oauthWeb"===t||"sso"===t){let e,{exchangeCode:t}=u;if(!t){const i=new URL(u.url);t=null===(s=i.searchParams)||void 0===s?void 0:s.get(d),e=(null===(o=i.searchParams)||void 0===o?void 0:o.get(c))||void 0}null===(r=(n=this.nativeCallbacks).complete)||void 0===r||r.call(n,{exchangeCode:t,exchangeError:e,idpInitiated:!0})}else if("magicLink"===t){const t=new URL(u.url),i=t.searchParams.get(p),s=t.searchParams.get(h).split("_").pop();e(this,Le,"f").call(this),this.flowState.update({token:i,stepId:s,action:void 0})}else if("beforeScreen"===t){const{screenResolve:e}=this.nativeCallbacks;this.nativeCallbacks.screenResolve=null;const{override:t}=u;t||(this.nativeCallbacks.screenNext=null),null==e||e(t)}else if("resumeScreen"===t){const{interactionId:e,form:t}=u,{screenNext:i}=this.nativeCallbacks;this.nativeCallbacks.screenNext=null,null==i||i(e,t)}else null===(a=(l=this.nativeCallbacks).complete)||void 0===a||a.call(l,u)}loadSdkScriptsModules(){const e=this.shadowRoot.querySelectorAll("div[data-script-id]");return Array.from(e).map((e=>e.moduleRes)).filter((e=>!!e))}loadSdkScripts(e){if(!(null==e?void 0:e.length))return null;const t=(e,t)=>i=>{this.dispatchEvent(new CustomEvent("components-context",{detail:{[T(e.id,e.resultKey)]:i},bubbles:!0,composed:!0})),t(e.id)};this.loggerWrapper.debug(`Preparing to load scripts: ${e.map((e=>e.id)).join(", ")}`);const s=e=>i(this,void 0,void 0,(function*(){var i,s,o;const n=this.shadowRoot.querySelector(`[data-script-id="${e.id}"]`);if(n){this.loggerWrapper.debug("Script already loaded",e.id);const{moduleRes:t}=n;return null===(i=null==t?void 0:t.start)||void 0===i||i.call(t),t}(null===(s=globalThis.descope)||void 0===s?void 0:s[e.id])||(yield this.injectNpmLib("@descope/flow-scripts","1.0.22",`dist/${e.id}.js`));const r=null===(o=globalThis.descope)||void 0===o?void 0:o[e.id];return new Promise(((i,s)=>{try{const s=r(e.initArgs,{baseUrl:this.baseUrl,ref:this},t(e,i),this.loggerWrapper);if(s){const t=document.createElement("div");t.setAttribute("data-script-id",e.id),t.moduleRes=s,this.shadowRoot.appendChild(t);const o=this.nextRequestStatus.subscribe((()=>{var i;this.loggerWrapper.debug("Stopping script",e.id),(null===(i=s.stop)||void 0===i?void 0:i.call(s))&&(this.nextRequestStatus.unsubscribe(o),this.loggerWrapper.debug("Removing script",e.id),this.shadowRoot.removeChild(t))}));"function"==typeof s.present&&i(e.id)}}catch(e){s(e)}}))})),o=Promise.all((null!=e?e:[]).map((e=>s(e).catch((t=>(this.loggerWrapper.warn(`Sdk script ${e.id} failed to load, continuing without it`,null==t?void 0:t.message),null))))));let n;const r=new Promise((e=>{n=setTimeout((()=>{this.loggerWrapper.warn("SDK scripts loading timeout"),e(!0)}),u)}));return Promise.race([o,r]).finally((()=>clearTimeout(n))).catch((e=>(this.loggerWrapper.warn("Sdk scripts failed to load, continuing without them",null==e?void 0:e.message),null)))}get isDismissScreenErrorOnInput(){return"true"===this.getAttribute("dismiss-screen-error-on-input")}init(){var e,i;if(!window.descopeBridge)return this._init();this.lazyInit=this._init,t(this,ye,null===(i=null===(e=null===window||void 0===window?void 0:window.descopeBridge)||void 0===e?void 0:e.registerFlow)||void 0===i?void 0:i.call(e,this),"f")}_init(){const t=Object.create(null,{init:{get:()=>super.init}});return i(this,void 0,void 0,(function*(){var i,s;this.shadowRoot.isConnected&&(null===(i=this.flowState)||void 0===i||i.subscribe(this.onFlowChange.bind(this)),e(this,ve,"m",Ce).call(this),window.addEventListener("visibilitychange",e(this,we,"f").visibilitychange)),yield null===(s=t.init)||void 0===s?void 0:s.call(this)}))}disconnectedCallback(){var i,s,o;super.disconnectedCallback(),this.teardownValidationTracking(),e(this,ye,"f")&&(null===(s=null===(i=window.descopeBridge)||void 0===i?void 0:i.unregisterFlow)||void 0===s||s.call(i,e(this,ye,"f")),t(this,ye,void 0,"f")),this.flowState.unsubscribeAll(),this.stepState.unsubscribeAll(),e(this,Le,"f").call(this),null===(o=e(this,fe,"f"))||void 0===o||o.abort(),t(this,fe,null,"f"),this.clearEmailVerification(),window.removeEventListener("visibilitychange",e(this,we,"f").visibilitychange)}getHtmlFilenameWithLocale(e,t){return i(this,void 0,void 0,(function*(){let i;const s=o(e),n=yield this.getTargetLocales();return n.includes(s.locale)?i=`${t}-${s.locale}.html`:n.includes(s.fallback)&&(i=`${t}-${s.fallback}.html`),i}))}getPageContent(e,t){return i(this,void 0,void 0,(function*(){if(t)try{const{body:e}=yield this.fetchStaticResource(t,"text");return e}catch(i){this.loggerWrapper.error(`Failed to fetch flow page from ${t}. Fallback to url ${e}`,i)}try{const{body:t}=yield this.fetchStaticResource(e,"text");return t}catch(e){this.loggerWrapper.error("Failed to fetch flow page",e.message)}return null}))}onFlowChange(d,c,p){return i(this,void 0,void 0,(function*(){var h,u;const{projectId:g,flowId:v,tenant:m,stepId:f,executionId:b,action:w,screenId:S,screenState:y,redirectTo:I,redirectIsPopup:A,redirectUrl:j,token:T,code:P,isPopup:L,exchangeError:F,webauthnTransactionId:$,webauthnOptions:N,redirectAuthCodeChallenge:V,redirectAuthCallbackUrl:M,redirectAuthBackupCallbackUri:q,redirectAuthInitiator:D,locale:B,samlIdpResponseUrl:_,samlIdpResponseSamlResponse:K,samlIdpResponseRelayState:H,wsFedIdpResponseUrl:G,wsFedIdpResponseWresult:J,wsFedIdpResponseWctx:Q,nativeResponseType:ie,nativePayload:se,reqTimestamp:re}=d,le=s(d,["projectId","flowId","tenant","stepId","executionId","action","screenId","screenState","redirectTo","redirectIsPopup","redirectUrl","token","code","isPopup","exchangeError","webauthnTransactionId","webauthnOptions","redirectAuthCodeChallenge","redirectAuthCallbackUrl","redirectAuthBackupCallbackUri","redirectAuthInitiator","locale","samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState","wsFedIdpResponseUrl","wsFedIdpResponseWresult","wsFedIdpResponseWctx","nativeResponseType","nativePayload","reqTimestamp"]);let ae,de,ce;p("executionId")&&b&&z(k(b),X(le),g,v);const pe=Z(),{outboundAppId:he,outboundAppScopes:ue}=this,ge=this.sdk.getLastUserLoginId();p("flowId")&&this.setValidationTrackingEnabled(!1);const me=yield this.getFlowConfig();e(this,ve,"m",_e).call(this,me,b,p);const we=yield this.getProjectConfig(),Se=Object.entries(we.flows||{}).reduce(((e,[t,i])=>(e[t]=i.version,e)),{}),ye=M&&V?{callbackUrl:M,codeChallenge:V,backupCallbackUri:q}:void 0,Ie=this.nativeOptions?{platform:this.nativeOptions.platform,bridgeVersion:this.nativeOptions.bridgeVersion,oauthProvider:this.nativeOptions.oauthProvider,oauthRedirect:this.nativeOptions.oauthRedirect,magicLinkRedirect:this.nativeOptions.magicLinkRedirect,ssoRedirect:this.nativeOptions.ssoRedirect,externalAuthRedirect:this.nativeOptions.externalAuthRedirect}:void 0;let ke={};if(!b){oe(this.loggerWrapper);const i=[...me.clientScripts||[],...me.sdkScripts||[]];if(me.conditions){let e=[];({startScreenId:ae,conditionInteractionId:ce,startScreenName:de,clientScripts:e,componentsConfig:ke}=ee({loginId:ge,code:P,token:T,abTestingKey:pe,lastAuth:ne(ge,this.loggerWrapper)},me.conditions)),i.push(...e||[])}else me.condition?({startScreenId:ae,startScreenName:de,conditionInteractionId:ce}=te(me.condition,{loginId:ge,code:P,token:T,abTestingKey:pe,lastAuth:ne(ge,this.loggerWrapper)})):(de=me.startScreenName,ae=me.startScreenId);if(t(this,De,ae,"f"),t(this,Be,de,"f"),t(this,be,this.loadSdkScripts(i),"f"),me.fingerprintEnabled&&me.fingerprintKey?yield n(me.fingerprintKey,this.baseUrl):r(),!R(ae,le)){const t=yield this.sdk.flow.start(v,Object.assign(Object.assign(Object.assign(Object.assign({tenant:m,redirectAuth:ye},le),{client:this.client}),j&&{redirectUrl:j}),{lastAuth:ne(ge,this.loggerWrapper),abTestingKey:pe,locale:o(B).locale,nativeOptions:Ie,outboundAppId:he,outboundAppScopes:ue}),ce,"",we.componentsVersion,Se,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({origin:e(this,ve,"a",He)},this.formConfigValues),P?{exchangeCode:P,idpInitiated:!0}:{}),le.descopeIdpInitiated&&{idpInitiated:!0}),T?{token:T}:{}),le.oidcLoginHint?{externalId:le.oidcLoginHint}:{}));return e(this,$e,"f").call(this,t),void("completed"!==(null===(h=null==t?void 0:t.data)||void 0===h?void 0:h.status)&&this.flowState.update({code:void 0,token:void 0}))}}if(this.loggerWrapper.debug("Before popup postmessage send",JSON.stringify({isPopup:L,code:P,exchangeError:F,isCodeChanged:p("code"),isExchangeErrorChanged:p("exchangeError")})),L&&(p("code")&&P||p("exchangeError")&&F))return void e(this,ve,"m",rt).call(this,b,P,F);if(b&&(p("token")&&T||p("code")&&P||p("exchangeError")&&F)){const t=yield this.sdk.flow.next(b,f,a.submit,me.version,we.componentsVersion,{token:T,exchangeCode:P,exchangeError:F,origin:e(this,ve,"a",He)});return e(this,$e,"f").call(this,t),void this.flowState.update({token:void 0,code:void 0,exchangeError:void 0})}if(w===l.loadForm&&_&&["samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState"].some((e=>p(e)))){if(!K)return void this.loggerWrapper.error("Did not get saml idp params data to load");W(_,K,H||"",U)}if(w===l.loadForm&&G&&["wsFedIdpResponseUrl","wsFedIdpResponseWresult","wsFedIdpResponseWctx"].some((e=>p(e)))){if(!J)return void this.loggerWrapper.error("Did not get wsfed idp params data to load");C(G,J,Q||"",U)}if(w===l.redirect&&(p("redirectTo")||p("deferredRedirect"))){if(!I)return void this.loggerWrapper.error("Did not get redirect url");if("no-op"===I)return;if("android"===D&&document.hidden)return void this.flowState.update({deferredRedirect:!0});if(this.loggerWrapper.debug(`Redirect is popup ${A}`),A){this.loggerWrapper.debug("Opening redirect in popup");const t=x(I,"?",598,700),i=this.shouldUsePopupPostMessage();i&&(t.name=`descope-wc|${window.location.origin}`),this.loggerWrapper.debug("Popup communication method: "+(i?"postMessage":"BroadcastChannel"));let s=!1;const o=e=>{this.loggerWrapper.debug("Received popup message",JSON.stringify(e.data));const t=i?this.popupOrigin:window.location.origin;if(e.origin!==t)return void this.loggerWrapper.debug(`Ignoring message from unexpected origin. received: "${e.origin}", expected: "${t}"`);const{action:o,data:n}=e.data||{};"code"===o&&(s=!0,this.flowState.update({code:n.code,exchangeError:n.exchangeError}))};let n;this.loggerWrapper.debug("Starting popup closed detection");const r=setInterval((()=>{t.closed&&(this.loggerWrapper.debug("Popup closed, dispatching popupclosed event"),clearInterval(r),e(this,ve,"m",nt).call(this,"popupclosed",{abandoned:!s}),this.loggerWrapper.debug("Cleaning up popup listeners"),null==n||n())}),1e3);if(i)window.addEventListener("message",o),n=()=>{this.loggerWrapper.debug("Cleaning up popup postMessage listener"),window.removeEventListener("message",o)};else{this.loggerWrapper.debug("Creating broadcast channel");const e=new BroadcastChannel(b);e.onmessage=o,n=()=>{this.loggerWrapper.debug("Closing channel"),e.close()}}}else Y(I,k(b),Object.assign(Object.assign({},this.adoptedSsoQueryParams),X(le)),g,v),this.handleRedirect(I),this.flowState.update({redirectTo:"no-op"}),e(this,ve,"m",nt).call(this,"popupclosed",{});return}if(w===l.webauthnCreate||w===l.webauthnGet){if(!$||!N)return void this.loggerWrapper.error("Did not get webauthn transaction id or options");null===(u=e(this,fe,"f"))||void 0===u||u.abort(),t(this,fe,null,"f");const i=yield e(this,ve,"m",je).call(this,w,N),s=yield this.sdk.flow.next(b,f,a.submit,me.version,we.componentsVersion,Object.assign({transactionId:$},i));e(this,$e,"f").call(this,s)}if(w===l.nativeBridge)return this.nativeCallbacks.complete=t=>i(this,void 0,void 0,(function*(){const i=yield this.sdk.flow.next(b,f,a.submit,me.version,we.componentsVersion,t);e(this,$e,"f").call(this,i)})),e(this,ve,"m",Re).call(this,ie,se),void setTimeout((()=>{this.dispatchEvent(new Event("popupclosed"))}),500);if((p("action")||p("deferredPolling"))&&e(this,Ue,"f").call(this,b,f,me.version,we.componentsVersion),!S&&!ae)return void this.loggerWrapper.warn("No screen was found to show");const We=ae||S,Ce=yield this.getHtmlFilenameWithLocale(B,We),{oidcLoginHint:xe,oidcPrompt:Ee,oidcErrorRedirectUri:Oe,oidcResource:Te,samlIdpUsername:Pe}=le,Le={direction:E(f,c.stepId),screenState:Object.assign(Object.assign({},y),{form:Object.assign(Object.assign({},this.formConfigValues),null==y?void 0:y.form),lastAuth:{loginId:ge,name:this.sdk.getLastUserDisplayName()||ge},componentsConfig:Object.assign(Object.assign(Object.assign({},me.componentsConfig),ke),null==y?void 0:y.componentsConfig)}),htmlFilename:`${We}.html`,htmlLocaleFilename:Ce,screenId:We,stepName:d.stepName||de,samlIdpUsername:Pe,oidcLoginHint:xe,oidcPrompt:Ee,oidcErrorRedirectUri:Oe,oidcResource:Te,action:w,locale:o(B).locale},Fe=ne(ge,this.loggerWrapper);R(ae,le)?Le.next=(t,s)=>i(this,void 0,void 0,(function*(){const i=(null==me?void 0:me.clientScripts)||[];yield e(this,ve,"m",et).call(this,i);const n=yield this.sdk.flow.start(v,Object.assign(Object.assign(Object.assign(Object.assign({tenant:m,redirectAuth:ye},le),{lastAuth:Fe,preview:this.preview,abTestingKey:pe,client:this.client}),j&&{redirectUrl:j}),{locale:o(B).locale,nativeOptions:Ie,outboundAppId:he,outboundAppScopes:ue}),ce,t,we.componentsVersion,Se,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({origin:e(this,ve,"a",He)},this.formConfigValues),this.getComponentsContext()),O(s)),P&&{exchangeCode:P,idpInitiated:!0}),le.descopeIdpInitiated&&{idpInitiated:!0}),T&&{token:T}),Le.next.isCustomScreen);return e(this,$e,"f").call(this,n),n})):(p("projectId")||p("baseUrl")||p("executionId")||p("stepId"))&&(Le.next=(t,s)=>i(this,void 0,void 0,(function*(){const i=(null==y?void 0:y.clientScripts)||[];yield e(this,ve,"m",et).call(this,i);const o=yield this.sdk.flow.next(b,f,t,me.version,we.componentsVersion,Object.assign(Object.assign({origin:e(this,ve,"a",He)},this.getComponentsContext()),O(s)),Le.next.isCustomScreen);return e(this,$e,"f").call(this,o),o}))),this.loggerWrapper.debug("Got a screen with id",Le.screenId),yield e(this,ve,"m",Ae).call(this,Le),this.stepState.update(Le)}))}onStepChange(t,s){return i(this,void 0,void 0,(function*(){var o,n,r;const{htmlFilename:l,htmlLocaleFilename:d,direction:c,next:p,screenState:h,screenId:u}=t;this.loggerWrapper.debug("Rendering a flow screen"),this.clearEmailVerification(),this.updateScreenUser(null==h?void 0:h.user);const g=document.createElement("template");g.innerHTML=yield this.getPageContent(l,d);const m=g.content.cloneNode(!0),f=this.loadDescopeUiComponents(g);this.sdk.webauthn.helpers.isSupported()?yield e(this,ve,"m",Me).call(this,m,p):V(m),!t.samlIdpUsername||(null===(o=h.form)||void 0===o?void 0:o.loginId)||(null===(n=h.form)||void 0===n?void 0:n.email)||(h.form||(h.form={}),h.form.loginId=t.samlIdpUsername,h.form.email=t.samlIdpUsername),M(m,h,this.formConfig,this.loggerWrapper),this.applyComponentsState(m,null==h?void 0:h.componentsState),this.startEmailVerification(m);const{geo:b}=null!==(r=yield this.getExecutionContext())&&void 0!==r?r:{};q(m,b),D(m,t.locale);const w=()=>i(this,void 0,void 0,(function*(){var i,o;yield f;const n=this.contentRootElement;B(n,null===(i=null==h?void 0:h.totp)||void 0===i?void 0:i.image),_(n,null===(o=null==h?void 0:h.notp)||void 0===o?void 0:o.image),K(n,m,h.cssVars,this.loggerWrapper),n.replaceChildren(m);const r=!s.htmlFilename;setTimeout((()=>{e(this,ve,"m",Xe).call(this),this.updateUsernameAnchor(),this.validateOnBlur&&A(n,(t=>this.trackValidationErrors([t],e(this,ve,"a",Ke)))),H(n,h),this.initRealtimeConditions(n,h),e(this,ve,"m",qe).call(this,{isFirstScreen:r,isCustomScreen:!1,stepName:t.stepName}),j(n,this.autoFocus,r),e(this,ve,"m",st).call(this,u)})),e(this,ve,"m",ot).call(this,p,u);n.querySelector(`[${v}="polling"]`)&&p(a.polling,{})}));c?e(this,ve,"m",Pe).call(this,w):w()}))}getInputs(){return Array.from(this.shadowRoot.querySelectorAll(`*:not(slot)[name]:not([${g}])`))}shouldUsePopupPostMessage(){if(!this.popupOrigin)return!1;try{new URL(this.popupOrigin)}catch(e){return!1}return!0}}me=new WeakMap,fe=new WeakMap,be=new WeakMap,we=new WeakMap,ye=new WeakMap,Oe=new WeakMap,Te=new WeakMap,Ue=new WeakMap,Le=new WeakMap,Fe=new WeakMap,$e=new WeakMap,Ne=new WeakMap,De=new WeakMap,Be=new WeakMap,Qe=new WeakMap,Ze=new WeakMap,ve=new WeakSet,Se=function(){document.hidden||setTimeout((()=>{this.flowState.update({deferredRedirect:!1,deferredPolling:!1})}),300)},Ie=function(t,s,o){return i(this,void 0,void 0,(function*(){var i;return(null===(i=this.nativeOptions)||void 0===i?void 0:i.bridgeVersion)>=2&&new Promise((i=>{this.nativeCallbacks.screenNext=o,this.nativeCallbacks.screenResolve=i,e(this,ve,"m",Re).call(this,"beforeScreen",{screen:t,context:s})}))}))},ke=function(t){var i;(null===(i=this.nativeOptions)||void 0===i?void 0:i.bridgeVersion)>=2&&e(this,ve,"m",Re).call(this,"afterScreen",{screen:t})},Re=function(t,i){e(this,ve,"m",nt).call(this,"bridge",{type:t,payload:i})},We=function({errorText:e,errorType:t}){const i=()=>{var i;let s=e;try{s=(null===(i=this.errorTransformer)||void 0===i?void 0:i.call(this,{text:e,type:t}))||e}catch(e){this.loggerWrapper.error("Error transforming error message",e.message)}G(this.contentRootElement,"error-message",s)};this.addEventListener("screen-updated",i,{once:!0}),i()},Ce=function(){var t,i,o,n;null===(t=this.stepState)||void 0===t||t.subscribe(this.onStepChange.bind(this),(e=>{var t=e.screenState,i=void 0===t?{}:t,{errorText:o,errorType:n}=i,r=s(i,["errorText","errorType"]),l=s(e,["screenState"]);return Object.assign(Object.assign({},l),{screenState:r})})),null===(i=this.stepState)||void 0===i||i.subscribe(e(this,ve,"m",We).bind(this),(e=>{var t,i;return{errorText:null===(t=null==e?void 0:e.screenState)||void 0===t?void 0:t.errorText,errorType:null===(i=null==e?void 0:e.screenState)||void 0===i?void 0:i.errorType}}),{forceUpdate:!0}),null===(o=this.stepState)||void 0===o||o.subscribe(e(this,ve,"m",xe).bind(this),(e=>{var t,i;return{errorText:null===(t=null==e?void 0:e.screenState)||void 0===t?void 0:t.errorText,errorType:null===(i=null==e?void 0:e.screenState)||void 0===i?void 0:i.errorType}}),{forceUpdate:!0}),null===(n=this.flowState)||void 0===n||n.subscribe((({screenId:e,executionId:t})=>{var i;try{this.updateTelemetryContext({screenId:e,executionId:t})}catch(e){null===(i=this.logger)||void 0===i||i.error("Error updating telemetry screenId:",e)}}),(e=>({screenId:e.screenId,executionId:e.executionId})))},xe=function({errorText:e,errorType:t}){(t||e)&&(this.contentRootElement.querySelectorAll('descope-passcode[data-auto-submit="true"]').forEach((e=>{e.shadowRoot.querySelectorAll("descope-text-field[data-id]").forEach((e=>{e.value=""}))})),j(this.contentRootElement,this.autoFocus,!1))},Ee=function(){return i(this,void 0,void 0,(function*(){this.loggerWrapper.debug("Trying to restart the flow");const e=yield this.getComponentsVersion();this.reset();e===(yield this.getComponentsVersion())?(this.loggerWrapper.debug("Components version was not changed, restarting flow"),this.flowState.update(Object.assign({stepId:null,executionId:null},this.adoptedSsoQueryParams))):this.loggerWrapper.error("Components version mismatch, please reload the page")}))},Ae=function(o){return i(this,void 0,void 0,(function*(){var i;const n=Object.assign(Object.assign({},this.stepState.current),o),{next:r,stepName:l}=n,a=s(n,["next","stepName"]),d=L(a);let c=yield e(this,ve,"m",Ie).call(this,l,d,r);c||(c=Boolean(yield null===(i=this.onScreenUpdate)||void 0===i?void 0:i.call(this,l,d,r,this)));const p=!this.stepState.current.htmlFilename;if(e(this,Te,"f").call(this,c),r&&(r.isCustomScreen=c),e(this,Oe,"f")!==c){const[i,s]=["flow","custom"].sort((()=>c?-1:1));this.loggerWrapper.debug(`Switching from ${s} screen to ${i} screen`),t(this,Oe,c,"f"),c?this.stepState.unsubscribeAll():e(this,ve,"m",Ce).call(this)}c?(this.loggerWrapper.debug("Showing a custom screen"),e(this,ve,"m",qe).call(this,{isFirstScreen:p,isCustomScreen:c,stepName:o.stepName}),this.disableKeyPressHandler()):this.handleKeyPress(),this.stepState.forceUpdate=c}))},je=function(e,t){return i(this,void 0,void 0,(function*(){const i=new AbortController;try{const s=e===l.webauthnCreate?this.sdk.webauthn.helpers.create(t,i):this.sdk.webauthn.helpers.get(t,i),o=yield S(m,s,lt);return o!==lt?{response:o}:(i.abort(),this.loggerWrapper.warn(`WebAuthn operation timed out after ${m}ms`),{failure:"AbortError",failureReason:"aborted",failureMessage:"Passkey operation timed out"})}catch(e){return"InvalidStateError"===e.name?this.loggerWrapper.warn("WebAuthn operation failed",e.message):"NotAllowedError"!==e.name&&this.loggerWrapper.error(e.message),{failure:e.name,failureReason:e.reason,failureMessage:e.message}}}))},Pe=function(e){this.contentRootElement.addEventListener("transitionend",(()=>{this.loggerWrapper.debug("page switch transition end"),this.contentRootElement.classList.remove("fade-out"),e()}),{once:!0}),this.loggerWrapper.debug("page switch transition start"),this.contentRootElement.classList.add("fade-out")},Ve=function(e){const t=e.getAttribute("name");if(!["email"].includes(t)){const i=`user-${t}`;e.setAttribute("name",i),e.addEventListener("input",(()=>{e.setAttribute("name",e.value?t:i)}))}},Me=function(s,o){return i(this,void 0,void 0,(function*(){var n;null===(n=e(this,fe,"f"))||void 0===n||n.abort();const r=s.querySelector('*[autocomplete="webauthn"]');if(r&&(yield J())){const{options:s,transactionId:n}=(yield e(this,Ne,"f").call(this))||{};s&&n&&(e(this,ve,"m",Ve).call(this,r),t(this,fe,new AbortController,"f"),this.sdk.webauthn.helpers.conditional(s,e(this,fe,"f")).then((e=>i(this,void 0,void 0,(function*(){o(r.id,{transactionId:n,response:e})})))).catch((e=>{"AbortError"!==e.name&&this.loggerWrapper.error("Conditional login failed",e.message)})))}}))},qe=function({isFirstScreen:t,isCustomScreen:i,stepName:s}){t&&e(this,ve,"m",nt).call(this,"ready",{}),i||e(this,ve,"m",ke).call(this,s),e(this,ve,"m",nt).call(this,"page-updated",{screenName:s}),e(this,ve,"m",nt).call(this,"screen-updated",{screenName:s})},_e=function(e,t,i){this.setValidationTrackingEnabled(!!e.clientValidationTrackingEnabled),t&&i("executionId")&&this.setValidationTrackingExecution(t)},Ke=function(){var t,i,s,o,n,r,l;const a=null===(t=this.flowState)||void 0===t?void 0:t.current;return(null==a?void 0:a.executionId)?{executionId:a.executionId,screenId:a.screenId,screenName:(null===(l=null===(r=this.stepState)||void 0===r?void 0:r.current)||void 0===l?void 0:l.stepName)||a.stepName}:{executionId:void 0,screenId:null!==(i=e(this,De,"f"))&&void 0!==i?i:null==a?void 0:a.screenId,screenName:null!==(s=e(this,Be,"f"))&&void 0!==s?s:(null===(n=null===(o=this.stepState)||void 0===o?void 0:o.current)||void 0===n?void 0:n.stepName)||(null==a?void 0:a.stepName)}},He=function(){var e;return(null===(e=this.nativeOptions)||void 0===e?void 0:e.origin)||window.location.origin},Ge=function(){let t=!0;const i=[];return Array.from(this.shadowRoot.querySelectorAll("*[name]")).reverse().forEach((e=>{var s,o,n;"slot"===e.localName||le(e,this.contentRootElement)||(null===(s=e.reportValidity)||void 0===s||s.call(e),e.validity&&!e.validity.valid&&i.push(e),t&&(t=null===(n=null===(o=e.checkValidity)||void 0===o?void 0:o.call(e))||void 0===n||n))})),i.length&&this.trackValidationErrors(i,e(this,ve,"a",Ke)),t},Je=function(){return i(this,void 0,void 0,(function*(){const e=this.getInputs();return(yield Promise.all(e.map((e=>i(this,void 0,void 0,(function*(){return{name:e.getAttribute("name"),value:e.value}})))))).reduce(((e,t)=>Object.assign(Object.assign({},e),{[t.name]:t.value})),{})}))},ze=function(s){var o,n;const r=Array.from(this.contentRootElement.querySelectorAll(':not([disabled]), [disabled="false"]')).filter((e=>e!==s)),l=(null===(n=null===(o=this.flowState.current)||void 0===o?void 0:o.screenState)||void 0===n?void 0:n.clientScripts)||[];s.setAttribute("loading","true"),r.forEach((e=>e.setAttribute("disabled","true")));const a=()=>{s.removeAttribute("loading"),r.forEach((e=>{e.removeAttribute("disabled")}))},d=e=>i(this,void 0,void 0,(function*(){var s;this.loggerWrapper.debug("Restoring components state"),this.removeEventListener("popupclosed",d);if(!0===(null===(s=null==e?void 0:e.detail)||void 0===s?void 0:s.abandoned)&&l.length)return t(this,be,(()=>i(this,void 0,void 0,(function*(){try{yield this.loadSdkScripts(l)}catch(e){this.loggerWrapper.warn("Failed to refresh client scripts on popup close",null==e?void 0:e.message)}})))(),"f"),void a();a();const o=yield this.getFlowConfig(),n=[...o.clientScripts||[],...o.sdkScripts||[]];this.loadSdkScripts(n)})),c=()=>{var i;window.removeEventListener("pageshow",e(this,Qe,"f")),t(this,Qe,(e=>{e.persisted&&(this.logger.debug("Page was loaded from cache, restoring components state"),d())}),"f"),window.addEventListener("pageshow",e(this,Qe,"f"),{once:!0});const s=null===(i=this.stepState)||void 0===i?void 0:i.subscribe(((e,t)=>{e===t&&d(),this.removeEventListener("popupclosed",d),this.stepState.unsubscribe(s)}),(e=>e.screenId),{forceUpdate:!0})},p=this.nextRequestStatus.subscribe((({isLoading:e})=>{e?this.addEventListener("popupclosed",d,{once:!0}):(this.nextRequestStatus.unsubscribe(p),"success"===this.flowStatus?(this.removeEventListener("popupclosed",d),a()):c())}));return a},Xe=function(){F();this.contentRootElement.querySelectorAll('[external-input="true"]').forEach((t=>e(this,ve,"m",Ye).call(this,t)))},Ye=function(e){if(!e)return;e.querySelectorAll("input").forEach((t=>{const i=t.getAttribute("slot"),s=`input-${e.id}-${i}`,o=document.createElement("slot");o.setAttribute("name",s),o.setAttribute("slot",i),e.appendChild(o),t.setAttribute("slot",s),this.appendChild(t)}))},et=function(t){return i(this,void 0,void 0,(function*(){if(e(this,be,"f")){this.loggerWrapper.debug("Waiting for sdk scripts to load");const t=Date.now();yield e(this,be,"f"),this.loggerWrapper.debug("Sdk scripts loaded for",(Date.now()-t).toString())}const i=this.loadSdkScriptsModules(),s=t.map((e=>e.id));for(const e of i)if(s.includes(e.id))try{if("function"==typeof e.present){(yield e.present())||this.loggerWrapper.debug(`Sdk script ${e.id} was cancelled`)}}catch(t){this.loggerWrapper.error(`Failed to present ${e.id} script module`,t.message)}const o=[];for(const e of i)"function"==typeof e.refresh&&o.push(e.refresh());if(o.length>0)try{yield S(u,Promise.all(o),null)}catch(e){this.loggerWrapper.error("Failed to refresh script module",e.message)}}))},tt=function(t,i){this.contentRootElement.querySelectorAll('descope-passcode[data-auto-submit="true"]').forEach((s=>{s.addEventListener("input",(()=>{var o;(null===(o=s.checkValidity)||void 0===o?void 0:o.call(s))&&e(this,Ze,"f").call(this,s,t,i)}))}))},it=function(e,t,i){t&&i&&"true"===e.getAttribute(f)&&re(i,t,this.loggerWrapper)},st=function(e){var t;const i=this.sdk.getLastUserLoginId(),s=null===(t=ne(i,this.loggerWrapper).lastUsedPerScreen)||void 0===t?void 0:t[e];if(!s)return;const o=this.contentRootElement.querySelector(b),n=this.contentRootElement.querySelector(`#${CSS.escape(s)}`);o&&n&&(n.replaceWith(o),o.appendChild(n))},ot=function(t,i){this.contentRootElement.querySelectorAll(`descope-button:not([${w}]), [data-type="button"]:not([${w}]`).forEach((s=>{s.onclick=()=>{e(this,Ze,"f").call(this,s,t,i)}})),e(this,ve,"m",tt).call(this,t,i),this.isDismissScreenErrorOnInput&&this.contentRootElement.querySelectorAll(`*[name]:not([${g}])`).forEach((e=>{e.addEventListener("input",(()=>{this.stepState.update((e=>Object.assign(Object.assign({},e),{screenState:Object.assign(Object.assign({},e.screenState),{errorText:"",errorType:""})})))}))}))},nt=function(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t}))},rt=function(e,t,i){var s;const[o,n]=(null===(s=window.name)||void 0===s?void 0:s.split("|"))||[],r="descope-wc"===o&&!!n,l=r?$(n):void 0;r&&!l&&this.loggerWrapper.warn("Popup opener origin is not approved for this project, add it to the approved domains to send the OAuth result to it",n);const a={data:{code:t,exchangeError:i},action:"code"};if(l){this.loggerWrapper.debug("Using postMessage fallback to notify opener in origin",l);try{window.opener.postMessage(a,l)}catch(e){this.loggerWrapper.error("Failed to send postMessage fallback (likely COOP isolation)",null==e?void 0:e.message)}}else{this.loggerWrapper.debug("Creating popup channel",e);const t=new BroadcastChannel(e);t.postMessage(a),t.close()}try{window.close()}catch(e){}},at.bridgeVersion=3;export{at as default};
1
+ import{__classPrivateFieldGet as e,__classPrivateFieldSet as t,__awaiter as i,__rest as s}from"tslib";import{getUserLocale as o}from"@descope/sdk-helpers";import{ensureFingerprintIds as n,clearFingerprintData as r}from"@descope/web-js-sdk";import{RESPONSE_ACTIONS as l,CUSTOM_INTERACTIONS as a,URL_CODE_PARAM_NAME as d,URL_ERR_PARAM_NAME as c,URL_TOKEN_PARAM_NAME as p,URL_RUN_IDS_PARAM_NAME as h,CLIENT_SIGNALS_SCRIPT_ID as u,SDK_SCRIPTS_LOAD_TIMEOUT as g,DESCOPE_ATTRIBUTE_EXCLUDE_FIELD as v,ELEMENT_TYPE_ATTRIBUTE as m,WEBAUTHN_TIMEOUT as f,DESCOPE_ATTRIBUTE_OPT_IN_LAST_USED as b,DESCOPE_LAST_AUTH_BADGE_COMPONENT as w,DESCOPE_ATTRIBUTE_EXCLUDE_NEXT_BUTTON as S}from"../constants/index.js";import{timeoutPromise as y,withMemCache as I,leadingDebounce as k,getIdFromExecId as R,showFirstScreenOnExecutionInit as W,injectSamlIdpForm as C,injectWsFedIdpForm as x,openCenteredPopup as E,getAnimationDirection as O,transformScreenInputs as A,handleReportValidityOnBlur as j,handleAutoFocus as T,getScriptResultPath as P,getElementDescopeAttributes as U,submitForm as L,transformStepStateForCustomScreen as F,clearPreviousExternalInputs as $,getTrustedPopupOpenerOrigin as N}from"../helpers/helpers.js";import M from"../helpers/state.js";import{disableWebauthnButtons as V,updateTemplateFromScreenState as q,setComponentsAutoDetectByGeo as D,setComponentsAutoDetectByLocale as B,setTOTPVariable as _,setNOTPVariable as K,setCssVars as H,updateScreenFromScreenState as G,replaceElementMessage as J}from"../helpers/templates.js";import{isConditionalLoginSupported as Q}from"../helpers/webauthn.js";import{clearSsoQueryParams as z,linkRunToSsoContext as X,pickSsoQueryParams as Y,clearSsoContextOnAppRedirect as Z}from"../helpers/oidcSession.js";import{getABTestingKey as ee}from"../helpers/abTestingKey.js";import{calculateConditions as te,calculateCondition as ie}from"../helpers/conditions.js";import{setLastAuth as se,getInFlightLastUsedPerScreen as oe,clearInFlightLastAuth as ne,getLastAuth as re,updateLastUsedPerScreen as le}from"../helpers/lastAuth.js";import{isHiddenByCondition as ae}from"../helpers/realtime-conditions/applier.js";import de from"./BaseDescopeWc.js";import{FETCH_EXCEPTION_ERROR_CODE as ce,FLOW_TIMED_OUT_ERROR_CODE as pe,POLLING_STATUS_NOT_FOUND_ERROR_CODE as he,NONCE_VALIDATION_ERROR_CODE as ue,FETCH_ERROR_RESPONSE_ERROR_CODE as ge,FLOW_REQUESTED_IS_IN_OLD_VERSION_ERROR_CODE as ve}from"../constants/general.js";var me,fe,be,we,Se,ye,Ie,ke,Re,We,Ce,xe,Ee,Oe,Ae,je,Te,Pe,Ue,Le,Fe,$e,Ne,Me,Ve,qe,De,Be,_e,Ke,He,Ge,Je,Qe,ze,Xe,Ye,Ze,et,tt,it,st,ot,nt,rt,lt,at;const dt="__descope_webauthn_timed_out__";class ct extends de{static set sdkConfigOverrides(e){de.sdkConfigOverrides=e}static get sdkConfigOverrides(){return de.sdkConfigOverrides}constructor(){const s=new M({deferredRedirect:!1,deferredPolling:!1});super(s.update.bind(s)),me.add(this),this.stepState=new M({}),fe.set(this,void 0),be.set(this,null),we.set(this,null),Se.set(this,new Map),ye.set(this,{visibilitychange:e(this,me,"m",Ie).bind(this)}),this.bridgeVersion=ct.bridgeVersion,ke.set(this,void 0),this.nativeCallbacks={},je.set(this,!1),this.handleRedirect=e=>{window.location.assign(e)},Ue.set(this,(t=>{t&&this.clearEmailVerification();const i=()=>{this.contentRootElement.classList.toggle("hidden",t),this.slotElement.classList.toggle("hidden",!t),t&&(this.contentRootElement.innerHTML="")};t&&this.contentRootElement.hasChildNodes()?e(this,me,"m",Le).call(this,i):i()})),Fe.set(this,((s,o,n,r,d=!1)=>{const c=[pe,he,ue];if(this.flowState.current.action===l.poll){if(e(this,Ne,"f").call(this)&&document.hidden)return this.logger.debug("polling - Deferring polling until in foreground"),void this.flowState.update({deferredPolling:!0});this.logger.debug("polling - Scheduling polling request");const l=Date.now(),p=d?500:2e3;t(this,fe,setTimeout((()=>i(this,void 0,void 0,(function*(){var t,i;this.logger.debug("polling - Calling next");const h=this.sdk.flow.next(s,o,a.polling,n,r,{}),u=document.hidden&&!d&&Date.now()-l>p+500;let g;u&&this.logger.debug("polling - The polling seems to be throttled");try{const e=u?1e3:6e3;g=yield y(e,h)}catch(t){return this.logger.warn(`polling - The ${u?"throttled fetch":"fetch"} call timed out or was aborted`),void e(this,Fe,"f").call(this,s,o,n,r,u)}if((null===(t=null==g?void 0:g.error)||void 0===t?void 0:t.errorCode)===ce)return this.logger.debug("polling - Got a generic error due to exception in fetch call"),void e(this,Fe,"f").call(this,s,o,n,r);this.logger.debug("polling - Got a response"),(null==g?void 0:g.error)&&this.logger.debug("polling - Response has an error",JSON.stringify(g.error,null,4)),(null===(i=null==g?void 0:g.error)||void 0===i?void 0:i.errorCode)&&c.includes(g.error.errorCode)?this.logger.debug("polling - Stopping polling due to error"):e(this,Fe,"f").call(this,s,o,n,r),e(this,Me,"f").call(this,g)}))),p),"f")}})),$e.set(this,(()=>{clearTimeout(e(this,fe,"f")),t(this,fe,null,"f")})),Ne.set(this,(()=>!!window.descopeBridge||/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent))),Me.set(this,(i=>{var s,o,n,r,a,d,c,p,h,u,g,v,m;if(!(null==i?void 0:i.ok)){const t=null===(s=null==i?void 0:i.response)||void 0===s?void 0:s.url,l=`${null===(o=null==i?void 0:i.response)||void 0===o?void 0:o.status} - ${null===(n=null==i?void 0:i.response)||void 0===n?void 0:n.statusText}`;e(this,me,"m",lt).call(this,"error",(null==i?void 0:i.error)||{errorCode:ge,errorDescription:l,errorMessage:t}),this.loggerWrapper.error((null===(r=null==i?void 0:i.error)||void 0===r?void 0:r.errorDescription)||t,(null===(a=null==i?void 0:i.error)||void 0===a?void 0:a.errorMessage)||l);const c=null===(d=null==i?void 0:i.error)||void 0===d?void 0:d.errorCode;return void(c!==ve&&c!==pe&&c!==ue||!this.isRestartOnError||e(this,me,"m",Ae).call(this))}null===(p=null===(c=i.data)||void 0===c?void 0:c.runnerLogs)||void 0===p||p.forEach((e=>{const{level:t,title:i,log:s}=e;t&&this.loggerWrapper[t]?this.loggerWrapper[t](i,s):this.loggerWrapper.info(i,s)}));const f=null===(g=null===(u=null===(h=i.data)||void 0===h?void 0:h.screen)||void 0===u?void 0:u.state)||void 0===g?void 0:g.errorText;(null===(v=i.data)||void 0===v?void 0:v.error)?this.loggerWrapper.error(`[${i.data.error.code}]: ${i.data.error.description}`,`${f?`${f} - `:""}${i.data.error.message}`):f&&this.loggerWrapper.error(f);const{status:b,authInfo:w,lastAuth:S,action:y,openInNewTabUrl:I}=i.data;if(y!==l.poll&&e(this,$e,"f").call(this),"completed"===b){this.storeLastAuthenticatedUser&&se(Object.assign(Object.assign({},S),{lastUsedPerScreen:oe()})),ne(this.loggerWrapper);const t=Object.assign({},w);return i.data.output&&Object.keys(i.data.output).length>0&&(t.flowOutput=i.data.output),this.setValidationTrackingExecution(i.data.executionId),z(this.projectId,this.flowId),void e(this,me,"m",lt).call(this,"success",t)}this.storeLastAuthenticatedUser&&se(S,!0),I&&window.open(I,"_blank");const{executionId:k,stepId:R,stepName:W,screen:C,redirect:x,webauthn:E,error:O,samlIdpResponse:A,wsFedIdpResponse:j,nativeResponse:T}=i.data,P=Date.now();y!==l.poll?(this.loggerWrapper.info(`Step "${W||`#${R}`}" is ${b}`,"",{screen:C,status:b,stepId:R,stepName:W,action:y,error:O}),(null===(m=C.state)||void 0===m?void 0:m.clientScripts)&&t(this,we,this.loadSdkScripts(C.state.clientScripts),"f"),this.flowState.update({stepId:R,stepName:W,executionId:k,action:y,redirectTo:null==x?void 0:x.url,redirectIsPopup:null==x?void 0:x.isPopup,screenId:null==C?void 0:C.id,screenState:null==C?void 0:C.state,webauthnTransactionId:null==E?void 0:E.transactionId,webauthnOptions:null==E?void 0:E.options,samlIdpResponseUrl:null==A?void 0:A.url,samlIdpResponseSamlResponse:null==A?void 0:A.samlResponse,samlIdpResponseRelayState:null==A?void 0:A.relayState,wsFedIdpResponseUrl:null==j?void 0:j.url,wsFedIdpResponseWresult:null==j?void 0:j.wresult,wsFedIdpResponseWctx:null==j?void 0:j.wctx,nativeResponseType:null==T?void 0:T.type,nativePayload:null==T?void 0:T.payload,reqTimestamp:P})):this.flowState.update({action:y,reqTimestamp:P})})),Ve.set(this,I((()=>i(this,void 0,void 0,(function*(){var e;try{const t=yield this.sdk.webauthn.signIn.start("",window.location.origin);return t.ok||this.loggerWrapper.warn("Webauthn start failed",null===(e=null==t?void 0:t.error)||void 0===e?void 0:e.errorMessage),t.data}catch(e){this.loggerWrapper.warn("Webauthn start failed",e.message)}}))))),_e.set(this,void 0),Ke.set(this,void 0),Xe.set(this,null),tt.set(this,k(((t,s,o)=>i(this,void 0,void 0,(function*(){var i;if("true"!==t.getAttribute("loading")&&"true"!==t.getAttribute("disabled")){if("true"===t.getAttribute("formnovalidate")||e(this,me,"m",Qe).call(this)){const n=null==t?void 0:t.getAttribute("id");e(this,me,"m",ot).call(this,t,n,o);const r=e(this,me,"m",Ye).call(this,t);try{const o=yield e(this,me,"m",ze).call(this),r=U(t);this.nextRequestStatus.update({isLoading:!0});const l=yield this.emailVerificationToken(t),a=Object.assign(Object.assign(Object.assign(Object.assign({},r),o),{origin:e(this,me,"a",Je)}),l&&{evpToken:l}),d=yield s(n,a);this.nextRequestStatus.update({isLoading:!1}),this.captureLastSubmittedLoginId(o,null===(i=null==d?void 0:d.data)||void 0===i?void 0:i.executionId),this.storeCredentials(o)}catch(e){throw r(),e}}}else this.loggerWrapper.debug("Submit already in flight, ignoring")}))))),this.flowState=s,this.setValidationTrackingSender(((e,t)=>i(this,[e,t],void 0,(function*({executionId:e,events:t},{keepalive:i}){const s=yield this.sdk.flow.event(e,t,i);return{ok:s.ok,retryable:s.code>=500||429===s.code}}))))}nativeResume(t,i){var s,o,n,r,l,a;const u=JSON.parse(i);if("oauthWeb"===t||"sso"===t){let e,{exchangeCode:t}=u;if(!t){const i=new URL(u.url);t=null===(s=i.searchParams)||void 0===s?void 0:s.get(d),e=(null===(o=i.searchParams)||void 0===o?void 0:o.get(c))||void 0}null===(r=(n=this.nativeCallbacks).complete)||void 0===r||r.call(n,{exchangeCode:t,exchangeError:e,idpInitiated:!0})}else if("magicLink"===t){const t=new URL(u.url),i=t.searchParams.get(p),s=t.searchParams.get(h).split("_").pop();e(this,$e,"f").call(this),this.flowState.update({token:i,stepId:s,action:void 0})}else if("beforeScreen"===t){const{screenResolve:e}=this.nativeCallbacks;this.nativeCallbacks.screenResolve=null;const{override:t}=u;t||(this.nativeCallbacks.screenNext=null),null==e||e(t)}else if("resumeScreen"===t){const{interactionId:e,form:t}=u,{screenNext:i}=this.nativeCallbacks;this.nativeCallbacks.screenNext=null,null==i||i(e,t)}else null===(a=(l=this.nativeCallbacks).complete)||void 0===a||a.call(l,u)}loadSdkScriptsModules(){const e=this.shadowRoot.querySelectorAll("div[data-script-id]");return Array.from(e).map((e=>e.moduleRes)).filter((e=>!!e))}loadSdkScripts(t){const s=this.preview?null==t?void 0:t.filter((e=>e.id!==u)):t;if(!(null==s?void 0:s.length))return null;const o=(e,t)=>i=>{this.dispatchEvent(new CustomEvent("components-context",{detail:{[P(e.id,e.resultKey)]:i},bubbles:!0,composed:!0})),t(e.id)};this.loggerWrapper.debug(`Preparing to load scripts: ${s.map((e=>e.id)).join(", ")}`);const n=t=>i(this,void 0,void 0,(function*(){var i,s,r;const l=this.shadowRoot.querySelector(`[data-script-id="${t.id}"]`);if(l){this.loggerWrapper.debug("Script already loaded",t.id);const{moduleRes:e}=l;return null===(i=null==e?void 0:e.start)||void 0===i||i.call(e),e}if(!(null===(s=globalThis.descope)||void 0===s?void 0:s[t.id])){const i=e(this,Se,"f").get(t.id);if(i)return yield i,n(t);const s=this.injectNpmLib("@descope/flow-scripts","1.0.22",`dist/${t.id}.js`);e(this,Se,"f").set(t.id,s);try{yield s}finally{e(this,Se,"f").delete(t.id)}}const a=null===(r=globalThis.descope)||void 0===r?void 0:r[t.id];return new Promise(((e,i)=>{try{const i=a(t.initArgs,{baseUrl:this.baseUrl,ref:this},o(t,e),this.loggerWrapper);if(i){const s=document.createElement("div");s.setAttribute("data-script-id",t.id),s.moduleRes=i,this.shadowRoot.appendChild(s);const o=this.nextRequestStatus.subscribe((()=>{var e;this.loggerWrapper.debug("Stopping script",t.id),(null===(e=i.stop)||void 0===e?void 0:e.call(i))&&(this.nextRequestStatus.unsubscribe(o),this.loggerWrapper.debug("Removing script",t.id),this.shadowRoot.removeChild(s))}));"function"==typeof i.present&&e(t.id)}}catch(e){i(e)}}))})),r=Promise.all((null!=s?s:[]).map((e=>n(e).catch((t=>(this.loggerWrapper.warn(`Sdk script ${e.id} failed to load, continuing without it`,null==t?void 0:t.message),null))))));let l;const a=new Promise((e=>{l=setTimeout((()=>{this.loggerWrapper.warn("SDK scripts loading timeout"),e(!0)}),g)}));return Promise.race([r,a]).finally((()=>clearTimeout(l))).catch((e=>(this.loggerWrapper.warn("Sdk scripts failed to load, continuing without them",null==e?void 0:e.message),null)))}get isDismissScreenErrorOnInput(){return"true"===this.getAttribute("dismiss-screen-error-on-input")}init(){var e,i;if(!window.descopeBridge)return this._init();this.lazyInit=this._init,t(this,ke,null===(i=null===(e=null===window||void 0===window?void 0:window.descopeBridge)||void 0===e?void 0:e.registerFlow)||void 0===i?void 0:i.call(e,this),"f")}_init(){const t=Object.create(null,{init:{get:()=>super.init}});return i(this,void 0,void 0,(function*(){var i,s;this.shadowRoot.isConnected&&(null===(i=this.flowState)||void 0===i||i.subscribe(this.onFlowChange.bind(this)),e(this,me,"m",Ee).call(this),window.addEventListener("visibilitychange",e(this,ye,"f").visibilitychange)),yield null===(s=t.init)||void 0===s?void 0:s.call(this)}))}disconnectedCallback(){var i,s,o;super.disconnectedCallback(),this.teardownValidationTracking(),e(this,ke,"f")&&(null===(s=null===(i=window.descopeBridge)||void 0===i?void 0:i.unregisterFlow)||void 0===s||s.call(i,e(this,ke,"f")),t(this,ke,void 0,"f")),this.flowState.unsubscribeAll(),this.stepState.unsubscribeAll(),e(this,$e,"f").call(this),null===(o=e(this,be,"f"))||void 0===o||o.abort(),t(this,be,null,"f"),this.clearEmailVerification(),window.removeEventListener("visibilitychange",e(this,ye,"f").visibilitychange)}getHtmlFilenameWithLocale(e,t){return i(this,void 0,void 0,(function*(){let i;const s=o(e),n=yield this.getTargetLocales();return n.includes(s.locale)?i=`${t}-${s.locale}.html`:n.includes(s.fallback)&&(i=`${t}-${s.fallback}.html`),i}))}getPageContent(e,t){return i(this,void 0,void 0,(function*(){if(t)try{const{body:e}=yield this.fetchStaticResource(t,"text");return e}catch(i){this.loggerWrapper.error(`Failed to fetch flow page from ${t}. Fallback to url ${e}`,i)}try{const{body:t}=yield this.fetchStaticResource(e,"text");return t}catch(e){this.loggerWrapper.error("Failed to fetch flow page",e.message)}return null}))}onFlowChange(d,c,p){return i(this,void 0,void 0,(function*(){var h,u;const{projectId:g,flowId:v,tenant:m,stepId:f,executionId:b,action:w,screenId:S,screenState:y,redirectTo:I,redirectIsPopup:k,redirectUrl:j,token:T,code:P,isPopup:U,exchangeError:F,webauthnTransactionId:$,webauthnOptions:N,redirectAuthCodeChallenge:M,redirectAuthCallbackUrl:V,redirectAuthBackupCallbackUri:q,redirectAuthInitiator:D,locale:B,samlIdpResponseUrl:_,samlIdpResponseSamlResponse:K,samlIdpResponseRelayState:H,wsFedIdpResponseUrl:G,wsFedIdpResponseWresult:J,wsFedIdpResponseWctx:Q,nativeResponseType:z,nativePayload:se,reqTimestamp:oe}=d,le=s(d,["projectId","flowId","tenant","stepId","executionId","action","screenId","screenState","redirectTo","redirectIsPopup","redirectUrl","token","code","isPopup","exchangeError","webauthnTransactionId","webauthnOptions","redirectAuthCodeChallenge","redirectAuthCallbackUrl","redirectAuthBackupCallbackUri","redirectAuthInitiator","locale","samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState","wsFedIdpResponseUrl","wsFedIdpResponseWresult","wsFedIdpResponseWctx","nativeResponseType","nativePayload","reqTimestamp"]);let ae,de,ce;p("executionId")&&b&&X(R(b),Y(le),g,v);const pe=ee(),{outboundAppId:he,outboundAppScopes:ue}=this,ge=this.sdk.getLastUserLoginId();p("flowId")&&this.setValidationTrackingEnabled(!1);const ve=yield this.getFlowConfig();e(this,me,"m",He).call(this,ve,b,p);const fe=yield this.getProjectConfig(),Se=Object.entries(fe.flows||{}).reduce(((e,[t,i])=>(e[t]=i.version,e)),{}),ye=V&&M?{callbackUrl:V,codeChallenge:M,backupCallbackUri:q}:void 0,Ie=this.nativeOptions?{platform:this.nativeOptions.platform,bridgeVersion:this.nativeOptions.bridgeVersion,oauthProvider:this.nativeOptions.oauthProvider,oauthRedirect:this.nativeOptions.oauthRedirect,magicLinkRedirect:this.nativeOptions.magicLinkRedirect,ssoRedirect:this.nativeOptions.ssoRedirect,externalAuthRedirect:this.nativeOptions.externalAuthRedirect}:void 0;let ke={};if(!b){ne(this.loggerWrapper);const i=[...ve.clientScripts||[],...ve.sdkScripts||[]];if(ve.conditions){let e=[];({startScreenId:ae,conditionInteractionId:ce,startScreenName:de,clientScripts:e,componentsConfig:ke}=te({loginId:ge,code:P,token:T,abTestingKey:pe,lastAuth:re(ge,this.loggerWrapper)},ve.conditions)),i.push(...e||[])}else ve.condition?({startScreenId:ae,startScreenName:de,conditionInteractionId:ce}=ie(ve.condition,{loginId:ge,code:P,token:T,abTestingKey:pe,lastAuth:re(ge,this.loggerWrapper)})):(de=ve.startScreenName,ae=ve.startScreenId);if(t(this,_e,ae,"f"),t(this,Ke,de,"f"),t(this,we,this.loadSdkScripts(i),"f"),ve.fingerprintEnabled&&ve.fingerprintKey?yield n(ve.fingerprintKey,this.baseUrl):r(),!W(ae,le)){const t=yield this.sdk.flow.start(v,Object.assign(Object.assign(Object.assign(Object.assign({tenant:m,redirectAuth:ye},le),{client:this.client}),j&&{redirectUrl:j}),{lastAuth:re(ge,this.loggerWrapper),preview:this.preview,abTestingKey:pe,locale:o(B).locale,nativeOptions:Ie,outboundAppId:he,outboundAppScopes:ue}),ce,"",fe.componentsVersion,Se,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({origin:e(this,me,"a",Je)},this.formConfigValues),P?{exchangeCode:P,idpInitiated:!0}:{}),le.descopeIdpInitiated&&{idpInitiated:!0}),T?{token:T}:{}),le.oidcLoginHint?{externalId:le.oidcLoginHint}:{}));return e(this,Me,"f").call(this,t),void("completed"!==(null===(h=null==t?void 0:t.data)||void 0===h?void 0:h.status)&&this.flowState.update({code:void 0,token:void 0}))}}if(this.loggerWrapper.debug("Before popup postmessage send",JSON.stringify({isPopup:U,code:P,exchangeError:F,isCodeChanged:p("code"),isExchangeErrorChanged:p("exchangeError")})),U&&(p("code")&&P||p("exchangeError")&&F))return void e(this,me,"m",at).call(this,b,P,F);if(b&&(p("token")&&T||p("code")&&P||p("exchangeError")&&F)){const t=yield this.sdk.flow.next(b,f,a.submit,ve.version,fe.componentsVersion,{token:T,exchangeCode:P,exchangeError:F,origin:e(this,me,"a",Je)});return e(this,Me,"f").call(this,t),void this.flowState.update({token:void 0,code:void 0,exchangeError:void 0})}if(w===l.loadForm&&_&&["samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState"].some((e=>p(e)))){if(!K)return void this.loggerWrapper.error("Did not get saml idp params data to load");C(_,K,H||"",L)}if(w===l.loadForm&&G&&["wsFedIdpResponseUrl","wsFedIdpResponseWresult","wsFedIdpResponseWctx"].some((e=>p(e)))){if(!J)return void this.loggerWrapper.error("Did not get wsfed idp params data to load");x(G,J,Q||"",L)}if(w===l.redirect&&(p("redirectTo")||p("deferredRedirect"))){if(!I)return void this.loggerWrapper.error("Did not get redirect url");if("no-op"===I)return;if("android"===D&&document.hidden)return void this.flowState.update({deferredRedirect:!0});if(this.loggerWrapper.debug(`Redirect is popup ${k}`),k){this.loggerWrapper.debug("Opening redirect in popup");const t=E(I,"?",598,700),i=this.shouldUsePopupPostMessage();i&&(t.name=`descope-wc|${window.location.origin}`),this.loggerWrapper.debug("Popup communication method: "+(i?"postMessage":"BroadcastChannel"));let s=!1;const o=e=>{this.loggerWrapper.debug("Received popup message",JSON.stringify(e.data));const t=i?this.popupOrigin:window.location.origin;if(e.origin!==t)return void this.loggerWrapper.debug(`Ignoring message from unexpected origin. received: "${e.origin}", expected: "${t}"`);const{action:o,data:n}=e.data||{};"code"===o&&(s=!0,this.flowState.update({code:n.code,exchangeError:n.exchangeError}))};let n;this.loggerWrapper.debug("Starting popup closed detection");const r=setInterval((()=>{t.closed&&(this.loggerWrapper.debug("Popup closed, dispatching popupclosed event"),clearInterval(r),e(this,me,"m",lt).call(this,"popupclosed",{abandoned:!s}),this.loggerWrapper.debug("Cleaning up popup listeners"),null==n||n())}),1e3);if(i)window.addEventListener("message",o),n=()=>{this.loggerWrapper.debug("Cleaning up popup postMessage listener"),window.removeEventListener("message",o)};else{this.loggerWrapper.debug("Creating broadcast channel");const e=new BroadcastChannel(b);e.onmessage=o,n=()=>{this.loggerWrapper.debug("Closing channel"),e.close()}}}else Z(I,R(b),Object.assign(Object.assign({},this.adoptedSsoQueryParams),Y(le)),g,v),this.handleRedirect(I),this.flowState.update({redirectTo:"no-op"}),e(this,me,"m",lt).call(this,"popupclosed",{});return}if(w===l.webauthnCreate||w===l.webauthnGet){if(!$||!N)return void this.loggerWrapper.error("Did not get webauthn transaction id or options");null===(u=e(this,be,"f"))||void 0===u||u.abort(),t(this,be,null,"f");const i=yield e(this,me,"m",Pe).call(this,w,N),s=yield this.sdk.flow.next(b,f,a.submit,ve.version,fe.componentsVersion,Object.assign({transactionId:$},i));e(this,Me,"f").call(this,s)}if(w===l.nativeBridge)return this.nativeCallbacks.complete=t=>i(this,void 0,void 0,(function*(){const i=yield this.sdk.flow.next(b,f,a.submit,ve.version,fe.componentsVersion,t);e(this,Me,"f").call(this,i)})),e(this,me,"m",Ce).call(this,z,se),void setTimeout((()=>{this.dispatchEvent(new Event("popupclosed"))}),500);if((p("action")||p("deferredPolling"))&&e(this,Fe,"f").call(this,b,f,ve.version,fe.componentsVersion),!S&&!ae)return void this.loggerWrapper.warn("No screen was found to show");const Re=ae||S,We=yield this.getHtmlFilenameWithLocale(B,Re),{oidcLoginHint:xe,oidcPrompt:Ee,oidcErrorRedirectUri:Oe,oidcResource:Ae,samlIdpUsername:je}=le,Ue={direction:O(f,c.stepId),screenState:Object.assign(Object.assign({},y),{form:Object.assign(Object.assign({},this.formConfigValues),null==y?void 0:y.form),lastAuth:{loginId:ge,name:this.sdk.getLastUserDisplayName()||ge},componentsConfig:Object.assign(Object.assign(Object.assign({},ve.componentsConfig),ke),null==y?void 0:y.componentsConfig)}),htmlFilename:`${Re}.html`,htmlLocaleFilename:We,screenId:Re,stepName:d.stepName||de,samlIdpUsername:je,oidcLoginHint:xe,oidcPrompt:Ee,oidcErrorRedirectUri:Oe,oidcResource:Ae,action:w,locale:o(B).locale},Le=re(ge,this.loggerWrapper);W(ae,le)?Ue.next=(t,s)=>i(this,void 0,void 0,(function*(){const i=(null==ve?void 0:ve.clientScripts)||[];yield e(this,me,"m",it).call(this,i);const n=yield this.sdk.flow.start(v,Object.assign(Object.assign(Object.assign(Object.assign({tenant:m,redirectAuth:ye},le),{lastAuth:Le,preview:this.preview,abTestingKey:pe,client:this.client}),j&&{redirectUrl:j}),{locale:o(B).locale,nativeOptions:Ie,outboundAppId:he,outboundAppScopes:ue}),ce,t,fe.componentsVersion,Se,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({origin:e(this,me,"a",Je)},this.formConfigValues),this.getComponentsContext()),A(s)),P&&{exchangeCode:P,idpInitiated:!0}),le.descopeIdpInitiated&&{idpInitiated:!0}),T&&{token:T}),Ue.next.isCustomScreen);return e(this,Me,"f").call(this,n),n})):(p("projectId")||p("baseUrl")||p("executionId")||p("stepId"))&&(Ue.next=(t,s)=>i(this,void 0,void 0,(function*(){const i=(null==y?void 0:y.clientScripts)||[];yield e(this,me,"m",it).call(this,i);const o=yield this.sdk.flow.next(b,f,t,ve.version,fe.componentsVersion,Object.assign(Object.assign({origin:e(this,me,"a",Je)},this.getComponentsContext()),A(s)),Ue.next.isCustomScreen);return e(this,Me,"f").call(this,o),o}))),this.loggerWrapper.debug("Got a screen with id",Ue.screenId),yield e(this,me,"m",Te).call(this,Ue),this.stepState.update(Ue)}))}onStepChange(t,s){return i(this,void 0,void 0,(function*(){var o,n,r;const{htmlFilename:l,htmlLocaleFilename:d,direction:c,next:p,screenState:h,screenId:u}=t;this.loggerWrapper.debug("Rendering a flow screen"),this.clearEmailVerification(),this.updateScreenUser(null==h?void 0:h.user);const g=document.createElement("template");g.innerHTML=yield this.getPageContent(l,d);const v=g.content.cloneNode(!0),f=this.loadDescopeUiComponents(g);this.sdk.webauthn.helpers.isSupported()?yield e(this,me,"m",De).call(this,v,p):V(v),!t.samlIdpUsername||(null===(o=h.form)||void 0===o?void 0:o.loginId)||(null===(n=h.form)||void 0===n?void 0:n.email)||(h.form||(h.form={}),h.form.loginId=t.samlIdpUsername,h.form.email=t.samlIdpUsername),q(v,h,this.formConfig,this.loggerWrapper),this.applyComponentsState(v,null==h?void 0:h.componentsState),this.startEmailVerification(v);const{geo:b}=null!==(r=yield this.getExecutionContext())&&void 0!==r?r:{};D(v,b),B(v,t.locale);const w=()=>i(this,void 0,void 0,(function*(){var i,o;yield f;const n=this.contentRootElement;_(n,null===(i=null==h?void 0:h.totp)||void 0===i?void 0:i.image),K(n,null===(o=null==h?void 0:h.notp)||void 0===o?void 0:o.image),H(n,v,h.cssVars,this.loggerWrapper),n.replaceChildren(v);const r=!s.htmlFilename;setTimeout((()=>{e(this,me,"m",Ze).call(this),this.updateUsernameAnchor(),this.validateOnBlur&&j(n,(t=>this.trackValidationErrors([t],e(this,me,"a",Ge)))),G(n,h),this.initRealtimeConditions(n,h),e(this,me,"m",Be).call(this,{isFirstScreen:r,isCustomScreen:!1,stepName:t.stepName}),T(n,this.autoFocus,r),e(this,me,"m",nt).call(this,u)})),e(this,me,"m",rt).call(this,p,u);n.querySelector(`[${m}="polling"]`)&&p(a.polling,{})}));c?e(this,me,"m",Le).call(this,w):w()}))}getInputs(){return Array.from(this.shadowRoot.querySelectorAll(`*:not(slot)[name]:not([${v}])`))}shouldUsePopupPostMessage(){if(!this.popupOrigin)return!1;try{new URL(this.popupOrigin)}catch(e){return!1}return!0}}fe=new WeakMap,be=new WeakMap,we=new WeakMap,Se=new WeakMap,ye=new WeakMap,ke=new WeakMap,je=new WeakMap,Ue=new WeakMap,Fe=new WeakMap,$e=new WeakMap,Ne=new WeakMap,Me=new WeakMap,Ve=new WeakMap,_e=new WeakMap,Ke=new WeakMap,Xe=new WeakMap,tt=new WeakMap,me=new WeakSet,Ie=function(){document.hidden||setTimeout((()=>{this.flowState.update({deferredRedirect:!1,deferredPolling:!1})}),300)},Re=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,me,"m",Ce).call(this,"beforeScreen",{screen:t,context:s})}))}))},We=function(t){var i;(null===(i=this.nativeOptions)||void 0===i?void 0:i.bridgeVersion)>=2&&e(this,me,"m",Ce).call(this,"afterScreen",{screen:t})},Ce=function(t,i){e(this,me,"m",lt).call(this,"bridge",{type:t,payload:i})},xe=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)}J(this.contentRootElement,"error-message",s)};this.addEventListener("screen-updated",i,{once:!0}),i()},Ee=function(){var t,i,o,n;null===(t=this.stepState)||void 0===t||t.subscribe(this.onStepChange.bind(this),(e=>{var t=e.screenState,i=void 0===t?{}:t,{errorText:o,errorType:n}=i,r=s(i,["errorText","errorType"]),l=s(e,["screenState"]);return Object.assign(Object.assign({},l),{screenState:r})})),null===(i=this.stepState)||void 0===i||i.subscribe(e(this,me,"m",xe).bind(this),(e=>{var t,i;return{errorText:null===(t=null==e?void 0:e.screenState)||void 0===t?void 0:t.errorText,errorType:null===(i=null==e?void 0:e.screenState)||void 0===i?void 0:i.errorType}}),{forceUpdate:!0}),null===(o=this.stepState)||void 0===o||o.subscribe(e(this,me,"m",Oe).bind(this),(e=>{var t,i;return{errorText:null===(t=null==e?void 0:e.screenState)||void 0===t?void 0:t.errorText,errorType:null===(i=null==e?void 0:e.screenState)||void 0===i?void 0:i.errorType}}),{forceUpdate:!0}),null===(n=this.flowState)||void 0===n||n.subscribe((({screenId:e,executionId:t})=>{var i;try{this.updateTelemetryContext({screenId:e,executionId:t})}catch(e){null===(i=this.logger)||void 0===i||i.error("Error updating telemetry screenId:",e)}}),(e=>({screenId:e.screenId,executionId:e.executionId})))},Oe=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=""}))})),T(this.contentRootElement,this.autoFocus,!1))},Ae=function(){return i(this,void 0,void 0,(function*(){this.loggerWrapper.debug("Trying to restart the flow");const e=yield this.getComponentsVersion();this.reset();e===(yield this.getComponentsVersion())?(this.loggerWrapper.debug("Components version was not changed, restarting flow"),this.flowState.update(Object.assign({stepId:null,executionId:null},this.adoptedSsoQueryParams))):this.loggerWrapper.error("Components version mismatch, please reload the page")}))},Te=function(o){return i(this,void 0,void 0,(function*(){var i;const n=Object.assign(Object.assign({},this.stepState.current),o),{next:r,stepName:l}=n,a=s(n,["next","stepName"]),d=F(a);let c=yield e(this,me,"m",Re).call(this,l,d,r);c||(c=Boolean(yield null===(i=this.onScreenUpdate)||void 0===i?void 0:i.call(this,l,d,r,this)));const p=!this.stepState.current.htmlFilename;if(e(this,Ue,"f").call(this,c),r&&(r.isCustomScreen=c),e(this,je,"f")!==c){const[i,s]=["flow","custom"].sort((()=>c?-1:1));this.loggerWrapper.debug(`Switching from ${s} screen to ${i} screen`),t(this,je,c,"f"),c?this.stepState.unsubscribeAll():e(this,me,"m",Ee).call(this)}c?(this.loggerWrapper.debug("Showing a custom screen"),e(this,me,"m",Be).call(this,{isFirstScreen:p,isCustomScreen:c,stepName:o.stepName}),this.disableKeyPressHandler()):this.handleKeyPress(),this.stepState.forceUpdate=c}))},Pe=function(e,t){return i(this,void 0,void 0,(function*(){const i=new AbortController;try{const s=e===l.webauthnCreate?this.sdk.webauthn.helpers.create(t,i):this.sdk.webauthn.helpers.get(t,i),o=yield y(f,s,dt);return o!==dt?{response:o}:(i.abort(),this.loggerWrapper.warn(`WebAuthn operation timed out after ${f}ms`),{failure:"AbortError",failureReason:"aborted",failureMessage:"Passkey operation timed out"})}catch(e){return"InvalidStateError"===e.name?this.loggerWrapper.warn("WebAuthn operation failed",e.message):"NotAllowedError"!==e.name&&this.loggerWrapper.error(e.message),{failure:e.name,failureReason:e.reason,failureMessage:e.message}}}))},Le=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")},qe=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)}))}},De=function(s,o){return i(this,void 0,void 0,(function*(){var n;null===(n=e(this,be,"f"))||void 0===n||n.abort();const r=s.querySelector('*[autocomplete="webauthn"]');if(r&&(yield Q())){const{options:s,transactionId:n}=(yield e(this,Ve,"f").call(this))||{};s&&n&&(e(this,me,"m",qe).call(this,r),t(this,be,new AbortController,"f"),this.sdk.webauthn.helpers.conditional(s,e(this,be,"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)})))}}))},Be=function({isFirstScreen:t,isCustomScreen:i,stepName:s}){t&&e(this,me,"m",lt).call(this,"ready",{}),i||e(this,me,"m",We).call(this,s),e(this,me,"m",lt).call(this,"page-updated",{screenName:s}),e(this,me,"m",lt).call(this,"screen-updated",{screenName:s})},He=function(e,t,i){this.setValidationTrackingEnabled(!!e.clientValidationTrackingEnabled),t&&i("executionId")&&this.setValidationTrackingExecution(t)},Ge=function(){var t,i,s,o,n,r,l;const a=null===(t=this.flowState)||void 0===t?void 0:t.current;return(null==a?void 0:a.executionId)?{executionId:a.executionId,screenId:a.screenId,screenName:(null===(l=null===(r=this.stepState)||void 0===r?void 0:r.current)||void 0===l?void 0:l.stepName)||a.stepName}:{executionId:void 0,screenId:null!==(i=e(this,_e,"f"))&&void 0!==i?i:null==a?void 0:a.screenId,screenName:null!==(s=e(this,Ke,"f"))&&void 0!==s?s:(null===(n=null===(o=this.stepState)||void 0===o?void 0:o.current)||void 0===n?void 0:n.stepName)||(null==a?void 0:a.stepName)}},Je=function(){var e;return(null===(e=this.nativeOptions)||void 0===e?void 0:e.origin)||window.location.origin},Qe=function(){let t=!0;const i=[];return Array.from(this.shadowRoot.querySelectorAll("*[name]")).reverse().forEach((e=>{var s,o,n;"slot"===e.localName||ae(e,this.contentRootElement)||(null===(s=e.reportValidity)||void 0===s||s.call(e),e.validity&&!e.validity.valid&&i.push(e),t&&(t=null===(n=null===(o=e.checkValidity)||void 0===o?void 0:o.call(e))||void 0===n||n))})),i.length&&this.trackValidationErrors(i,e(this,me,"a",Ge)),t},ze=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})),{})}))},Ye=function(s){var o,n;const r=Array.from(this.contentRootElement.querySelectorAll(':not([disabled]), [disabled="false"]')).filter((e=>e!==s)),l=(null===(n=null===(o=this.flowState.current)||void 0===o?void 0:o.screenState)||void 0===n?void 0:n.clientScripts)||[];s.setAttribute("loading","true"),r.forEach((e=>e.setAttribute("disabled","true")));const a=()=>{s.removeAttribute("loading"),r.forEach((e=>{e.removeAttribute("disabled")}))},d=e=>i(this,void 0,void 0,(function*(){var s;this.loggerWrapper.debug("Restoring components state"),this.removeEventListener("popupclosed",d);if(!0===(null===(s=null==e?void 0:e.detail)||void 0===s?void 0:s.abandoned)&&l.length)return t(this,we,(()=>i(this,void 0,void 0,(function*(){try{yield this.loadSdkScripts(l)}catch(e){this.loggerWrapper.warn("Failed to refresh client scripts on popup close",null==e?void 0:e.message)}})))(),"f"),void a();a();const o=yield this.getFlowConfig(),n=[...o.clientScripts||[],...o.sdkScripts||[]];this.loadSdkScripts(n)})),c=()=>{var i;window.removeEventListener("pageshow",e(this,Xe,"f")),t(this,Xe,(e=>{e.persisted&&(this.logger.debug("Page was loaded from cache, restoring components state"),d())}),"f"),window.addEventListener("pageshow",e(this,Xe,"f"),{once:!0});const s=null===(i=this.stepState)||void 0===i?void 0:i.subscribe(((e,t)=>{e===t&&d(),this.removeEventListener("popupclosed",d),this.stepState.unsubscribe(s)}),(e=>e.screenId),{forceUpdate:!0})},p=this.nextRequestStatus.subscribe((({isLoading:e})=>{e?this.addEventListener("popupclosed",d,{once:!0}):(this.nextRequestStatus.unsubscribe(p),"success"===this.flowStatus?(this.removeEventListener("popupclosed",d),a()):c())}));return a},Ze=function(){$();this.contentRootElement.querySelectorAll('[external-input="true"]').forEach((t=>e(this,me,"m",et).call(this,t)))},et=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)}))},it=function(t){return i(this,void 0,void 0,(function*(){if(e(this,we,"f")){this.loggerWrapper.debug("Waiting for sdk scripts to load");const t=Date.now();yield e(this,we,"f"),this.loggerWrapper.debug("Sdk scripts loaded for",(Date.now()-t).toString())}const i=this.loadSdkScriptsModules(),s=t.map((e=>e.id));for(const e of i)if(s.includes(e.id))try{if("function"==typeof e.present){(yield e.present())||this.loggerWrapper.debug(`Sdk script ${e.id} was cancelled`)}}catch(t){this.loggerWrapper.error(`Failed to present ${e.id} script module`,t.message)}const o=[];for(const e of i)"function"==typeof e.refresh&&o.push(e.refresh());if(o.length>0)try{yield y(g,Promise.all(o),null)}catch(e){this.loggerWrapper.error("Failed to refresh script module",e.message)}}))},st=function(t,i){this.contentRootElement.querySelectorAll('descope-passcode[data-auto-submit="true"]').forEach((s=>{s.addEventListener("input",(()=>{var o;(null===(o=s.checkValidity)||void 0===o?void 0:o.call(s))&&e(this,tt,"f").call(this,s,t,i)}))}))},ot=function(e,t,i){t&&i&&"true"===e.getAttribute(b)&&le(i,t,this.loggerWrapper)},nt=function(e){var t;const i=this.sdk.getLastUserLoginId(),s=null===(t=re(i,this.loggerWrapper).lastUsedPerScreen)||void 0===t?void 0:t[e];if(!s)return;const o=this.contentRootElement.querySelector(w),n=this.contentRootElement.querySelector(`#${CSS.escape(s)}`);o&&n&&(n.replaceWith(o),o.appendChild(n))},rt=function(t,i){this.contentRootElement.querySelectorAll(`descope-button:not([${S}]), [data-type="button"]:not([${S}]`).forEach((s=>{s.onclick=()=>{e(this,tt,"f").call(this,s,t,i)}})),e(this,me,"m",st).call(this,t,i),this.isDismissScreenErrorOnInput&&this.contentRootElement.querySelectorAll(`*[name]:not([${v}])`).forEach((e=>{e.addEventListener("input",(()=>{this.stepState.update((e=>Object.assign(Object.assign({},e),{screenState:Object.assign(Object.assign({},e.screenState),{errorText:"",errorType:""})})))}))}))},lt=function(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t}))},at=function(e,t,i){var s;const[o,n]=(null===(s=window.name)||void 0===s?void 0:s.split("|"))||[],r="descope-wc"===o&&!!n,l=r?N(n):void 0;r&&!l&&this.loggerWrapper.warn("Popup opener origin is not approved for this project, add it to the approved domains to send the OAuth result to it",n);const a={data:{code:t,exchangeError:i},action:"code"};if(l){this.loggerWrapper.debug("Using postMessage fallback to notify opener in origin",l);try{window.opener.postMessage(a,l)}catch(e){this.loggerWrapper.error("Failed to send postMessage fallback (likely COOP isolation)",null==e?void 0:e.message)}}else{this.loggerWrapper.debug("Creating popup channel",e);const t=new BroadcastChannel(e);t.postMessage(a),t.close()}try{window.close()}catch(e){}},ct.bridgeVersion=3;export{ct as default};
2
2
  //# sourceMappingURL=DescopeWc.js.map