@descope/web-component 3.36.1 → 3.37.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/descope-wc/BaseDescopeWc.js +1 -1
- package/dist/cjs/descope-wc/DescopeWc.js +1 -1
- package/dist/cjs/descope-wc/DescopeWc.js.map +1 -1
- package/dist/cjs/helpers/conditions.js +1 -1
- package/dist/cjs/helpers/conditions.js.map +1 -1
- package/dist/cjs/helpers/templates.js +1 -1
- package/dist/cjs/helpers/templates.js.map +1 -1
- package/dist/cjs/types.js.map +1 -1
- package/dist/esm/descope-wc/BaseDescopeWc.js +1 -1
- package/dist/esm/descope-wc/DescopeWc.js +1 -1
- package/dist/esm/descope-wc/DescopeWc.js.map +1 -1
- package/dist/esm/helpers/conditions.js +1 -1
- package/dist/esm/helpers/conditions.js.map +1 -1
- package/dist/esm/helpers/templates.js +1 -1
- package/dist/esm/helpers/templates.js.map +1 -1
- package/dist/esm/types.js.map +1 -1
- package/dist/index.d.ts +50 -43
- package/dist/index.js +2 -2
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"conditions.js","sources":["../../../src/lib/helpers/conditions.ts"],"sourcesContent":["import { ClientCondition, ConditionsMap, Context } from '../types';\n\nconst elseInteractionId = 'ELSE';\n\nconst conditionsMap: ConditionsMap = {\n 'lastAuth.loginId': {\n 'not-empty': (ctx) => !!ctx.loginId,\n empty: (ctx) => !ctx.loginId,\n },\n idpInitiated: {\n 'is-true': (ctx) => !!ctx.code,\n 'is-false': (ctx) => !ctx.code,\n },\n externalToken: {\n 'is-true': (ctx) => !!ctx.token,\n 'is-false': (ctx) => !ctx.token,\n },\n abTestingKey: {\n 'greater-than': (ctx, predicate: number) =>\n (ctx.abTestingKey || 0) > predicate,\n 'less-than': (ctx, predicate: number) =>\n (ctx.abTestingKey || 0) < predicate,\n },\n};\n\nexport const calculateCondition = (\n condition: ClientCondition,\n ctx: Context,\n) => {\n const checkFunc = conditionsMap[condition?.key]?.[condition.operator];\n if (!checkFunc) {\n return {};\n }\n const conditionResult = checkFunc(ctx, condition.predicate)\n ? condition.met\n : condition.unmet;\n return {\n startScreenId: conditionResult?.screenId,\n startScreenName: conditionResult?.screenName,\n conditionInteractionId: conditionResult?.interactionId,\n };\n};\n\n/* eslint-disable import/prefer-default-export */\nexport const calculateConditions = (\n ctx: Context,\n conditions?: ClientCondition[],\n) => {\n const conditionResult = conditions?.find(({ key, operator, predicate }) => {\n if (key === elseInteractionId) {\n return true;\n }\n const checkFunc = conditionsMap[key]?.[operator];\n return !!checkFunc?.(ctx, predicate);\n });\n return !conditionResult\n ? {}\n : {\n startScreenId: conditionResult.met.screenId,\n startScreenName: conditionResult.met.screenName,\n conditionInteractionId: conditionResult.met.interactionId,\n clientScripts: conditionResult.met.clientScripts,\n };\n};\n"],"names":["conditionsMap","ctx","loginId","empty","idpInitiated","code","externalToken","token","abTestingKey","predicate","condition","checkFunc","_a","key","operator","conditionResult","met","unmet","startScreenId","screenId","startScreenName","screenName","conditionInteractionId","interactionId","conditions","find","clientScripts"],"mappings":"aAEA,MAEMA,EAA+B,CACnC,mBAAoB,CAClB,YAAcC,KAAUA,EAAIC,QAC5BC,MAAQF,IAASA,EAAIC,SAEvBE,aAAc,CACZ,UAAYH,KAAUA,EAAII,KAC1B,WAAaJ,IAASA,EAAII,MAE5BC,cAAe,CACb,UAAYL,KAAUA,EAAIM,MAC1B,WAAaN,IAASA,EAAIM,OAE5BC,aAAc,CACZ,eAAgB,CAACP,EAAKQ,KACnBR,EAAIO,cAAgB,GAAKC,EAC5B,YAAa,CAACR,EAAKQ,KAChBR,EAAIO,cAAgB,GAAKC,+BAIE,CAChCC,EACAT,WAEA,MAAMU,EAAyC,QAA7BC,EAAAZ,EAAcU,aAAS,EAATA,EAAWG,YAAI,IAAAD,OAAA,EAAAA,EAAGF,EAAUI,UAC5D,IAAKH,EACH,MAAO,GAET,MAAMI,EAAkBJ,EAAUV,EAAKS,EAAUD,WAC7CC,EAAUM,IACVN,EAAUO,MACd,MAAO,CACLC,cAAeH,aAAA,EAAAA,EAAiBI,SAChCC,gBAAiBL,aAAA,EAAAA,EAAiBM,WAClCC,uBAAwBP,aAAA,EAAAA,EAAiBQ,cAC1C,8BAIgC,CACjCtB,EACAuB,KAEA,MAAMT,EAAkBS,aAAU,EAAVA,EAAYC,MAAK,EAAGZ,MAAKC,WAAUL,sBACzD,GA/CsB,SA+ClBI,EACF,OAAO,EAET,MAAMF,EAA8B,QAAlBC,EAAAZ,EAAca,UAAI,IAAAD,OAAA,EAAAA,EAAGE,GACvC,SAASH,aAAS,EAATA,EAAYV,EAAKQ,GAAU,IAEtC,OAAQM,EAEJ,CACEG,cAAeH,EAAgBC,IAAIG,SACnCC,gBAAiBL,EAAgBC,IAAIK,WACrCC,uBAAwBP,EAAgBC,IAAIO,cAC5CG,cAAeX,EAAgBC,IAAIU,
|
|
1
|
+
{"version":3,"file":"conditions.js","sources":["../../../src/lib/helpers/conditions.ts"],"sourcesContent":["import { ClientCondition, ConditionsMap, Context } from '../types';\n\nconst elseInteractionId = 'ELSE';\n\nconst conditionsMap: ConditionsMap = {\n 'lastAuth.loginId': {\n 'not-empty': (ctx) => !!ctx.loginId,\n empty: (ctx) => !ctx.loginId,\n },\n idpInitiated: {\n 'is-true': (ctx) => !!ctx.code,\n 'is-false': (ctx) => !ctx.code,\n },\n externalToken: {\n 'is-true': (ctx) => !!ctx.token,\n 'is-false': (ctx) => !ctx.token,\n },\n abTestingKey: {\n 'greater-than': (ctx, predicate: number) =>\n (ctx.abTestingKey || 0) > predicate,\n 'less-than': (ctx, predicate: number) =>\n (ctx.abTestingKey || 0) < predicate,\n },\n};\n\nexport const calculateCondition = (\n condition: ClientCondition,\n ctx: Context,\n) => {\n const checkFunc = conditionsMap[condition?.key]?.[condition.operator];\n if (!checkFunc) {\n return {};\n }\n const conditionResult = checkFunc(ctx, condition.predicate)\n ? condition.met\n : condition.unmet;\n return {\n startScreenId: conditionResult?.screenId,\n startScreenName: conditionResult?.screenName,\n conditionInteractionId: conditionResult?.interactionId,\n };\n};\n\n/* eslint-disable import/prefer-default-export */\nexport const calculateConditions = (\n ctx: Context,\n conditions?: ClientCondition[],\n) => {\n const conditionResult = conditions?.find(({ key, operator, predicate }) => {\n if (key === elseInteractionId) {\n return true;\n }\n const checkFunc = conditionsMap[key]?.[operator];\n return !!checkFunc?.(ctx, predicate);\n });\n return !conditionResult\n ? {}\n : {\n startScreenId: conditionResult.met.screenId,\n startScreenName: conditionResult.met.screenName,\n conditionInteractionId: conditionResult.met.interactionId,\n clientScripts: conditionResult.met.clientScripts,\n componentsConfig: conditionResult.met.componentsConfig,\n };\n};\n"],"names":["conditionsMap","ctx","loginId","empty","idpInitiated","code","externalToken","token","abTestingKey","predicate","condition","checkFunc","_a","key","operator","conditionResult","met","unmet","startScreenId","screenId","startScreenName","screenName","conditionInteractionId","interactionId","conditions","find","clientScripts","componentsConfig"],"mappings":"aAEA,MAEMA,EAA+B,CACnC,mBAAoB,CAClB,YAAcC,KAAUA,EAAIC,QAC5BC,MAAQF,IAASA,EAAIC,SAEvBE,aAAc,CACZ,UAAYH,KAAUA,EAAII,KAC1B,WAAaJ,IAASA,EAAII,MAE5BC,cAAe,CACb,UAAYL,KAAUA,EAAIM,MAC1B,WAAaN,IAASA,EAAIM,OAE5BC,aAAc,CACZ,eAAgB,CAACP,EAAKQ,KACnBR,EAAIO,cAAgB,GAAKC,EAC5B,YAAa,CAACR,EAAKQ,KAChBR,EAAIO,cAAgB,GAAKC,+BAIE,CAChCC,EACAT,WAEA,MAAMU,EAAyC,QAA7BC,EAAAZ,EAAcU,aAAS,EAATA,EAAWG,YAAI,IAAAD,OAAA,EAAAA,EAAGF,EAAUI,UAC5D,IAAKH,EACH,MAAO,GAET,MAAMI,EAAkBJ,EAAUV,EAAKS,EAAUD,WAC7CC,EAAUM,IACVN,EAAUO,MACd,MAAO,CACLC,cAAeH,aAAA,EAAAA,EAAiBI,SAChCC,gBAAiBL,aAAA,EAAAA,EAAiBM,WAClCC,uBAAwBP,aAAA,EAAAA,EAAiBQ,cAC1C,8BAIgC,CACjCtB,EACAuB,KAEA,MAAMT,EAAkBS,aAAU,EAAVA,EAAYC,MAAK,EAAGZ,MAAKC,WAAUL,sBACzD,GA/CsB,SA+ClBI,EACF,OAAO,EAET,MAAMF,EAA8B,QAAlBC,EAAAZ,EAAca,UAAI,IAAAD,OAAA,EAAAA,EAAGE,GACvC,SAASH,aAAS,EAATA,EAAYV,EAAKQ,GAAU,IAEtC,OAAQM,EAEJ,CACEG,cAAeH,EAAgBC,IAAIG,SACnCC,gBAAiBL,EAAgBC,IAAIK,WACrCC,uBAAwBP,EAAgBC,IAAIO,cAC5CG,cAAeX,EAAgBC,IAAIU,cACnCC,iBAAkBZ,EAAgBC,IAAIW,kBANxC,CAAE,CAOD"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var e=require("@descope/escape-markdown"),
|
|
1
|
+
"use strict";var e=require("tslib"),t=require("@descope/escape-markdown"),r=require("../constants/index.js"),o=require("./helpers.js");const s=["disabled"],n=(e,t)=>{Object.entries(t||{}).forEach((([t,o])=>{Array.from(e.querySelectorAll(`*[name="${t}"]:not([${r.DESCOPE_ATTRIBUTE_EXCLUDE_FIELD}])`)).forEach((e=>{e.value=o}))}))},l=(e,t)=>t.split(".").reduce(((e,t)=>(null==e?void 0:e[t])||""),e),c=(e,r,o)=>e.replace(/{{(.+?)}}/g,((e,s)=>o?t.escapeMarkdown(l(r,s)):l(r,s))),i=(e,t,o)=>{e.querySelectorAll(`[${r.ELEMENT_TYPE_ATTRIBUTE}="${t}"]`).forEach((e=>{e.setAttribute("href",o)}))},a=(e,t,r)=>{var o,s;const n=null===(o=customElements.get(t))||void 0===o?void 0:o.cssVarList.url;r&&n&&(null===(s=null==e?void 0:e.style)||void 0===s||s.setProperty(n,`url(data:image/jpg;base64,${r})`))};exports.disableWebauthnButtons=e=>{e.querySelectorAll(`descope-button[${r.ELEMENT_TYPE_ATTRIBUTE}="biometrics"]`).forEach((e=>e.setAttribute("disabled","true")))},exports.setCssVars=(e,t,r,o)=>{r&&Object.keys(r).forEach((s=>{t.querySelector(s)||o.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(r[s]).forEach((t=>{var l;const c=r[s],i=null===(l=null==n?void 0:n.cssVarList)||void 0===l?void 0:l[t];if(!i)return void o.info(`Could not find css variable name for ${t} in ${s}`,"Check if the css variable is defined in the component");const a=c[t];e.style.setProperty(i,a)})):o.info(`Could not find component class for ${s}`,"Check if the component is registered")}))},exports.setNOTPVariable=(e,t)=>{a(e,"descope-notp-image",t)},exports.setPhoneAutoDetectDefaultCode=(e,t)=>{Array.from(e.querySelectorAll('[default-code="autoDetect"]')).forEach((e=>{e.setAttribute("default-code",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,l,a,u,d)=>{var f,p;let E=null==n?void 0:n.errorText;try{E=(null==u?void 0:u({text:null==n?void 0:n.errorText,type:null==n?void 0:n.errorType}))||(null==n?void 0:n.errorText)}catch(e){d.error("Error transforming error message",e.message)}((e,t,o="")=>{e.querySelectorAll(`[${r.ELEMENT_TYPE_ATTRIBUTE}="${t}"]`).forEach((e=>{e.textContent=o,e.classList[o?"remove":"add"]("hide")}))})(t,"error-message",E),i(t,"totp-link",null===(f=null==n?void 0:n.totp)||void 0===f?void 0:f.provisionUrl),i(t,"notp-link",null===(p=null==n?void 0:n.notp)||void 0===p?void 0:p.redirectUrl),((e,t)=>{e.querySelectorAll("descope-text,descope-link,descope-enriched-text,descope-code-snippet").forEach((e=>{const r=o.shouldHandleMarkdown(e.localName);e.textContent=c(e.textContent,t,r);const s=e.getAttribute("href");s&&e.setAttribute("href",c(s,t))}))})(t,n),((t,r,o)=>{if(!r)return;const{componentsDynamicAttrs:s}=r,n=e.__rest(r,["componentsDynamicAttrs"]),l=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:r}=t;r&&Object.keys(r).length&&(l[e]=r)}})),Object.keys(l).forEach((e=>{t.querySelectorAll(e).forEach((t=>{const r=l[e];Object.keys(r).forEach((e=>{let s=r[e];if("string"!=typeof s)try{s=JSON.stringify(s)}catch(t){o.error(`Could not stringify value "${s}" for "${e}"`,t.message),s=""}t.setAttribute(e,s)}))}))}))})(t,l,d),((e,t)=>{e.querySelectorAll(`[${r.HAS_DYNAMIC_VALUES_ATTR_NAME}]`).forEach((e=>{Array.from(e.attributes).forEach((e=>{e.value=c(e.value,t)}))}))})(t,n),((e,t)=>{Object.entries(t).forEach((([t,r])=>{e.querySelectorAll(`[name="${t}"]`).forEach((e=>{Object.entries(r).forEach((([t,r])=>{s.includes(t)&&e.setAttribute(t,r)}))}))}))})(t,a)};
|
|
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\nconst replaceElementMessage = (\n baseEle: DocumentFragment,\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 const componentClass:\n | (CustomElementConstructor & { cssVarList: CssVars })\n | undefined = customElements.get(componentName) as any;\n\n if (!componentClass) {\n logger.info(\n `Could not find component class for ${componentName}`,\n 'Check if the component is registered',\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 // collect components that needs configuration from DOM\n Object.keys(componentsConfig).forEach((componentName) => {\n baseEle.querySelectorAll(`[name=${componentName}]`).forEach((comp) => {\n const config = componentsConfig[componentName];\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 */\nexport const updateTemplateFromScreenState = (\n baseEle: DocumentFragment,\n screenState?: ScreenState,\n componentsConfig?: ComponentsConfig,\n flowInputs?: Record<string, string>,\n errorTransformer?: (error: { text: string; type: string }) => string,\n logger?: { error: (message: string, description: string) => void },\n) => {\n let errorText = screenState?.errorText;\n try {\n errorText =\n errorTransformer?.({\n text: screenState?.errorText,\n type: screenState?.errorType,\n }) || screenState?.errorText;\n } catch (e) {\n logger.error('Error transforming error message', e.message);\n }\n replaceElementMessage(baseEle, 'error-message', errorText);\n replaceHrefByDataType(baseEle, 'totp-link', screenState?.totp?.provisionUrl);\n replaceHrefByDataType(baseEle, 'notp-link', screenState?.notp?.redirectUrl);\n replaceElementTemplates(baseEle, screenState);\n setElementConfig(baseEle, 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 setPhoneAutoDetectDefaultCode = (\n fragment: DocumentFragment,\n autoDetectCode?: string,\n) => {\n Array.from(fragment.querySelectorAll('[default-code=\"autoDetect\"]')).forEach(\n (phoneEle) => {\n phoneEle.setAttribute('default-code', autoDetectCode);\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","nextPageTemplate","cssVars","logger","keys","componentName","querySelector","debug","componentClass","cssVarKey","componentCssVars","varName","info","autoDetectCode","phoneEle","inputs","form","componentsConfig","flowInputs","errorTransformer","errorText","type","errorType","e","error","message","eleType","textContent","classList","replaceElementMessage","totp","notp","redirectUrl","inEle","shouldHandleMarkdown","localName","href","getAttribute","replaceElementTemplates","comp","config","attr","JSON","stringify","setElementConfig","HAS_DYNAMIC_VALUES_ATTR_NAME","attributes","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\nconst replaceElementMessage = (\n baseEle: DocumentFragment,\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 const componentClass:\n | (CustomElementConstructor & { cssVarList: CssVars })\n | undefined = customElements.get(componentName) as any;\n\n if (!componentClass) {\n logger.info(\n `Could not find component class for ${componentName}`,\n 'Check if the component is registered',\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 */\nexport const updateTemplateFromScreenState = (\n baseEle: DocumentFragment,\n screenState?: ScreenState,\n componentsConfig?: ComponentsConfig,\n flowInputs?: Record<string, string>,\n errorTransformer?: (error: { text: string; type: string }) => string,\n logger?: { error: (message: string, description: string) => void },\n) => {\n let errorText = screenState?.errorText;\n try {\n errorText =\n errorTransformer?.({\n text: screenState?.errorText,\n type: screenState?.errorType,\n }) || screenState?.errorText;\n } catch (e) {\n logger.error('Error transforming error message', e.message);\n }\n replaceElementMessage(baseEle, 'error-message', errorText);\n replaceHrefByDataType(baseEle, 'totp-link', screenState?.totp?.provisionUrl);\n replaceHrefByDataType(baseEle, 'notp-link', screenState?.notp?.redirectUrl);\n replaceElementTemplates(baseEle, screenState);\n setElementConfig(baseEle, 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 setPhoneAutoDetectDefaultCode = (\n fragment: DocumentFragment,\n autoDetectCode?: string,\n) => {\n Array.from(fragment.querySelectorAll('[default-code=\"autoDetect\"]')).forEach(\n (phoneEle) => {\n phoneEle.setAttribute('default-code', autoDetectCode);\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","nextPageTemplate","cssVars","logger","keys","componentName","querySelector","debug","componentClass","cssVarKey","componentCssVars","varName","info","autoDetectCode","phoneEle","inputs","form","componentsConfig","flowInputs","errorTransformer","errorText","type","errorType","e","error","message","eleType","textContent","classList","replaceElementMessage","totp","notp","redirectUrl","inEle","shouldHandleMarkdown","localName","href","getAttribute","replaceElementTemplates","componentsDynamicAttrs","rest","__rest","configMap","acc","componentSelector","componentDynamicAttrs","attributes","length","componentsSelector","comp","config","attr","JSON","stringify","setElementConfig","HAS_DYNAMIC_VALUES_ATTR_NAME","replaceTemplateDynamicAttrValues","formData","attrName","attrValue","includes","setFormConfigValues"],"mappings":"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"}
|
package/dist/cjs/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sources":["../../src/lib/types.ts"],"sourcesContent":["/* istanbul ignore file */\n\nimport createSdk from '@descope/web-js-sdk';\n\nexport type SdkConfig = Parameters<typeof createSdk>[0];\nexport type Sdk = ReturnType<typeof createSdk>;\n\nexport type SdkFlowNext = Sdk['flow']['next'];\n\nexport type ComponentsConfig = Record<string, any>;\nexport type CssVars = Record<string, any>;\n\ntype KeepArgsByIndex<F, Indices extends readonly number[]> = F extends (\n ...args: infer A\n) => infer R\n ? (...args: PickArgsByIndex<A, Indices>) => R\n : never;\n\ntype PickArgsByIndex<\n All extends readonly any[],\n Indices extends readonly number[],\n> = {\n [K in keyof Indices]: Indices[K] extends keyof All ? All[Indices[K]] : never;\n};\n\ntype Project = {\n name: string;\n};\n\nexport enum Direction {\n backward = 'backward',\n forward = 'forward',\n}\n\nexport interface LastAuthState {\n loginId?: string;\n name?: string;\n}\n\nexport interface ScreenState {\n errorText?: string;\n errorType?: string;\n componentsConfig?: ComponentsConfig;\n cssVars?: CssVars;\n form?: Record<string, string>;\n inputs?: Record<string, string>; // Backward compatibility\n lastAuth?: LastAuthState;\n project?: Project;\n totp?: { image?: string; provisionUrl?: string };\n notp?: { image?: string; redirectUrl?: string };\n selfProvisionDomains?: unknown;\n user?: unknown;\n sso?: unknown;\n dynamicSelects?: unknown;\n keysInUse?: unknown;\n genericForm?: unknown;\n linkId?: unknown;\n sentTo?: unknown;\n clientScripts?: ClientScript[];\n}\n\nexport type SSOQueryParams = {\n oidcIdpStateId?: string;\n samlIdpStateId?: string;\n samlIdpUsername?: string;\n descopeIdpInitiated?: boolean;\n ssoAppId?: string;\n thirdPartyAppId: string;\n thirdPartyAppStateId?: string;\n applicationScopes?: string;\n} & OIDCOptions;\n\nexport type OIDCOptions = {\n oidcLoginHint?: string;\n oidcPrompt?: string;\n oidcErrorRedirectUri?: string;\n};\n\nexport type Locale = {\n locale: string;\n fallback: string;\n};\n\nexport type FlowState = {\n flowId: string;\n projectId: string;\n baseUrl: string;\n tenant: string;\n stepId: string;\n stepName: string;\n executionId: string;\n action: string;\n redirectTo: string;\n openInNewTabUrl?: string;\n redirectUrl: string;\n screenId: string;\n screenState: ScreenState;\n token: string;\n code: string;\n exchangeError: string;\n webauthnTransactionId: string;\n webauthnOptions: string;\n redirectAuthCodeChallenge: string;\n redirectAuthCallbackUrl: string;\n redirectAuthBackupCallbackUri: string;\n redirectAuthInitiator: string;\n deferredRedirect: boolean;\n locale: string;\n samlIdpResponseUrl: string;\n samlIdpResponseSamlResponse: string;\n samlIdpResponseRelayState: string;\n nativeResponseType: string;\n nativePayload: Record<string, any>;\n reqTimestamp: number;\n} & SSOQueryParams;\n\nexport type StepState = {\n screenState: ScreenState;\n screenId: string;\n stepName: string;\n htmlFilename: string;\n htmlLocaleFilename: string;\n next: NextFn;\n direction: Direction | undefined;\n samlIdpUsername: string;\n openInNewTabUrl?: string;\n} & OIDCOptions;\n\nexport type CustomScreenState = Omit<\n ScreenState,\n 'cssVars' | 'componentsConfig' | 'inputs'\n> & {\n error?: {\n text: ScreenState['errorText'];\n type: ScreenState['errorType'];\n };\n};\n\nexport type DebugState = {\n isDebug: boolean;\n};\n\nexport interface ScriptElement extends HTMLDivElement {\n moduleRes?: ScriptModule;\n}\n\nexport type ScriptModule = {\n stop: () => void;\n start: () => void;\n};\n\nexport type ClientScript = {\n id: string;\n initArgs: Record<string, any>;\n resultKey?: string;\n};\n\nexport type NextFn = KeepArgsByIndex<SdkFlowNext, [2, 5]>;\nexport type NextFnReturnPromiseValue = Awaited<ReturnType<NextFn>>;\n\nexport type DebuggerMessage = {\n title: string;\n description?: string;\n};\n\nexport type FlowStateUpdateFn = (state: FlowState) => void;\n\ntype Operator =\n | 'equal'\n | 'not-equal'\n | 'contains'\n | 'greater-than'\n | 'less-than'\n | 'empty'\n | 'not-empty'\n | 'is-true'\n | 'is-false'\n | 'in'\n | 'not-in';\n\nexport interface ClientConditionResult {\n screenId: string;\n screenName: string;\n clientScripts?: ClientScript[];\n interactionId: string;\n}\n\nexport interface ClientCondition {\n operator: Operator;\n key: string;\n predicate?: string | number;\n met: ClientConditionResult;\n unmet?: ClientConditionResult;\n}\n\nexport type AutoFocusOptions = true | false | 'skipFirstScreen';\n\nexport type ThemeOptions = 'light' | 'dark' | 'os';\n\nexport type Key =\n | 'lastAuth.loginId'\n | 'idpInitiated'\n | 'externalToken'\n | 'abTestingKey';\n\ntype CheckFunction = (ctx: Context, predicate?: string | number) => boolean;\n\nexport type ConditionsMap = {\n [key in Key]: {\n [operator in Operator]?: CheckFunction;\n };\n};\n\nexport interface Context {\n loginId?: string;\n code?: string;\n token?: string;\n abTestingKey?: number;\n}\n\nexport type DescopeUI = Record<string, () => Promise<void>> & {\n componentsThemeManager: Record<string, any>;\n};\n\ntype Font = {\n family: string[];\n label: string;\n url?: string;\n};\n\ntype ThemeTemplate = {\n fonts: {\n font1: Font;\n font2: Font;\n };\n};\n\nexport type FlowConfig = {\n startScreenId?: string;\n startScreenName?: string;\n version: number;\n targetLocales?: string[];\n conditions?: ClientCondition[];\n condition?: ClientCondition;\n fingerprintEnabled?: boolean;\n fingerprintKey?: string;\n sdkScripts?: [\n {\n id: string;\n initArgs: Record<string, any>;\n resultKey?: string;\n },\n ];\n clientScripts?: ClientScript[];\n};\n\nexport interface ProjectConfiguration {\n componentsVersion: string;\n cssTemplate: {\n dark: ThemeTemplate;\n light: ThemeTemplate;\n };\n flows: {\n [key: string]: FlowConfig; // dynamic key names for flows\n };\n}\n\nexport type FlowStatus = 'loading' | 'error' | 'success' | 'ready' | 'initial';\n"],"names":["Direction"],"mappings":"
|
|
1
|
+
{"version":3,"file":"types.js","sources":["../../src/lib/types.ts"],"sourcesContent":["/* istanbul ignore file */\n\nimport createSdk from '@descope/web-js-sdk';\n\nexport type SdkConfig = Parameters<typeof createSdk>[0];\nexport type Sdk = ReturnType<typeof createSdk>;\n\nexport type SdkFlowNext = Sdk['flow']['next'];\n\nexport type ComponentsDynamicAttrs = {\n attributes: Record<string, any>;\n};\n\nexport type ComponentsConfig = Record<string, any> & {\n componentsDynamicAttrs?: Record<string, ComponentsDynamicAttrs>;\n};\nexport type CssVars = Record<string, any>;\n\ntype KeepArgsByIndex<F, Indices extends readonly number[]> = F extends (\n ...args: infer A\n) => infer R\n ? (...args: PickArgsByIndex<A, Indices>) => R\n : never;\n\ntype PickArgsByIndex<\n All extends readonly any[],\n Indices extends readonly number[],\n> = {\n [K in keyof Indices]: Indices[K] extends keyof All ? All[Indices[K]] : never;\n};\n\ntype Project = {\n name: string;\n};\n\nexport enum Direction {\n backward = 'backward',\n forward = 'forward',\n}\n\nexport interface LastAuthState {\n loginId?: string;\n name?: string;\n}\n\nexport interface ScreenState {\n errorText?: string;\n errorType?: string;\n componentsConfig?: ComponentsConfig;\n cssVars?: CssVars;\n form?: Record<string, string>;\n inputs?: Record<string, string>; // Backward compatibility\n lastAuth?: LastAuthState;\n project?: Project;\n totp?: { image?: string; provisionUrl?: string };\n notp?: { image?: string; redirectUrl?: string };\n selfProvisionDomains?: unknown;\n user?: unknown;\n sso?: unknown;\n dynamicSelects?: unknown;\n keysInUse?: unknown;\n genericForm?: unknown;\n linkId?: unknown;\n sentTo?: unknown;\n clientScripts?: ClientScript[];\n}\n\nexport type SSOQueryParams = {\n oidcIdpStateId?: string;\n samlIdpStateId?: string;\n samlIdpUsername?: string;\n descopeIdpInitiated?: boolean;\n ssoAppId?: string;\n thirdPartyAppId: string;\n thirdPartyAppStateId?: string;\n applicationScopes?: string;\n} & OIDCOptions;\n\nexport type OIDCOptions = {\n oidcLoginHint?: string;\n oidcPrompt?: string;\n oidcErrorRedirectUri?: string;\n};\n\nexport type Locale = {\n locale: string;\n fallback: string;\n};\n\nexport type FlowState = {\n flowId: string;\n projectId: string;\n baseUrl: string;\n tenant: string;\n stepId: string;\n stepName: string;\n executionId: string;\n action: string;\n redirectTo: string;\n openInNewTabUrl?: string;\n redirectUrl: string;\n screenId: string;\n screenState: ScreenState;\n token: string;\n code: string;\n exchangeError: string;\n webauthnTransactionId: string;\n webauthnOptions: string;\n redirectAuthCodeChallenge: string;\n redirectAuthCallbackUrl: string;\n redirectAuthBackupCallbackUri: string;\n redirectAuthInitiator: string;\n deferredRedirect: boolean;\n locale: string;\n samlIdpResponseUrl: string;\n samlIdpResponseSamlResponse: string;\n samlIdpResponseRelayState: string;\n nativeResponseType: string;\n nativePayload: Record<string, any>;\n reqTimestamp: number;\n} & SSOQueryParams;\n\nexport type StepState = {\n screenState: ScreenState;\n screenId: string;\n stepName: string;\n htmlFilename: string;\n htmlLocaleFilename: string;\n next: NextFn;\n direction: Direction | undefined;\n samlIdpUsername: string;\n openInNewTabUrl?: string;\n} & OIDCOptions;\n\nexport type CustomScreenState = Omit<\n ScreenState,\n 'cssVars' | 'componentsConfig' | 'inputs'\n> & {\n error?: {\n text: ScreenState['errorText'];\n type: ScreenState['errorType'];\n };\n};\n\nexport type DebugState = {\n isDebug: boolean;\n};\n\nexport interface ScriptElement extends HTMLDivElement {\n moduleRes?: ScriptModule;\n}\n\nexport type ScriptModule = {\n stop: () => void;\n start: () => void;\n};\n\nexport type ClientScript = {\n id: string;\n initArgs: Record<string, any>;\n resultKey?: string;\n};\n\nexport type NextFn = KeepArgsByIndex<SdkFlowNext, [2, 5]>;\nexport type NextFnReturnPromiseValue = Awaited<ReturnType<NextFn>>;\n\nexport type DebuggerMessage = {\n title: string;\n description?: string;\n};\n\nexport type FlowStateUpdateFn = (state: FlowState) => void;\n\ntype Operator =\n | 'equal'\n | 'not-equal'\n | 'contains'\n | 'greater-than'\n | 'less-than'\n | 'empty'\n | 'not-empty'\n | 'is-true'\n | 'is-false'\n | 'in'\n | 'not-in';\n\nexport interface ClientConditionResult {\n screenId: string;\n screenName: string;\n clientScripts?: ClientScript[];\n componentsConfig?: ComponentsConfig;\n interactionId: string;\n}\n\nexport interface ClientCondition {\n operator: Operator;\n key: string;\n predicate?: string | number;\n met: ClientConditionResult;\n unmet?: ClientConditionResult;\n}\n\nexport type AutoFocusOptions = true | false | 'skipFirstScreen';\n\nexport type ThemeOptions = 'light' | 'dark' | 'os';\n\nexport type Key =\n | 'lastAuth.loginId'\n | 'idpInitiated'\n | 'externalToken'\n | 'abTestingKey';\n\ntype CheckFunction = (ctx: Context, predicate?: string | number) => boolean;\n\nexport type ConditionsMap = {\n [key in Key]: {\n [operator in Operator]?: CheckFunction;\n };\n};\n\nexport interface Context {\n loginId?: string;\n code?: string;\n token?: string;\n abTestingKey?: number;\n}\n\nexport type DescopeUI = Record<string, () => Promise<void>> & {\n componentsThemeManager: Record<string, any>;\n};\n\ntype Font = {\n family: string[];\n label: string;\n url?: string;\n};\n\ntype ThemeTemplate = {\n fonts: {\n font1: Font;\n font2: Font;\n };\n};\n\nexport type FlowConfig = {\n startScreenId?: string;\n startScreenName?: string;\n version: number;\n targetLocales?: string[];\n conditions?: ClientCondition[];\n condition?: ClientCondition;\n fingerprintEnabled?: boolean;\n fingerprintKey?: string;\n sdkScripts?: [\n {\n id: string;\n initArgs: Record<string, any>;\n resultKey?: string;\n },\n ];\n clientScripts?: ClientScript[];\n componentsConfig?: ComponentsConfig;\n};\n\nexport interface ProjectConfiguration {\n componentsVersion: string;\n cssTemplate: {\n dark: ThemeTemplate;\n light: ThemeTemplate;\n };\n flows: {\n [key: string]: FlowConfig; // dynamic key names for flows\n };\n}\n\nexport type FlowStatus = 'loading' | 'error' | 'success' | 'ready' | 'initial';\n"],"names":["Direction"],"mappings":"aAmCA,IAAYA,EAAAA,QAGXA,eAAA,GAHWA,EAAAA,QAASA,YAATA,kBAGX,CAAA,IAFC,SAAA,WACAA,EAAA,QAAA"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{__classPrivateFieldGet as t,__awaiter as e,__classPrivateFieldSet as i}from"tslib";import{compose as r}from"@descope/sdk-helpers";import{staticResourcesMixin as s}from"@descope/sdk-mixins/static-resources-mixin";import{themeMixin as o}from"@descope/sdk-mixins/theme-mixin";import n from"@descope/web-js-sdk";import{ELEMENTS_TO_IGNORE_ENTER_KEY_ON as a}from"../constants/index.js";import{handleUrlParams as u,clearRunIdsFromUrl as l,camelCase as d,getRunIdsFromUrl as c,getContentUrl as h,fetchContent as f}from"../helpers/helpers.js";import g from"../helpers/state.js";import"@descope/escape-markdown";import"../helpers/webauthn.js";import{transformFlowInputFormData as p,extractNestedAttribute as m}from"../helpers/flowInputs.js";import{formMountMixin as v}from"../mixins/formMountMixin.js";import b from"./initTemplate.js";import{CONFIG_FILENAME as w,PREV_VER_ASSETS_FOLDER as C}from"../constants/content.js";import{FETCH_EXCEPTION_ERROR_CODE as k}from"../constants/general.js";var A,x,y,j,I,E,L,U,M,O,S,W,D,N,P,R,F,T,B,V,q;const H=r(o,s,v)(HTMLElement);class K extends H{static get observedAttributes(){return["project-id","flow-id","base-url","tenant","locale","debug","storage-prefix","preview","redirect-url","auto-focus","store-last-authenticated-user","refresh-cookie-name","keep-last-authenticated-user-after-logout","validate-on-blur","style-id"]}constructor(r){super(),A.add(this),y.set(this,!1),this.flowStatus="initial",this.loggerWrapper={error:(e,i="")=>{this.logger.error(e,i,new Error),t(this,A,"m",V).call(this,e,i)},warn:(t,e="")=>{this.logger.warn(t,e)},info:(t,e="",i={})=>{this.logger.info(t,e,i)},debug:(t,e="")=>{this.logger.debug(t,e)}},j.set(this,new g),I.set(this,new g),E.set(this,{}),this.getComponentsContext=()=>t(this,E,"f"),this.nextRequestStatus=new g({isLoading:!1}),L.set(this,void 0),U.set(this,{popstate:t(this,A,"m",W).bind(this),componentsContext:t(this,A,"m",F).bind(this)}),M.set(this,void 0),this.getConfig=()=>e(this,void 0,void 0,(function*(){return(yield this.config)||{isMissingConfig:!0}})),i(this,M,r,"f"),t(this,A,"m",O).call(this)}get flowId(){return this.getAttribute("flow-id")}get client(){try{return JSON.parse(this.getAttribute("client"))||{}}catch(t){return{}}}get tenantId(){return this.getAttribute("tenant")||void 0}get redirectUrl(){return this.getAttribute("redirect-url")||void 0}get debug(){return"true"===this.getAttribute("debug")}get locale(){return this.getAttribute("locale")||void 0}get autoFocus(){var t;const e=null!==(t=this.getAttribute("auto-focus"))&&void 0!==t?t:"true";return"skipFirstScreen"===e?e:"true"===e}get validateOnBlur(){return"true"===this.getAttribute("validate-on-blur")}get storeLastAuthenticatedUser(){var t;return"true"===(null!==(t=this.getAttribute("store-last-authenticated-user"))&&void 0!==t?t:"true")}get refreshCookieName(){return this.getAttribute("refresh-cookie-name")||""}get keepLastAuthenticatedUserAfterLogout(){return"true"===this.getAttribute("keep-last-authenticated-user-after-logout")}get storagePrefix(){return this.getAttribute("storage-prefix")||""}get preview(){return!!this.getAttribute("preview")}get formConfig(){return p(this.form)}get form(){return this.getAttribute("form")}get formConfigValues(){return m(this.formConfig,"value")}get isRestartOnError(){return"true"===this.getAttribute("restart-on-error")}getExecutionContext(){return e(this,void 0,void 0,(function*(){const t=yield this.getConfig();return"executionContext"in t?t.executionContext:void 0}))}getProjectConfig(){return e(this,void 0,void 0,(function*(){const t=yield this.getConfig();return"projectConfig"in t?t.projectConfig:void 0}))}getFlowConfig(){return e(this,void 0,void 0,(function*(){var t,e;const i=yield this.getProjectConfig(),r=(null===(t=null==i?void 0:i.flows)||void 0===t?void 0:t[this.flowId])||{};return null!==(e=r.version)&&void 0!==e||(r.version=0),r}))}getTargetLocales(){return e(this,void 0,void 0,(function*(){const t=yield this.getFlowConfig();return((null==t?void 0:t.targetLocales)||[]).map((t=>t.toLowerCase()))}))}getComponentsVersion(){return e(this,void 0,void 0,(function*(){var t;const e=yield this.getConfig(),i="projectConfig"in e?null===(t=e.projectConfig)||void 0===t?void 0:t.componentsVersion:{};return i||(this.logger.error("Did not get components version, using latest version"),"latest")}))}init(){const r=Object.create(null,{init:{get:()=>super.init}});return e(this,void 0,void 0,(function*(){var e;if(this.flowStatus="loading",["ready","error","success"].forEach((t=>this.addEventListener(t,(()=>{this.flowStatus=t})))),yield null===(e=r.init)||void 0===e?void 0:e.call(this),t(this,I,"f").subscribe(t(this,A,"m",B).bind(this)),t(this,I,"f").update({isDebug:this.debug}),t(this,A,"m",S).call(this),yield t(this,A,"m",P).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 s=yield this.getConfig();if("isMissingConfig"in s&&s.isMissingConfig)return void this.loggerWrapper.error("Cannot get config file","Make sure that your projectId & flowId are correct");t(this,A,"m",q).call(this);const{executionId:o,stepId:n,token:a,code:l,exchangeError:d,redirectAuthCallbackUrl:c,redirectAuthBackupCallbackUri:h,redirectAuthCodeChallenge:f,redirectAuthInitiator:g,ssoQueryParams:p}=u(this.flowId,this.loggerWrapper);window.addEventListener("popstate",t(this,U,"f").popstate),window.addEventListener("components-context",t(this,U,"f").componentsContext),t(this,j,"f").subscribe(t(this,A,"m",N).bind(this)),t(this,j,"f").update(Object.assign({projectId:this.projectId,flowId:this.flowId,baseUrl:this.baseUrl,tenant:this.tenantId,redirectUrl:this.redirectUrl,locale:this.locale,stepId:n,executionId:o,token:a,code:l,exchangeError:d,redirectAuthCallbackUrl:c,redirectAuthBackupCallbackUri:h,redirectAuthCodeChallenge:f,redirectAuthInitiator:g},p)),i(this,y,!0,"f")}))}disconnectedCallback(){t(this,j,"f").unsubscribeAll(),t(this,I,"f").unsubscribeAll(),t(this,A,"m",T).call(this),window.removeEventListener("popstate",t(this,U,"f").popstate),window.removeEventListener("components-context",t(this,U,"f").componentsContext)}attributeChangedCallback(e,i,r){if(this.shadowRoot.isConnected&&t(this,y,"f")&&i!==r&&x.observedAttributes.includes(e)){t(this,A,"m",S).call(this);const s=null===i;t(this,j,"f").update((({stepId:t,executionId:i})=>{let o=t,n=i;return s||(n=null,o=null,l()),{[d(e)]:r,stepId:o,executionId:n}})),t(this,I,"f").update({isDebug:this.debug})}}}x=K,y=new WeakMap,j=new WeakMap,I=new WeakMap,E=new WeakMap,L=new WeakMap,U=new WeakMap,M=new WeakMap,A=new WeakSet,O=function(){this.shadowRoot.appendChild(b.content.cloneNode(!0)),this.slotElement=document.createElement("slot"),this.slotElement.classList.add("hidden"),this.rootElement.appendChild(this.slotElement)},S=function(){const t=["base-url","tenant","locale","debug","redirect-url","auto-focus","store-last-authenticated-user","refresh-cookie-name","keep-last-authenticated-user-after-logout","preview","storage-prefix","form","client","validate-on-blur","style-id"];x.observedAttributes.forEach((e=>{if(!t.includes(e)&&!this[d(e)])throw Error(`${e} cannot be empty`)}))},W=function(){const{stepId:e,executionId:i}=c(this.flowId);t(this,j,"f").update({stepId:e,executionId:i})},D=function(t,i){this.sdk=n(Object.assign(Object.assign({persistTokens:!0,preview:this.preview,storagePrefix:this.storagePrefix,storeLastAuthenticatedUser:this.storeLastAuthenticatedUser,keepLastAuthenticatedUserAfterLogout:this.keepLastAuthenticatedUserAfterLogout,refreshCookieName:this.refreshCookieName},x.sdkConfigOverrides),{projectId:t,baseUrl:i})),["start","next"].forEach((t=>{const i=this.sdk.flow[t];this.sdk.flow[t]=(...t)=>e(this,void 0,void 0,(function*(){try{return yield i(...t)}catch(t){return{error:{errorCode:k,errorDescription:t.toString()}}}}))}))},N=function(i,r,s){return e(this,void 0,void 0,(function*(){const{projectId:e,baseUrl:r}=i;if(s("projectId")||s("baseUrl")){if(!e)return;t(this,A,"m",D).call(this,e,r)}t(this,M,"f").call(this,i)}))},P=function(){return e(this,void 0,void 0,(function*(){const e=yield this.getConfig();return"isMissingConfig"in e&&e.isMissingConfig&&(yield t(this,A,"m",R).call(this))}))},R=function(){return e(this,void 0,void 0,(function*(){const t=h({projectId:this.projectId,filename:w,assetsFolder:C,baseUrl:this.baseStaticUrl});try{return yield f(t,"json"),!0}catch(t){return!1}}))},F=function(e){i(this,E,Object.assign(Object.assign({},t(this,E,"f")),e.detail),"f")},T=function(){var e;null===(e=t(this,L,"f"))||void 0===e||e.remove(),i(this,L,null,"f")},B=function(r){return e(this,arguments,void 0,(function*({isDebug:e}){e?(i(this,L,document.createElement("descope-debugger"),"f"),Object.assign(t(this,L,"f").style,{position:"fixed",top:"0",right:"0",height:"100vh",width:"100vw",pointerEvents:"none",zIndex:99999}),yield import("../debugger-wc.js"),document.body.appendChild(t(this,L,"f"))):t(this,A,"m",T).call(this)}))},V=function(e,i){var r;e&&this.debug&&(null===(r=t(this,L,"f"))||void 0===r||r.updateData({title:e,description:i}))},q=function(){this.rootElement.onkeydown=t=>{var e,i,r;const s=!!(null===(e=this.shadowRoot.activeElement)||void 0===e?void 0:e.getAttribute("href")),o=a.includes(null!==(r=null===(i=this.shadowRoot.activeElement)||void 0===i?void 0:i.localName)&&void 0!==r?r:"");if("Enter"!==t.key||s||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 u=Array.from(n).filter((t=>"true"===t.getAttribute("auto-submit")));if(1===u.length)return void u[0].click();const l=Array.from(n).filter((t=>"button"===t.getAttribute("data-type")));if(1===l.length)"false"!==l[0].getAttribute("auto-submit")&&l[0].click();else if(0===l.length){const t=Array.from(n).filter((t=>"sso"===t.getAttribute("data-type")));1===t.length&&"false"!==t[0].getAttribute("auto-submit")&&t[0].click()}}},K.sdkConfigOverrides={baseHeaders:{"x-descope-sdk-name":"web-component","x-descope-sdk-version":"3.36.1"}};export{K as default};
|
|
1
|
+
import{__classPrivateFieldGet as t,__awaiter as e,__classPrivateFieldSet as i}from"tslib";import{compose as r}from"@descope/sdk-helpers";import{staticResourcesMixin as s}from"@descope/sdk-mixins/static-resources-mixin";import{themeMixin as o}from"@descope/sdk-mixins/theme-mixin";import n from"@descope/web-js-sdk";import{ELEMENTS_TO_IGNORE_ENTER_KEY_ON as a}from"../constants/index.js";import{handleUrlParams as u,clearRunIdsFromUrl as l,camelCase as d,getRunIdsFromUrl as c,getContentUrl as h,fetchContent as f}from"../helpers/helpers.js";import g from"../helpers/state.js";import"@descope/escape-markdown";import"../helpers/webauthn.js";import{transformFlowInputFormData as p,extractNestedAttribute as m}from"../helpers/flowInputs.js";import{formMountMixin as v}from"../mixins/formMountMixin.js";import b from"./initTemplate.js";import{CONFIG_FILENAME as w,PREV_VER_ASSETS_FOLDER as C}from"../constants/content.js";import{FETCH_EXCEPTION_ERROR_CODE as k}from"../constants/general.js";var A,x,y,j,I,E,L,U,M,O,S,W,D,N,P,R,F,T,B,V,q;const H=r(o,s,v)(HTMLElement);class K extends H{static get observedAttributes(){return["project-id","flow-id","base-url","tenant","locale","debug","storage-prefix","preview","redirect-url","auto-focus","store-last-authenticated-user","refresh-cookie-name","keep-last-authenticated-user-after-logout","validate-on-blur","style-id"]}constructor(r){super(),A.add(this),y.set(this,!1),this.flowStatus="initial",this.loggerWrapper={error:(e,i="")=>{this.logger.error(e,i,new Error),t(this,A,"m",V).call(this,e,i)},warn:(t,e="")=>{this.logger.warn(t,e)},info:(t,e="",i={})=>{this.logger.info(t,e,i)},debug:(t,e="")=>{this.logger.debug(t,e)}},j.set(this,new g),I.set(this,new g),E.set(this,{}),this.getComponentsContext=()=>t(this,E,"f"),this.nextRequestStatus=new g({isLoading:!1}),L.set(this,void 0),U.set(this,{popstate:t(this,A,"m",W).bind(this),componentsContext:t(this,A,"m",F).bind(this)}),M.set(this,void 0),this.getConfig=()=>e(this,void 0,void 0,(function*(){return(yield this.config)||{isMissingConfig:!0}})),i(this,M,r,"f"),t(this,A,"m",O).call(this)}get flowId(){return this.getAttribute("flow-id")}get client(){try{return JSON.parse(this.getAttribute("client"))||{}}catch(t){return{}}}get tenantId(){return this.getAttribute("tenant")||void 0}get redirectUrl(){return this.getAttribute("redirect-url")||void 0}get debug(){return"true"===this.getAttribute("debug")}get locale(){return this.getAttribute("locale")||void 0}get autoFocus(){var t;const e=null!==(t=this.getAttribute("auto-focus"))&&void 0!==t?t:"true";return"skipFirstScreen"===e?e:"true"===e}get validateOnBlur(){return"true"===this.getAttribute("validate-on-blur")}get storeLastAuthenticatedUser(){var t;return"true"===(null!==(t=this.getAttribute("store-last-authenticated-user"))&&void 0!==t?t:"true")}get refreshCookieName(){return this.getAttribute("refresh-cookie-name")||""}get keepLastAuthenticatedUserAfterLogout(){return"true"===this.getAttribute("keep-last-authenticated-user-after-logout")}get storagePrefix(){return this.getAttribute("storage-prefix")||""}get preview(){return!!this.getAttribute("preview")}get formConfig(){return p(this.form)}get form(){return this.getAttribute("form")}get formConfigValues(){return m(this.formConfig,"value")}get isRestartOnError(){return"true"===this.getAttribute("restart-on-error")}getExecutionContext(){return e(this,void 0,void 0,(function*(){const t=yield this.getConfig();return"executionContext"in t?t.executionContext:void 0}))}getProjectConfig(){return e(this,void 0,void 0,(function*(){const t=yield this.getConfig();return"projectConfig"in t?t.projectConfig:void 0}))}getFlowConfig(){return e(this,void 0,void 0,(function*(){var t,e;const i=yield this.getProjectConfig(),r=(null===(t=null==i?void 0:i.flows)||void 0===t?void 0:t[this.flowId])||{};return null!==(e=r.version)&&void 0!==e||(r.version=0),r}))}getTargetLocales(){return e(this,void 0,void 0,(function*(){const t=yield this.getFlowConfig();return((null==t?void 0:t.targetLocales)||[]).map((t=>t.toLowerCase()))}))}getComponentsVersion(){return e(this,void 0,void 0,(function*(){var t;const e=yield this.getConfig(),i="projectConfig"in e?null===(t=e.projectConfig)||void 0===t?void 0:t.componentsVersion:{};return i||(this.logger.error("Did not get components version, using latest version"),"latest")}))}init(){const r=Object.create(null,{init:{get:()=>super.init}});return e(this,void 0,void 0,(function*(){var e;if(this.flowStatus="loading",["ready","error","success"].forEach((t=>this.addEventListener(t,(()=>{this.flowStatus=t})))),yield null===(e=r.init)||void 0===e?void 0:e.call(this),t(this,I,"f").subscribe(t(this,A,"m",B).bind(this)),t(this,I,"f").update({isDebug:this.debug}),t(this,A,"m",S).call(this),yield t(this,A,"m",P).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 s=yield this.getConfig();if("isMissingConfig"in s&&s.isMissingConfig)return void this.loggerWrapper.error("Cannot get config file","Make sure that your projectId & flowId are correct");t(this,A,"m",q).call(this);const{executionId:o,stepId:n,token:a,code:l,exchangeError:d,redirectAuthCallbackUrl:c,redirectAuthBackupCallbackUri:h,redirectAuthCodeChallenge:f,redirectAuthInitiator:g,ssoQueryParams:p}=u(this.flowId,this.loggerWrapper);window.addEventListener("popstate",t(this,U,"f").popstate),window.addEventListener("components-context",t(this,U,"f").componentsContext),t(this,j,"f").subscribe(t(this,A,"m",N).bind(this)),t(this,j,"f").update(Object.assign({projectId:this.projectId,flowId:this.flowId,baseUrl:this.baseUrl,tenant:this.tenantId,redirectUrl:this.redirectUrl,locale:this.locale,stepId:n,executionId:o,token:a,code:l,exchangeError:d,redirectAuthCallbackUrl:c,redirectAuthBackupCallbackUri:h,redirectAuthCodeChallenge:f,redirectAuthInitiator:g},p)),i(this,y,!0,"f")}))}disconnectedCallback(){t(this,j,"f").unsubscribeAll(),t(this,I,"f").unsubscribeAll(),t(this,A,"m",T).call(this),window.removeEventListener("popstate",t(this,U,"f").popstate),window.removeEventListener("components-context",t(this,U,"f").componentsContext)}attributeChangedCallback(e,i,r){if(this.shadowRoot.isConnected&&t(this,y,"f")&&i!==r&&x.observedAttributes.includes(e)){t(this,A,"m",S).call(this);const s=null===i;t(this,j,"f").update((({stepId:t,executionId:i})=>{let o=t,n=i;return s||(n=null,o=null,l()),{[d(e)]:r,stepId:o,executionId:n}})),t(this,I,"f").update({isDebug:this.debug})}}}x=K,y=new WeakMap,j=new WeakMap,I=new WeakMap,E=new WeakMap,L=new WeakMap,U=new WeakMap,M=new WeakMap,A=new WeakSet,O=function(){this.shadowRoot.appendChild(b.content.cloneNode(!0)),this.slotElement=document.createElement("slot"),this.slotElement.classList.add("hidden"),this.rootElement.appendChild(this.slotElement)},S=function(){const t=["base-url","tenant","locale","debug","redirect-url","auto-focus","store-last-authenticated-user","refresh-cookie-name","keep-last-authenticated-user-after-logout","preview","storage-prefix","form","client","validate-on-blur","style-id"];x.observedAttributes.forEach((e=>{if(!t.includes(e)&&!this[d(e)])throw Error(`${e} cannot be empty`)}))},W=function(){const{stepId:e,executionId:i}=c(this.flowId);t(this,j,"f").update({stepId:e,executionId:i})},D=function(t,i){this.sdk=n(Object.assign(Object.assign({persistTokens:!0,preview:this.preview,storagePrefix:this.storagePrefix,storeLastAuthenticatedUser:this.storeLastAuthenticatedUser,keepLastAuthenticatedUserAfterLogout:this.keepLastAuthenticatedUserAfterLogout,refreshCookieName:this.refreshCookieName},x.sdkConfigOverrides),{projectId:t,baseUrl:i})),["start","next"].forEach((t=>{const i=this.sdk.flow[t];this.sdk.flow[t]=(...t)=>e(this,void 0,void 0,(function*(){try{return yield i(...t)}catch(t){return{error:{errorCode:k,errorDescription:t.toString()}}}}))}))},N=function(i,r,s){return e(this,void 0,void 0,(function*(){const{projectId:e,baseUrl:r}=i;if(s("projectId")||s("baseUrl")){if(!e)return;t(this,A,"m",D).call(this,e,r)}t(this,M,"f").call(this,i)}))},P=function(){return e(this,void 0,void 0,(function*(){const e=yield this.getConfig();return"isMissingConfig"in e&&e.isMissingConfig&&(yield t(this,A,"m",R).call(this))}))},R=function(){return e(this,void 0,void 0,(function*(){const t=h({projectId:this.projectId,filename:w,assetsFolder:C,baseUrl:this.baseStaticUrl});try{return yield f(t,"json"),!0}catch(t){return!1}}))},F=function(e){i(this,E,Object.assign(Object.assign({},t(this,E,"f")),e.detail),"f")},T=function(){var e;null===(e=t(this,L,"f"))||void 0===e||e.remove(),i(this,L,null,"f")},B=function(r){return e(this,arguments,void 0,(function*({isDebug:e}){e?(i(this,L,document.createElement("descope-debugger"),"f"),Object.assign(t(this,L,"f").style,{position:"fixed",top:"0",right:"0",height:"100vh",width:"100vw",pointerEvents:"none",zIndex:99999}),yield import("../debugger-wc.js"),document.body.appendChild(t(this,L,"f"))):t(this,A,"m",T).call(this)}))},V=function(e,i){var r;e&&this.debug&&(null===(r=t(this,L,"f"))||void 0===r||r.updateData({title:e,description:i}))},q=function(){this.rootElement.onkeydown=t=>{var e,i,r;const s=!!(null===(e=this.shadowRoot.activeElement)||void 0===e?void 0:e.getAttribute("href")),o=a.includes(null!==(r=null===(i=this.shadowRoot.activeElement)||void 0===i?void 0:i.localName)&&void 0!==r?r:"");if("Enter"!==t.key||s||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 u=Array.from(n).filter((t=>"true"===t.getAttribute("auto-submit")));if(1===u.length)return void u[0].click();const l=Array.from(n).filter((t=>"button"===t.getAttribute("data-type")));if(1===l.length)"false"!==l[0].getAttribute("auto-submit")&&l[0].click();else if(0===l.length){const t=Array.from(n).filter((t=>"sso"===t.getAttribute("data-type")));1===t.length&&"false"!==t[0].getAttribute("auto-submit")&&t[0].click()}}},K.sdkConfigOverrides={baseHeaders:{"x-descope-sdk-name":"web-component","x-descope-sdk-version":"3.37.0"}};export{K as default};
|
|
2
2
|
//# sourceMappingURL=BaseDescopeWc.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{__classPrivateFieldGet as e,__classPrivateFieldSet as t,__awaiter as i,__rest as s}from"tslib";import{ensureFingerprintIds as o,clearFingerprintData as n}from"@descope/web-js-sdk";import{URL_CODE_PARAM_NAME as r,URL_TOKEN_PARAM_NAME as a,URL_RUN_IDS_PARAM_NAME as l,RESPONSE_ACTIONS as d,CUSTOM_INTERACTIONS as c,SDK_SCRIPTS_LOAD_TIMEOUT as h,ELEMENT_TYPE_ATTRIBUTE as p,DESCOPE_ATTRIBUTE_EXCLUDE_FIELD as u,DESCOPE_ATTRIBUTE_EXCLUDE_NEXT_BUTTON as g}from"../constants/index.js";import{timeoutPromise as m,withMemCache as v,leadingDebounce as f,getUserLocale as b,showFirstScreenOnExecutionInit as w,injectSamlIdpForm as y,getAnimationDirection as I,transformStepStateForCustomScreen as S,getElementDescopeAttributes as k,submitForm as R,handleReportValidityOnBlur as C,handleAutoFocus as O,getFirstNonEmptyValue as W,clearPreviousExternalInputs as j}from"../helpers/helpers.js";import x from"../helpers/state.js";import{disableWebauthnButtons as A,updateTemplateFromScreenState as E,setPhoneAutoDetectDefaultCode as T,setTOTPVariable as U,setNOTPVariable as L,setCssVars as N,updateScreenFromScreenState as $}from"../helpers/templates.js";import{isConditionalLoginSupported as P}from"../helpers/webauthn.js";import{getABTestingKey as q}from"../helpers/abTestingKey.js";import{calculateConditions as F,calculateCondition as V}from"../helpers/conditions.js";import{setLastAuth as D,getLastAuth as M}from"../helpers/lastAuth.js";import{Direction as K}from"../types.js";import B from"./BaseDescopeWc.js";import H,{getScriptResultPath as _}from"./sdkScripts/index.js";import{FETCH_EXCEPTION_ERROR_CODE as G,FETCH_ERROR_RESPONSE_ERROR_CODE as J}from"../constants/general.js";var z,Q,X,Y,Z,ee,te,ie,se,oe,ne,re,ae,le,de,ce,he,pe,ue,ge,me,ve,fe,be,we,ye,Ie;class Se extends B{static set sdkConfigOverrides(e){B.sdkConfigOverrides=e}static get sdkConfigOverrides(){return B.sdkConfigOverrides}constructor(){const s=new x({deferredRedirect:!1});super(s.update.bind(s)),z.add(this),this.stepState=new x({}),Q.set(this,void 0),X.set(this,null),Y.set(this,null),Z.set(this,{visibilitychange:e(this,z,"m",ee).bind(this)}),this.bridgeVersion=1,this.nativeResume=(t,i)=>{var s;const o=JSON.parse(i);if(this.logger.info(`nativeResume received payload of type '${t}'`),"oauthWeb"===t||"sso"===t){let{exchangeCode:e}=o;if(!e){e=null===(s=new URL(o.url).searchParams)||void 0===s?void 0:s.get(r)}this.nativeComplete({exchangeCode:e,idpInitiated:!0})}else if("magicLink"===t){const t=new URL(o.url),i=t.searchParams.get(a),s=t.searchParams.get(l).split("_").pop();e(this,ne,"f").call(this),this.flowState.update({token:i,stepId:s,action:void 0})}else this.nativeComplete(o)},se.set(this,(e=>{this.contentRootElement.classList.toggle("hidden",e),this.slotElement.classList.toggle("hidden",!e)})),oe.set(this,((s,o,n,r,a=!1)=>{if(this.flowState.current.action===d.poll){this.logger.debug("polling - Scheduling polling request");const l=Date.now(),d=a?500:2e3;t(this,Q,setTimeout((()=>i(this,void 0,void 0,(function*(){var t;this.logger.debug("polling - Calling next");const i=this.sdk.flow.next(s,o,c.polling,n,r,{}),h=document.hidden&&!a&&Date.now()-l>d+500;let p;h&&this.logger.debug("polling - The polling seems to be throttled");try{const e=h?1e3:6e3;p=yield m(e,i)}catch(t){return this.logger.warn(`polling - The ${h?"throttled fetch":"fetch"} call timed out or was aborted`),void e(this,oe,"f").call(this,s,o,n,r,h)}if((null===(t=null==p?void 0:p.error)||void 0===t?void 0:t.errorCode)===G)return this.logger.debug("polling - Got a generic error due to exception in fetch call"),void e(this,oe,"f").call(this,s,o,n,r);this.logger.debug("polling - Got a response"),(null==p?void 0:p.error)&&this.logger.debug("polling - Response has an error",JSON.stringify(p.error,null,4)),e(this,oe,"f").call(this,s,o,n,r),e(this,re,"f").call(this,p)}))),d),"f")}})),ne.set(this,(()=>{clearTimeout(e(this,Q,"f")),t(this,Q,null,"f")})),re.set(this,(i=>{var s,o,n,r,a,l,c,h,p,u,g,m,v;if(!(null==i?void 0:i.ok)){const t=null===(s=null==i?void 0:i.response)||void 0===s?void 0:s.url,d=`${null===(o=null==i?void 0:i.response)||void 0===o?void 0:o.status} - ${null===(n=null==i?void 0:i.response)||void 0===n?void 0:n.statusText}`;e(this,z,"m",Ie).call(this,"error",(null==i?void 0:i.error)||{errorCode:J,errorDescription:d,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)||d);const c=null===(l=null==i?void 0:i.error)||void 0===l?void 0:l.errorCode;return void("E102004"!==c&&"E103205"!==c||!this.isRestartOnError||e(this,z,"m",te).call(this))}null===(h=null===(c=i.data)||void 0===c?void 0:c.runnerLogs)||void 0===h||h.forEach((e=>{const{level:t,title:i,log:s}=e;t&&this.loggerWrapper[t]?this.loggerWrapper[t](i,s):this.loggerWrapper.info(i,s)}));const f=null===(g=null===(u=null===(p=i.data)||void 0===p?void 0:p.screen)||void 0===u?void 0:u.state)||void 0===g?void 0:g.errorText;(null===(m=i.data)||void 0===m?void 0:m.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:y,action:I}=i.data;if(I!==d.poll&&e(this,ne,"f").call(this),"completed"===b)return this.storeLastAuthenticatedUser&&D(y),void e(this,z,"m",Ie).call(this,"success",w);const{executionId:S,stepId:k,stepName:R,screen:C,redirect:O,openInNewTabUrl:W,webauthn:j,error:x,samlIdpResponse:A,nativeResponse:E}=i.data,T=Date.now();I!==d.poll?(this.loggerWrapper.info(`Step "${R||`#${k}`}" is ${b}`,"",{screen:C,status:b,stepId:k,stepName:R,action:I,error:x}),(null===(v=C.state)||void 0===v?void 0:v.clientScripts)&&t(this,Y,this.loadSdkScripts(C.state.clientScripts),"f"),this.flowState.update({stepId:k,stepName:R,executionId:S,action:I,redirectTo:null==O?void 0:O.url,openInNewTabUrl:W,screenId:null==C?void 0:C.id,screenState:null==C?void 0:C.state,webauthnTransactionId:null==j?void 0:j.transactionId,webauthnOptions:null==j?void 0:j.options,samlIdpResponseUrl:null==A?void 0:A.url,samlIdpResponseSamlResponse:null==A?void 0:A.samlResponse,samlIdpResponseRelayState:null==A?void 0:A.relayState,nativeResponseType:null==E?void 0:E.type,nativePayload:null==E?void 0:E.payload,reqTimestamp:T})):this.flowState.update({action:I,reqTimestamp:T})})),ae.set(this,v((()=>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)}}))))),fe.set(this,f(((t,s)=>i(this,void 0,void 0,(function*(){var i;if("true"===t.getAttribute("formnovalidate")||e(this,z,"m",he).call(this)){const o=null==t?void 0:t.getAttribute("id");e(this,z,"m",ue).call(this,t);const n=yield e(this,z,"m",pe).call(this),r=k(t);if(this.nextRequestStatus.update({isLoading:!0}),e(this,Y,"f")){this.loggerWrapper.debug("Waiting for sdk scripts to load");const t=Date.now();yield e(this,Y,"f"),this.loggerWrapper.debug("Sdk scripts loaded for",(Date.now()-t).toString())}const a=this.getComponentsContext(),l=Object.assign(Object.assign(Object.assign(Object.assign({},a),r),n),{origin:(null===(i=this.nativeOptions)||void 0===i?void 0:i.origin)||window.location.origin});yield s(o,l),this.nextRequestStatus.update({isLoading:!1}),e(this,z,"m",ge).call(this,n)}}))))),this.flowState=s}loadSdkScripts(e){if(!(null==e?void 0:e.length))return null;const t=(e,t)=>i=>{this.dispatchEvent(new CustomEvent("components-context",{detail:{[_(e.id,e.resultKey)]:i},bubbles:!0,composed:!0})),t(e.id)};this.loggerWrapper.debug(`Preparing to load scripts: ${e.map((e=>e.id)).join(", ")}`);const s=Promise.all(null==e?void 0:e.map((e=>i(this,void 0,void 0,(function*(){var i;const s=this.shadowRoot.querySelector(`[data-script-id="${e.id}"]`);if(s){this.loggerWrapper.debug("Script already loaded",e.id);const{moduleRes:t}=s;return null===(i=null==t?void 0:t.start)||void 0===i||i.call(t),t}const o=yield H(e.id);return new Promise(((i,s)=>{try{const s=o(e.initArgs,{baseUrl:this.baseUrl},t(e,i));if(s){const t=document.createElement("div");t.setAttribute("data-script-id",e.id),t.moduleRes=s,this.shadowRoot.appendChild(t),this.nextRequestStatus.subscribe((()=>{var t;this.loggerWrapper.debug("Unloading script",e.id),null===(t=s.stop)||void 0===t||t.call(s)}))}}catch(e){s(e)}}))}))))),o=new Promise((e=>{setTimeout((()=>{this.loggerWrapper.warn("SDK scripts loading timeout"),e(!0)}),h)}));return Promise.race([s,o])}init(){if(!window.isDescopeBridge)return this._init();this.lazyInit=this._init}_init(){const t=Object.create(null,{init:{get:()=>super.init}});return i(this,void 0,void 0,(function*(){var i,s,o;this.shadowRoot.isConnected&&(null===(i=this.flowState)||void 0===i||i.subscribe(this.onFlowChange.bind(this)),null===(s=this.stepState)||void 0===s||s.subscribe(this.onStepChange.bind(this)),window.addEventListener("visibilitychange",e(this,Z,"f").visibilitychange)),yield null===(o=t.init)||void 0===o?void 0:o.call(this)}))}disconnectedCallback(){var i;super.disconnectedCallback(),this.flowState.unsubscribeAll(),this.stepState.unsubscribeAll(),null===(i=e(this,X,"f"))||void 0===i||i.abort(),t(this,X,null,"f"),window.removeEventListener("visibilitychange",e(this,Z,"f").visibilitychange)}getHtmlFilenameWithLocale(e,t){return i(this,void 0,void 0,(function*(){let i;const s=b(e),o=yield this.getTargetLocales();return o.includes(s.locale)?i=`${t}-${s.locale}.html`:o.includes(s.fallback)&&(i=`${t}-${s.fallback}.html`),i}))}getPageContent(e,t){return i(this,void 0,void 0,(function*(){if(t)try{const{body:e}=yield this.fetchStaticResource(t,"text");return e}catch(i){this.loggerWrapper.error(`Failed to fetch flow page from ${t}. Fallback to url ${e}`,i)}try{const{body:t}=yield this.fetchStaticResource(e,"text");return t}catch(e){this.loggerWrapper.error("Failed to fetch flow page",e.message)}return null}))}onFlowChange(r,a,l){return i(this,void 0,void 0,(function*(){var h,p;const{projectId:u,flowId:g,tenant:m,stepId:v,executionId:f,action:S,screenId:k,screenState:C,redirectTo:O,openInNewTabUrl:W,redirectUrl:j,token:x,code:A,exchangeError:E,webauthnTransactionId:T,webauthnOptions:U,redirectAuthCodeChallenge:L,redirectAuthCallbackUrl:N,redirectAuthBackupCallbackUri:$,redirectAuthInitiator:P,locale:D,samlIdpResponseUrl:K,samlIdpResponseSamlResponse:B,samlIdpResponseRelayState:H,nativeResponseType:_,nativePayload:G,reqTimestamp:J}=r,Q=s(r,["projectId","flowId","tenant","stepId","executionId","action","screenId","screenState","redirectTo","openInNewTabUrl","redirectUrl","token","code","exchangeError","webauthnTransactionId","webauthnOptions","redirectAuthCodeChallenge","redirectAuthCallbackUrl","redirectAuthBackupCallbackUri","redirectAuthInitiator","locale","samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState","nativeResponseType","nativePayload","reqTimestamp"]);let Z,ee,te;const se=q(),ne=this.sdk.getLastUserLoginId(),ae=yield this.getFlowConfig(),le=yield this.getProjectConfig(),de=Object.entries(le.flows||{}).reduce(((e,[t,i])=>(e[t]=i.version,e)),{}),ce=N&&L?{callbackUrl:N,codeChallenge:L,backupCallbackUri:$}:void 0,he=this.nativeOptions?{platform:this.nativeOptions.platform,oauthProvider:this.nativeOptions.oauthProvider,oauthRedirect:this.nativeOptions.oauthRedirect,magicLinkRedirect:this.nativeOptions.magicLinkRedirect,ssoRedirect:this.nativeOptions.ssoRedirect}:void 0;if(!f){const i=[...ae.clientScripts||[],...ae.sdkScripts||[]];if(ae.conditions){let e=[];({startScreenId:Z,conditionInteractionId:te,startScreenName:ee,clientScripts:e}=F({loginId:ne,code:A,token:x,abTestingKey:se},ae.conditions)),i.push(...e||[])}else ae.condition?({startScreenId:Z,conditionInteractionId:te}=V(ae.condition,{loginId:ne,code:A,token:x,abTestingKey:se})):(ee=ae.startScreenName,Z=ae.startScreenId);if(t(this,Y,this.loadSdkScripts(i),"f"),ae.fingerprintEnabled&&ae.fingerprintKey?yield o(ae.fingerprintKey,this.baseUrl):n(),!w(Z,Q)){const t=yield this.sdk.flow.start(g,Object.assign(Object.assign(Object.assign(Object.assign({tenant:m,redirectAuth:ce},Q),{client:this.client}),j&&{redirectUrl:j}),{lastAuth:M(ne),abTestingKey:se,locale:b(D).locale,nativeOptions:he}),te,"",le.componentsVersion,de,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),A?{exchangeCode:A,idpInitiated:!0}:{}),Q.descopeIdpInitiated&&{idpInitiated:!0}),x?{token:x}:{}),Q.oidcLoginHint?{externalId:Q.oidcLoginHint}:{}));return e(this,re,"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(f&&(l("token")&&x||l("code")&&A||l("exchangeError")&&E)){const t=yield this.sdk.flow.next(f,v,c.submit,ae.version,le.componentsVersion,{token:x,exchangeCode:A,exchangeError:E});return e(this,re,"f").call(this,t),void this.flowState.update({token:void 0,code:void 0,exchangeError:void 0})}if(S===d.loadForm&&["samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState"].some((e=>l(e)))){if(!K||!B)return void this.loggerWrapper.error("Did not get saml idp params data to load");y(K,B,H||"",R)}if(S===d.redirect&&(l("redirectTo")||l("deferredRedirect")))return O?"android"===P&&document.hidden?void this.flowState.update({deferredRedirect:!0}):void window.location.assign(O):void this.loggerWrapper.error("Did not get redirect url");if(S===d.webauthnCreate||S===d.webauthnGet){if(!T||!U)return void this.loggerWrapper.error("Did not get webauthn transaction id or options");let i,s;null===(p=e(this,X,"f"))||void 0===p||p.abort(),t(this,X,null,"f");try{i=S===d.webauthnCreate?yield this.sdk.webauthn.helpers.create(U):yield this.sdk.webauthn.helpers.get(U)}catch(e){"InvalidStateError"===e.name?this.loggerWrapper.warn("WebAuthn operation failed",e.message):"NotAllowedError"!==e.name&&this.loggerWrapper.error(e.message),s=e.name}const o=yield this.sdk.flow.next(f,v,c.submit,ae.version,le.componentsVersion,{transactionId:T,response:i,failure:s});e(this,re,"f").call(this,o)}if(S===d.nativeBridge)return this.nativeComplete=t=>i(this,void 0,void 0,(function*(){const i=yield this.sdk.flow.next(f,v,c.submit,ae.version,le.componentsVersion,t);e(this,re,"f").call(this,i)})),void e(this,z,"m",Ie).call(this,"bridge",{type:_,payload:G});if(l("action")&&e(this,oe,"f").call(this,f,v,ae.version,le.componentsVersion),!k&&!Z)return void this.loggerWrapper.warn("No screen was found to show");const pe=Z||k,ue=yield this.getHtmlFilenameWithLocale(D,pe),{oidcLoginHint:ge,oidcPrompt:me,oidcErrorRedirectUri:ve,samlIdpUsername:fe}=Q,be={direction:I(v,a.stepId),screenState:Object.assign(Object.assign({},C),{form:Object.assign(Object.assign({},this.formConfigValues),null==C?void 0:C.form),lastAuth:{loginId:ne,name:this.sdk.getLastUserDisplayName()||ne}}),htmlFilename:`${pe}.html`,htmlLocaleFilename:ue,screenId:pe,stepName:r.stepName||ee,samlIdpUsername:fe,oidcLoginHint:ge,oidcPrompt:me,oidcErrorRedirectUri:ve,openInNewTabUrl:W},we=M(ne);w(Z,Q)?be.next=(t,s)=>i(this,void 0,void 0,(function*(){const i=yield this.sdk.flow.start(g,Object.assign(Object.assign(Object.assign(Object.assign({tenant:m,redirectAuth:ce},Q),{lastAuth:we,preview:this.preview,abTestingKey:se,client:this.client}),j&&{redirectUrl:j}),{locale:b(D).locale,nativeOptions:he}),te,t,le.componentsVersion,de,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),s),A&&{exchangeCode:A,idpInitiated:!0}),Q.descopeIdpInitiated&&{idpInitiated:!0}),x&&{token:x}));return e(this,re,"f").call(this,i),i})):(l("projectId")||l("baseUrl")||l("executionId")||l("stepId"))&&(be.next=(t,s)=>i(this,void 0,void 0,(function*(){const i=yield this.sdk.flow.next(f,v,t,ae.version,le.componentsVersion,s);return e(this,re,"f").call(this,i),i}))),this.loggerWrapper.debug("Got a screen with id",be.screenId),yield e(this,z,"m",ie).call(this,be),this.stepState.update(be)}))}onStepChange(t,s){return i(this,void 0,void 0,(function*(){var o,n;const{htmlFilename:r,htmlLocaleFilename:a,direction:l,next:d,screenState:h,openInNewTabUrl:u}=t;this.loggerWrapper.debug("Rendering a flow screen");const g=document.createElement("template");g.innerHTML=yield this.getPageContent(r,a);const m=g.content.cloneNode(!0),v=this.loadDescopeUiComponents(g);this.sdk.webauthn.helpers.isSupported()?yield e(this,z,"m",de).call(this,m,d):A(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),E(m,h,h.componentsConfig,this.formConfig,this.errorTransformer,this.loggerWrapper);const{geo:f}=yield this.getExecutionContext();T(m,f);const b=()=>i(this,void 0,void 0,(function*(){var i,o;yield v;const n=this.contentRootElement;U(n,null===(i=null==h?void 0:h.totp)||void 0===i?void 0:i.image),L(n,null===(o=null==h?void 0:h.notp)||void 0===o?void 0:o.image),N(n,m,h.cssVars,this.loggerWrapper),n.replaceChildren(m);const r=!s.htmlFilename;setTimeout((()=>{e(this,z,"m",me).call(this),this.validateOnBlur&&C(n),$(n,h),e(this,z,"m",ce).call(this,{isFirstScreen:r,stepName:t.stepName}),O(n,this.autoFocus,r)})),e(this,z,"m",we).call(this,d);n.querySelector(`[${p}="polling"]`)&&d(c.polling,{}),u&&!s.openInNewTabUrl&&window.open(u,"_blank")}));l?e(this,z,"m",ye).call(this,b,l):b()}))}}Q=new WeakMap,X=new WeakMap,Y=new WeakMap,Z=new WeakMap,se=new WeakMap,oe=new WeakMap,ne=new WeakMap,re=new WeakMap,ae=new WeakMap,fe=new WeakMap,z=new WeakSet,ee=function(){document.hidden||setTimeout((()=>{this.flowState.update({deferredRedirect:!1})}),300)},te=function(){return i(this,void 0,void 0,(function*(){this.loggerWrapper.debug("Trying to restart the flow");const e=yield this.getComponentsVersion();this.reset();e===(yield this.getComponentsVersion())?(this.loggerWrapper.debug("Components version was not changed, restarting flow"),this.flowState.update({stepId:null,executionId:null})):this.loggerWrapper.error("Components version mismatch, please reload the page")}))},ie=function(t){return i(this,void 0,void 0,(function*(){var i;const o=Object.assign(Object.assign({},this.stepState.current),t),{next:n,stepName:r}=o,a=s(o,["next","stepName"]),l=Boolean(yield null===(i=this.onScreenUpdate)||void 0===i?void 0:i.call(this,r,S(a),n,this));if(l){this.loggerWrapper.debug("Rendering a custom screen"),this.contentRootElement.innerHTML="",e(this,z,"m",ce).call(this,{isFirstScreen:!this.stepState.current.htmlFilename,stepName:t.stepName}),this.stepState.unsubscribeAll();const i=this.stepState.subscribe((()=>{var e;this.stepState.unsubscribe(i),null===(e=this.stepState)||void 0===e||e.subscribe(this.onStepChange.bind(this))}))}e(this,se,"f").call(this,l)}))},le=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,X,"f"))||void 0===n||n.abort();const r=s.querySelector('*[autocomplete="webauthn"]');if(r&&(yield P())){const{options:s,transactionId:n}=(yield e(this,ae,"f").call(this))||{};s&&n&&(e(this,z,"m",le).call(this,r),t(this,X,new AbortController,"f"),this.sdk.webauthn.helpers.conditional(s,e(this,X,"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)})))}}))},ce=function({isFirstScreen:t,stepName:i}){t&&e(this,z,"m",Ie).call(this,"ready",{}),e(this,z,"m",Ie).call(this,"page-updated",{screenName:i}),e(this,z,"m",Ie).call(this,"screen-updated",{screenName:i})},he=function(){let e=!0;return Array.from(this.shadowRoot.querySelectorAll("*[name]")).reverse().forEach((t=>{var i,s;"slot"!==t.localName&&(null===(i=t.reportValidity)||void 0===i||i.call(t),e&&(e=null===(s=t.checkValidity)||void 0===s?void 0:s.call(t)))})),e},pe=function(){return i(this,void 0,void 0,(function*(){const e=Array.from(this.shadowRoot.querySelectorAll(`*[name]:not([${u}])`));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})),{})}))},ue=function(e){const t=this.nextRequestStatus.subscribe((({isLoading:i})=>{i?e.setAttribute("loading","true"):(this.nextRequestStatus.unsubscribe(t),e.removeAttribute("loading"))}))},ge=function(e={}){var t,i;const s=W(e,["externalId","email","phone"]),o=W(e,["newPassword","password"]);if(s&&o)try{if(!globalThis.PasswordCredential)return;const e=new globalThis.PasswordCredential({id:s,password:o});null===(i=null===(t=null===navigator||void 0===navigator?void 0:navigator.credentials)||void 0===t?void 0:t.store)||void 0===i||i.call(t,e)}catch(e){this.loggerWrapper.error("Could not store credentials",e.message)}},me=function(){j();this.contentRootElement.querySelectorAll('[external-input="true"]').forEach((t=>e(this,z,"m",ve).call(this,t)))},ve=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)}))},be=function(t){this.contentRootElement.querySelectorAll('descope-passcode[data-auto-submit="true"]').forEach((i=>{i.addEventListener("input",(()=>{var s;(null===(s=i.checkValidity)||void 0===s?void 0:s.call(i))&&e(this,fe,"f").call(this,i,t)}))}))},we=function(t){this.contentRootElement.querySelectorAll(`descope-button:not([${g}])`).forEach((i=>{i.onclick=()=>{e(this,fe,"f").call(this,i,t)}})),e(this,z,"m",be).call(this,t)},ye=function(e,t){this.contentRootElement.addEventListener("transitionend",(()=>{this.contentRootElement.classList.remove("fade-out"),e()}),{once:!0});const i=t===K.forward?"slide-forward":"slide-backward";Array.from(this.contentRootElement.getElementsByClassName("input-container")).forEach(((e,t)=>{e.style["transition-delay"]=40*t+"ms",e.classList.add(i)})),this.contentRootElement.classList.add("fade-out")},Ie=function(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t}))};export{Se as default};
|
|
1
|
+
import{__classPrivateFieldGet as e,__classPrivateFieldSet as t,__awaiter as i,__rest as s}from"tslib";import{ensureFingerprintIds as o,clearFingerprintData as n}from"@descope/web-js-sdk";import{URL_CODE_PARAM_NAME as r,URL_TOKEN_PARAM_NAME as a,URL_RUN_IDS_PARAM_NAME as l,RESPONSE_ACTIONS as d,CUSTOM_INTERACTIONS as c,SDK_SCRIPTS_LOAD_TIMEOUT as h,ELEMENT_TYPE_ATTRIBUTE as p,DESCOPE_ATTRIBUTE_EXCLUDE_FIELD as u,DESCOPE_ATTRIBUTE_EXCLUDE_NEXT_BUTTON as g}from"../constants/index.js";import{timeoutPromise as m,withMemCache as v,leadingDebounce as f,getUserLocale as b,showFirstScreenOnExecutionInit as w,injectSamlIdpForm as y,getAnimationDirection as I,transformStepStateForCustomScreen as S,getElementDescopeAttributes as k,submitForm as R,handleReportValidityOnBlur as C,handleAutoFocus as O,getFirstNonEmptyValue as j,clearPreviousExternalInputs as W}from"../helpers/helpers.js";import x from"../helpers/state.js";import{disableWebauthnButtons as A,updateTemplateFromScreenState as E,setPhoneAutoDetectDefaultCode as T,setTOTPVariable as U,setNOTPVariable as L,setCssVars as N,updateScreenFromScreenState as $}from"../helpers/templates.js";import{isConditionalLoginSupported as P}from"../helpers/webauthn.js";import{getABTestingKey as q}from"../helpers/abTestingKey.js";import{calculateConditions as F,calculateCondition as V}from"../helpers/conditions.js";import{setLastAuth as D,getLastAuth as M}from"../helpers/lastAuth.js";import{Direction as K}from"../types.js";import B from"./BaseDescopeWc.js";import H,{getScriptResultPath as _}from"./sdkScripts/index.js";import{FETCH_EXCEPTION_ERROR_CODE as G,FETCH_ERROR_RESPONSE_ERROR_CODE as J}from"../constants/general.js";var z,Q,X,Y,Z,ee,te,ie,se,oe,ne,re,ae,le,de,ce,he,pe,ue,ge,me,ve,fe,be,we,ye,Ie;class Se extends B{static set sdkConfigOverrides(e){B.sdkConfigOverrides=e}static get sdkConfigOverrides(){return B.sdkConfigOverrides}constructor(){const s=new x({deferredRedirect:!1});super(s.update.bind(s)),z.add(this),this.stepState=new x({}),Q.set(this,void 0),X.set(this,null),Y.set(this,null),Z.set(this,{visibilitychange:e(this,z,"m",ee).bind(this)}),this.bridgeVersion=1,this.nativeResume=(t,i)=>{var s;const o=JSON.parse(i);if(this.logger.info(`nativeResume received payload of type '${t}'`),"oauthWeb"===t||"sso"===t){let{exchangeCode:e}=o;if(!e){e=null===(s=new URL(o.url).searchParams)||void 0===s?void 0:s.get(r)}this.nativeComplete({exchangeCode:e,idpInitiated:!0})}else if("magicLink"===t){const t=new URL(o.url),i=t.searchParams.get(a),s=t.searchParams.get(l).split("_").pop();e(this,ne,"f").call(this),this.flowState.update({token:i,stepId:s,action:void 0})}else this.nativeComplete(o)},se.set(this,(e=>{this.contentRootElement.classList.toggle("hidden",e),this.slotElement.classList.toggle("hidden",!e)})),oe.set(this,((s,o,n,r,a=!1)=>{if(this.flowState.current.action===d.poll){this.logger.debug("polling - Scheduling polling request");const l=Date.now(),d=a?500:2e3;t(this,Q,setTimeout((()=>i(this,void 0,void 0,(function*(){var t;this.logger.debug("polling - Calling next");const i=this.sdk.flow.next(s,o,c.polling,n,r,{}),h=document.hidden&&!a&&Date.now()-l>d+500;let p;h&&this.logger.debug("polling - The polling seems to be throttled");try{const e=h?1e3:6e3;p=yield m(e,i)}catch(t){return this.logger.warn(`polling - The ${h?"throttled fetch":"fetch"} call timed out or was aborted`),void e(this,oe,"f").call(this,s,o,n,r,h)}if((null===(t=null==p?void 0:p.error)||void 0===t?void 0:t.errorCode)===G)return this.logger.debug("polling - Got a generic error due to exception in fetch call"),void e(this,oe,"f").call(this,s,o,n,r);this.logger.debug("polling - Got a response"),(null==p?void 0:p.error)&&this.logger.debug("polling - Response has an error",JSON.stringify(p.error,null,4)),e(this,oe,"f").call(this,s,o,n,r),e(this,re,"f").call(this,p)}))),d),"f")}})),ne.set(this,(()=>{clearTimeout(e(this,Q,"f")),t(this,Q,null,"f")})),re.set(this,(i=>{var s,o,n,r,a,l,c,h,p,u,g,m,v;if(!(null==i?void 0:i.ok)){const t=null===(s=null==i?void 0:i.response)||void 0===s?void 0:s.url,d=`${null===(o=null==i?void 0:i.response)||void 0===o?void 0:o.status} - ${null===(n=null==i?void 0:i.response)||void 0===n?void 0:n.statusText}`;e(this,z,"m",Ie).call(this,"error",(null==i?void 0:i.error)||{errorCode:J,errorDescription:d,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)||d);const c=null===(l=null==i?void 0:i.error)||void 0===l?void 0:l.errorCode;return void("E102004"!==c&&"E103205"!==c||!this.isRestartOnError||e(this,z,"m",te).call(this))}null===(h=null===(c=i.data)||void 0===c?void 0:c.runnerLogs)||void 0===h||h.forEach((e=>{const{level:t,title:i,log:s}=e;t&&this.loggerWrapper[t]?this.loggerWrapper[t](i,s):this.loggerWrapper.info(i,s)}));const f=null===(g=null===(u=null===(p=i.data)||void 0===p?void 0:p.screen)||void 0===u?void 0:u.state)||void 0===g?void 0:g.errorText;(null===(m=i.data)||void 0===m?void 0:m.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:y,action:I}=i.data;if(I!==d.poll&&e(this,ne,"f").call(this),"completed"===b)return this.storeLastAuthenticatedUser&&D(y),void e(this,z,"m",Ie).call(this,"success",w);const{executionId:S,stepId:k,stepName:R,screen:C,redirect:O,openInNewTabUrl:j,webauthn:W,error:x,samlIdpResponse:A,nativeResponse:E}=i.data,T=Date.now();I!==d.poll?(this.loggerWrapper.info(`Step "${R||`#${k}`}" is ${b}`,"",{screen:C,status:b,stepId:k,stepName:R,action:I,error:x}),(null===(v=C.state)||void 0===v?void 0:v.clientScripts)&&t(this,Y,this.loadSdkScripts(C.state.clientScripts),"f"),this.flowState.update({stepId:k,stepName:R,executionId:S,action:I,redirectTo:null==O?void 0:O.url,openInNewTabUrl:j,screenId:null==C?void 0:C.id,screenState:null==C?void 0:C.state,webauthnTransactionId:null==W?void 0:W.transactionId,webauthnOptions:null==W?void 0:W.options,samlIdpResponseUrl:null==A?void 0:A.url,samlIdpResponseSamlResponse:null==A?void 0:A.samlResponse,samlIdpResponseRelayState:null==A?void 0:A.relayState,nativeResponseType:null==E?void 0:E.type,nativePayload:null==E?void 0:E.payload,reqTimestamp:T})):this.flowState.update({action:I,reqTimestamp:T})})),ae.set(this,v((()=>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)}}))))),fe.set(this,f(((t,s)=>i(this,void 0,void 0,(function*(){var i;if("true"===t.getAttribute("formnovalidate")||e(this,z,"m",he).call(this)){const o=null==t?void 0:t.getAttribute("id");e(this,z,"m",ue).call(this,t);const n=yield e(this,z,"m",pe).call(this),r=k(t);if(this.nextRequestStatus.update({isLoading:!0}),e(this,Y,"f")){this.loggerWrapper.debug("Waiting for sdk scripts to load");const t=Date.now();yield e(this,Y,"f"),this.loggerWrapper.debug("Sdk scripts loaded for",(Date.now()-t).toString())}const a=this.getComponentsContext(),l=Object.assign(Object.assign(Object.assign(Object.assign({},a),r),n),{origin:(null===(i=this.nativeOptions)||void 0===i?void 0:i.origin)||window.location.origin});yield s(o,l),this.nextRequestStatus.update({isLoading:!1}),e(this,z,"m",ge).call(this,n)}}))))),this.flowState=s}loadSdkScripts(e){if(!(null==e?void 0:e.length))return null;const t=(e,t)=>i=>{this.dispatchEvent(new CustomEvent("components-context",{detail:{[_(e.id,e.resultKey)]:i},bubbles:!0,composed:!0})),t(e.id)};this.loggerWrapper.debug(`Preparing to load scripts: ${e.map((e=>e.id)).join(", ")}`);const s=Promise.all(null==e?void 0:e.map((e=>i(this,void 0,void 0,(function*(){var i;const s=this.shadowRoot.querySelector(`[data-script-id="${e.id}"]`);if(s){this.loggerWrapper.debug("Script already loaded",e.id);const{moduleRes:t}=s;return null===(i=null==t?void 0:t.start)||void 0===i||i.call(t),t}const o=yield H(e.id);return new Promise(((i,s)=>{try{const s=o(e.initArgs,{baseUrl:this.baseUrl},t(e,i));if(s){const t=document.createElement("div");t.setAttribute("data-script-id",e.id),t.moduleRes=s,this.shadowRoot.appendChild(t),this.nextRequestStatus.subscribe((()=>{var t;this.loggerWrapper.debug("Unloading script",e.id),null===(t=s.stop)||void 0===t||t.call(s)}))}}catch(e){s(e)}}))}))))),o=new Promise((e=>{setTimeout((()=>{this.loggerWrapper.warn("SDK scripts loading timeout"),e(!0)}),h)}));return Promise.race([s,o])}init(){if(!window.isDescopeBridge)return this._init();this.lazyInit=this._init}_init(){const t=Object.create(null,{init:{get:()=>super.init}});return i(this,void 0,void 0,(function*(){var i,s,o;this.shadowRoot.isConnected&&(null===(i=this.flowState)||void 0===i||i.subscribe(this.onFlowChange.bind(this)),null===(s=this.stepState)||void 0===s||s.subscribe(this.onStepChange.bind(this)),window.addEventListener("visibilitychange",e(this,Z,"f").visibilitychange)),yield null===(o=t.init)||void 0===o?void 0:o.call(this)}))}disconnectedCallback(){var i;super.disconnectedCallback(),this.flowState.unsubscribeAll(),this.stepState.unsubscribeAll(),null===(i=e(this,X,"f"))||void 0===i||i.abort(),t(this,X,null,"f"),window.removeEventListener("visibilitychange",e(this,Z,"f").visibilitychange)}getHtmlFilenameWithLocale(e,t){return i(this,void 0,void 0,(function*(){let i;const s=b(e),o=yield this.getTargetLocales();return o.includes(s.locale)?i=`${t}-${s.locale}.html`:o.includes(s.fallback)&&(i=`${t}-${s.fallback}.html`),i}))}getPageContent(e,t){return i(this,void 0,void 0,(function*(){if(t)try{const{body:e}=yield this.fetchStaticResource(t,"text");return e}catch(i){this.loggerWrapper.error(`Failed to fetch flow page from ${t}. Fallback to url ${e}`,i)}try{const{body:t}=yield this.fetchStaticResource(e,"text");return t}catch(e){this.loggerWrapper.error("Failed to fetch flow page",e.message)}return null}))}onFlowChange(r,a,l){return i(this,void 0,void 0,(function*(){var h,p;const{projectId:u,flowId:g,tenant:m,stepId:v,executionId:f,action:S,screenId:k,screenState:C,redirectTo:O,openInNewTabUrl:j,redirectUrl:W,token:x,code:A,exchangeError:E,webauthnTransactionId:T,webauthnOptions:U,redirectAuthCodeChallenge:L,redirectAuthCallbackUrl:N,redirectAuthBackupCallbackUri:$,redirectAuthInitiator:P,locale:D,samlIdpResponseUrl:K,samlIdpResponseSamlResponse:B,samlIdpResponseRelayState:H,nativeResponseType:_,nativePayload:G,reqTimestamp:J}=r,Q=s(r,["projectId","flowId","tenant","stepId","executionId","action","screenId","screenState","redirectTo","openInNewTabUrl","redirectUrl","token","code","exchangeError","webauthnTransactionId","webauthnOptions","redirectAuthCodeChallenge","redirectAuthCallbackUrl","redirectAuthBackupCallbackUri","redirectAuthInitiator","locale","samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState","nativeResponseType","nativePayload","reqTimestamp"]);let Z,ee,te;const se=q(),ne=this.sdk.getLastUserLoginId(),ae=yield this.getFlowConfig(),le=yield this.getProjectConfig(),de=Object.entries(le.flows||{}).reduce(((e,[t,i])=>(e[t]=i.version,e)),{}),ce=N&&L?{callbackUrl:N,codeChallenge:L,backupCallbackUri:$}:void 0,he=this.nativeOptions?{platform:this.nativeOptions.platform,oauthProvider:this.nativeOptions.oauthProvider,oauthRedirect:this.nativeOptions.oauthRedirect,magicLinkRedirect:this.nativeOptions.magicLinkRedirect,ssoRedirect:this.nativeOptions.ssoRedirect}:void 0;let pe={};if(!f){const i=[...ae.clientScripts||[],...ae.sdkScripts||[]];if(ae.conditions){let e=[];({startScreenId:Z,conditionInteractionId:te,startScreenName:ee,clientScripts:e,componentsConfig:pe}=F({loginId:ne,code:A,token:x,abTestingKey:se},ae.conditions)),i.push(...e||[])}else ae.condition?({startScreenId:Z,conditionInteractionId:te}=V(ae.condition,{loginId:ne,code:A,token:x,abTestingKey:se})):(ee=ae.startScreenName,Z=ae.startScreenId);if(t(this,Y,this.loadSdkScripts(i),"f"),ae.fingerprintEnabled&&ae.fingerprintKey?yield o(ae.fingerprintKey,this.baseUrl):n(),!w(Z,Q)){const t=yield this.sdk.flow.start(g,Object.assign(Object.assign(Object.assign(Object.assign({tenant:m,redirectAuth:ce},Q),{client:this.client}),W&&{redirectUrl:W}),{lastAuth:M(ne),abTestingKey:se,locale:b(D).locale,nativeOptions:he}),te,"",le.componentsVersion,de,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),A?{exchangeCode:A,idpInitiated:!0}:{}),Q.descopeIdpInitiated&&{idpInitiated:!0}),x?{token:x}:{}),Q.oidcLoginHint?{externalId:Q.oidcLoginHint}:{}));return e(this,re,"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(f&&(l("token")&&x||l("code")&&A||l("exchangeError")&&E)){const t=yield this.sdk.flow.next(f,v,c.submit,ae.version,le.componentsVersion,{token:x,exchangeCode:A,exchangeError:E});return e(this,re,"f").call(this,t),void this.flowState.update({token:void 0,code:void 0,exchangeError:void 0})}if(S===d.loadForm&&["samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState"].some((e=>l(e)))){if(!K||!B)return void this.loggerWrapper.error("Did not get saml idp params data to load");y(K,B,H||"",R)}if(S===d.redirect&&(l("redirectTo")||l("deferredRedirect")))return O?"android"===P&&document.hidden?void this.flowState.update({deferredRedirect:!0}):void window.location.assign(O):void this.loggerWrapper.error("Did not get redirect url");if(S===d.webauthnCreate||S===d.webauthnGet){if(!T||!U)return void this.loggerWrapper.error("Did not get webauthn transaction id or options");let i,s;null===(p=e(this,X,"f"))||void 0===p||p.abort(),t(this,X,null,"f");try{i=S===d.webauthnCreate?yield this.sdk.webauthn.helpers.create(U):yield this.sdk.webauthn.helpers.get(U)}catch(e){"InvalidStateError"===e.name?this.loggerWrapper.warn("WebAuthn operation failed",e.message):"NotAllowedError"!==e.name&&this.loggerWrapper.error(e.message),s=e.name}const o=yield this.sdk.flow.next(f,v,c.submit,ae.version,le.componentsVersion,{transactionId:T,response:i,failure:s});e(this,re,"f").call(this,o)}if(S===d.nativeBridge)return this.nativeComplete=t=>i(this,void 0,void 0,(function*(){const i=yield this.sdk.flow.next(f,v,c.submit,ae.version,le.componentsVersion,t);e(this,re,"f").call(this,i)})),void e(this,z,"m",Ie).call(this,"bridge",{type:_,payload:G});if(l("action")&&e(this,oe,"f").call(this,f,v,ae.version,le.componentsVersion),!k&&!Z)return void this.loggerWrapper.warn("No screen was found to show");const ue=Z||k,ge=yield this.getHtmlFilenameWithLocale(D,ue),{oidcLoginHint:me,oidcPrompt:ve,oidcErrorRedirectUri:fe,samlIdpUsername:be}=Q,we={direction:I(v,a.stepId),screenState:Object.assign(Object.assign({},C),{form:Object.assign(Object.assign({},this.formConfigValues),null==C?void 0:C.form),lastAuth:{loginId:ne,name:this.sdk.getLastUserDisplayName()||ne},componentsConfig:Object.assign(Object.assign(Object.assign({},ae.componentsConfig),pe),null==C?void 0:C.componentsConfig)}),htmlFilename:`${ue}.html`,htmlLocaleFilename:ge,screenId:ue,stepName:r.stepName||ee,samlIdpUsername:be,oidcLoginHint:me,oidcPrompt:ve,oidcErrorRedirectUri:fe,openInNewTabUrl:j},ye=M(ne);w(Z,Q)?we.next=(t,s)=>i(this,void 0,void 0,(function*(){const i=yield this.sdk.flow.start(g,Object.assign(Object.assign(Object.assign(Object.assign({tenant:m,redirectAuth:ce},Q),{lastAuth:ye,preview:this.preview,abTestingKey:se,client:this.client}),W&&{redirectUrl:W}),{locale:b(D).locale,nativeOptions:he}),te,t,le.componentsVersion,de,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),s),A&&{exchangeCode:A,idpInitiated:!0}),Q.descopeIdpInitiated&&{idpInitiated:!0}),x&&{token:x}));return e(this,re,"f").call(this,i),i})):(l("projectId")||l("baseUrl")||l("executionId")||l("stepId"))&&(we.next=(t,s)=>i(this,void 0,void 0,(function*(){const i=yield this.sdk.flow.next(f,v,t,ae.version,le.componentsVersion,s);return e(this,re,"f").call(this,i),i}))),this.loggerWrapper.debug("Got a screen with id",we.screenId),yield e(this,z,"m",ie).call(this,we),this.stepState.update(we)}))}onStepChange(t,s){return i(this,void 0,void 0,(function*(){var o,n;const{htmlFilename:r,htmlLocaleFilename:a,direction:l,next:d,screenState:h,openInNewTabUrl:u}=t;this.loggerWrapper.debug("Rendering a flow screen");const g=document.createElement("template");g.innerHTML=yield this.getPageContent(r,a);const m=g.content.cloneNode(!0),v=this.loadDescopeUiComponents(g);this.sdk.webauthn.helpers.isSupported()?yield e(this,z,"m",de).call(this,m,d):A(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),E(m,h,h.componentsConfig,this.formConfig,this.errorTransformer,this.loggerWrapper);const{geo:f}=yield this.getExecutionContext();T(m,f);const b=()=>i(this,void 0,void 0,(function*(){var i,o;yield v;const n=this.contentRootElement;U(n,null===(i=null==h?void 0:h.totp)||void 0===i?void 0:i.image),L(n,null===(o=null==h?void 0:h.notp)||void 0===o?void 0:o.image),N(n,m,h.cssVars,this.loggerWrapper),n.replaceChildren(m);const r=!s.htmlFilename;setTimeout((()=>{e(this,z,"m",me).call(this),this.validateOnBlur&&C(n),$(n,h),e(this,z,"m",ce).call(this,{isFirstScreen:r,stepName:t.stepName}),O(n,this.autoFocus,r)})),e(this,z,"m",we).call(this,d);n.querySelector(`[${p}="polling"]`)&&d(c.polling,{}),u&&!s.openInNewTabUrl&&window.open(u,"_blank")}));l?e(this,z,"m",ye).call(this,b,l):b()}))}}Q=new WeakMap,X=new WeakMap,Y=new WeakMap,Z=new WeakMap,se=new WeakMap,oe=new WeakMap,ne=new WeakMap,re=new WeakMap,ae=new WeakMap,fe=new WeakMap,z=new WeakSet,ee=function(){document.hidden||setTimeout((()=>{this.flowState.update({deferredRedirect:!1})}),300)},te=function(){return i(this,void 0,void 0,(function*(){this.loggerWrapper.debug("Trying to restart the flow");const e=yield this.getComponentsVersion();this.reset();e===(yield this.getComponentsVersion())?(this.loggerWrapper.debug("Components version was not changed, restarting flow"),this.flowState.update({stepId:null,executionId:null})):this.loggerWrapper.error("Components version mismatch, please reload the page")}))},ie=function(t){return i(this,void 0,void 0,(function*(){var i;const o=Object.assign(Object.assign({},this.stepState.current),t),{next:n,stepName:r}=o,a=s(o,["next","stepName"]),l=Boolean(yield null===(i=this.onScreenUpdate)||void 0===i?void 0:i.call(this,r,S(a),n,this));if(l){this.loggerWrapper.debug("Rendering a custom screen"),this.contentRootElement.innerHTML="",e(this,z,"m",ce).call(this,{isFirstScreen:!this.stepState.current.htmlFilename,stepName:t.stepName}),this.stepState.unsubscribeAll();const i=this.stepState.subscribe((()=>{var e;this.stepState.unsubscribe(i),null===(e=this.stepState)||void 0===e||e.subscribe(this.onStepChange.bind(this))}))}e(this,se,"f").call(this,l)}))},le=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,X,"f"))||void 0===n||n.abort();const r=s.querySelector('*[autocomplete="webauthn"]');if(r&&(yield P())){const{options:s,transactionId:n}=(yield e(this,ae,"f").call(this))||{};s&&n&&(e(this,z,"m",le).call(this,r),t(this,X,new AbortController,"f"),this.sdk.webauthn.helpers.conditional(s,e(this,X,"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)})))}}))},ce=function({isFirstScreen:t,stepName:i}){t&&e(this,z,"m",Ie).call(this,"ready",{}),e(this,z,"m",Ie).call(this,"page-updated",{screenName:i}),e(this,z,"m",Ie).call(this,"screen-updated",{screenName:i})},he=function(){let e=!0;return Array.from(this.shadowRoot.querySelectorAll("*[name]")).reverse().forEach((t=>{var i,s;"slot"!==t.localName&&(null===(i=t.reportValidity)||void 0===i||i.call(t),e&&(e=null===(s=t.checkValidity)||void 0===s?void 0:s.call(t)))})),e},pe=function(){return i(this,void 0,void 0,(function*(){const e=Array.from(this.shadowRoot.querySelectorAll(`*[name]:not([${u}])`));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})),{})}))},ue=function(e){const t=this.nextRequestStatus.subscribe((({isLoading:i})=>{i?e.setAttribute("loading","true"):(this.nextRequestStatus.unsubscribe(t),e.removeAttribute("loading"))}))},ge=function(e={}){var t,i;const s=j(e,["externalId","email","phone"]),o=j(e,["newPassword","password"]);if(s&&o)try{if(!globalThis.PasswordCredential)return;const e=new globalThis.PasswordCredential({id:s,password:o});null===(i=null===(t=null===navigator||void 0===navigator?void 0:navigator.credentials)||void 0===t?void 0:t.store)||void 0===i||i.call(t,e)}catch(e){this.loggerWrapper.error("Could not store credentials",e.message)}},me=function(){W();this.contentRootElement.querySelectorAll('[external-input="true"]').forEach((t=>e(this,z,"m",ve).call(this,t)))},ve=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)}))},be=function(t){this.contentRootElement.querySelectorAll('descope-passcode[data-auto-submit="true"]').forEach((i=>{i.addEventListener("input",(()=>{var s;(null===(s=i.checkValidity)||void 0===s?void 0:s.call(i))&&e(this,fe,"f").call(this,i,t)}))}))},we=function(t){this.contentRootElement.querySelectorAll(`descope-button:not([${g}])`).forEach((i=>{i.onclick=()=>{e(this,fe,"f").call(this,i,t)}})),e(this,z,"m",be).call(this,t)},ye=function(e,t){this.contentRootElement.addEventListener("transitionend",(()=>{this.contentRootElement.classList.remove("fade-out"),e()}),{once:!0});const i=t===K.forward?"slide-forward":"slide-backward";Array.from(this.contentRootElement.getElementsByClassName("input-container")).forEach(((e,t)=>{e.style["transition-delay"]=40*t+"ms",e.classList.add(i)})),this.contentRootElement.classList.add("fade-out")},Ie=function(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t}))};export{Se as default};
|
|
2
2
|
//# sourceMappingURL=DescopeWc.js.map
|