@descope/web-component 3.68.0 → 3.69.1
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/realtime-conditions/evaluator.js +1 -1
- package/dist/cjs/helpers/realtime-conditions/evaluator.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/realtime-conditions/evaluator.js +1 -1
- package/dist/esm/helpers/realtime-conditions/evaluator.js.map +1 -1
- package/dist/esm/types.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +2 -2
- package/package.json +4 -4
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";function e(e){if("number"==typeof e&&Number.isFinite(e))return{value:e,ok:!0};if("boolean"==typeof e)return{value:e?1:0,ok:!0};if("string"==typeof e){if(""===e.trim())return{value:0,ok:!1};const t=Number(e);if(Number.isFinite(t))return{value:t,ok:!0}}return{value:0,ok:!1}}function t(e){return null==e?"":"string"==typeof e?e:"boolean"==typeof e?e?"true":"false":"number"==typeof e?Number.isFinite(e)?String(e):"":String(e)}function n(e){if("boolean"==typeof e)return{value:e,ok:!0};if("string"==typeof e){if("true"===e)return{value:!0,ok:!0};if("false"===e)return{value:!1,ok:!0}}return"number"==typeof e?{value:0!==e,ok:!0}:{value:!1,ok:!1}}function r(e){return Array.isArray(e)?e:"string"==typeof e?e.split(","):null}function o(e){return null==e||("string"==typeof e?""===e:Array.isArray(e)?0===e.length:"object"==typeof e&&0===Object.keys(e).length)}const u=new Map;const l={equal:(e,n)=>e===n||t(e)===t(n),"not-equal":(e,n)=>e!==n&&t(e)!==t(n),contains:(e,n)=>Array.isArray(e)?e.includes(n):"string"==typeof e&&e.includes(t(n)),"greater-than":(t,n)=>{const r=e(t),o=e(n);return r.ok&&o.ok&&r.value>o.value},"greater-than-or-equal":(t,n)=>{const r=e(t),o=e(n);return r.ok&&o.ok&&r.value>=o.value},"less-than":(t,n)=>{const r=e(t),o=e(n);return r.ok&&o.ok&&r.value<o.value},"less-than-or-equal":(t,n)=>{const r=e(t),o=e(n);return r.ok&&o.ok&&r.value<=o.value},empty:e=>o(e),"not-empty":e=>!o(e),"is-true":e=>{const t=n(e);return t.ok&&t.value},"is-false":e=>{const t=n(e);return t.ok&&!t.value},in:(e,t)=>{const n=r(t);return null!==n&&n.includes(e)},"not-in":(e,t)=>{const n=r(t);return null!==n&&!n.includes(e)},matches:(e,n)=>{if("string"!=typeof e)return!1;const r=function(e){var t;if(u.has(e))return null!==(t=u.get(e))&&void 0!==t?t:null;let n;try{n=new RegExp(e)}catch(e){n=null}return u.set(e,n),n}(t(n));return null!==r&&r.test(e)}};function i(e,t){var n;if(e)return"form"===e.kind&&e.form?t[e.form]:"list"===e.kind?(null!==(n=e.items)&&void 0!==n?n:[]).map((e=>i(e,t))):e.value}function a(e,t){const n=l[e.operator];if(!n)return!1;return n(i(e.target,t),i(e.predicate,t))}function s(e,t){var n;return(null!==(n=e.rules)&&void 0!==n?n:[]).some((e=>function(e,t){var n;const r=null!==(n=e.atomicConditions)&&void 0!==n?n:[];return!!r.length&&(e.logicalOr?r.some((e=>a(e,t))):r.every((e=>a(e,t))))}(e,t)))}exports.collectReferencedFormKeys=function(e){const t=new Set,n=e=>{var r;e&&("form"===e.kind&&e.form?t.add(e.form):"list"===e.kind&&(null!==(r=e.items)&&void 0!==r?r:[]).forEach(n))};return(null!=e?e:[]).forEach((e=>{var t;return(null!==(t=e.rules)&&void 0!==t?t:[]).forEach((e=>{var t;return(null!==(t=e.atomicConditions)&&void 0!==t?t:[]).forEach((e=>{n(e.target),n(e.predicate)}))}))})),t},exports.collectTouchedComponentIds=function(e){const t=new Set;return(null!=e?e:[]).forEach((e=>{var n;(null!==(n=e.componentIds)&&void 0!==n?n:[]).forEach((e=>t.add(e)))})),t},exports.evaluateAll=function(e,t){const n={};return(null!=e?e:[]).forEach((e=>{var r;s(e,t)&&(null!==(r=e.componentIds)&&void 0!==r?r:[]).forEach((t=>{n[t]=e.action}))})),n},exports.evaluateCondition=s,exports.isEmpty=o,exports.toBoolean=n,exports.toFloat=e,exports.toSlice=r,exports.toString=t;
|
|
1
|
+
"use strict";function e(e){if("number"==typeof e&&Number.isFinite(e))return{value:e,ok:!0};if("boolean"==typeof e)return{value:e?1:0,ok:!0};if("string"==typeof e){if(""===e.trim())return{value:0,ok:!1};const t=Number(e);if(Number.isFinite(t))return{value:t,ok:!0}}return{value:0,ok:!1}}function t(e){return null==e?"":"string"==typeof e?e:"boolean"==typeof e?e?"true":"false":"number"==typeof e?Number.isFinite(e)?String(e):"":String(e)}function n(e){if("boolean"==typeof e)return{value:e,ok:!0};if("string"==typeof e){if("true"===e)return{value:!0,ok:!0};if("false"===e)return{value:!1,ok:!0}}return"number"==typeof e?{value:0!==e,ok:!0}:{value:!1,ok:!1}}function r(e){return Array.isArray(e)?e:"string"==typeof e?e.split(","):null}function o(e){return null==e||("string"==typeof e?""===e:Array.isArray(e)?0===e.length:"object"==typeof e&&0===Object.keys(e).length)}const u=new Map;const l={equal:(e,n)=>e===n||t(e)===t(n),"not-equal":(e,n)=>e!==n&&t(e)!==t(n),contains:(e,n)=>Array.isArray(e)?e.includes(n):"string"==typeof e&&e.includes(t(n)),"doesnt-contains":(e,n)=>Array.isArray(e)?!e.includes(n):"string"==typeof e&&!e.includes(t(n)),"greater-than":(t,n)=>{const r=e(t),o=e(n);return r.ok&&o.ok&&r.value>o.value},"greater-than-or-equal":(t,n)=>{const r=e(t),o=e(n);return r.ok&&o.ok&&r.value>=o.value},"less-than":(t,n)=>{const r=e(t),o=e(n);return r.ok&&o.ok&&r.value<o.value},"less-than-or-equal":(t,n)=>{const r=e(t),o=e(n);return r.ok&&o.ok&&r.value<=o.value},empty:e=>o(e),"not-empty":e=>!o(e),"is-true":e=>{const t=n(e);return t.ok&&t.value},"is-false":e=>{const t=n(e);return t.ok&&!t.value},in:(e,t)=>{const n=r(t);return null!==n&&n.includes(e)},"not-in":(e,t)=>{const n=r(t);return null!==n&&!n.includes(e)},matches:(e,n)=>{if("string"!=typeof e)return!1;const r=function(e){var t;if(u.has(e))return null!==(t=u.get(e))&&void 0!==t?t:null;let n;try{n=new RegExp(e)}catch(e){n=null}return u.set(e,n),n}(t(n));return null!==r&&r.test(e)}};function i(e,t){var n;if(e)return"form"===e.kind&&e.form?t[e.form]:"list"===e.kind?(null!==(n=e.items)&&void 0!==n?n:[]).map((e=>i(e,t))):e.value}function a(e,t){const n=l[e.operator];if(!n)return!1;return n(i(e.target,t),i(e.predicate,t))}function s(e,t){var n;return(null!==(n=e.rules)&&void 0!==n?n:[]).some((e=>function(e,t){var n;const r=null!==(n=e.atomicConditions)&&void 0!==n?n:[];return!!r.length&&(e.logicalOr?r.some((e=>a(e,t))):r.every((e=>a(e,t))))}(e,t)))}exports.collectReferencedFormKeys=function(e){const t=new Set,n=e=>{var r;e&&("form"===e.kind&&e.form?t.add(e.form):"list"===e.kind&&(null!==(r=e.items)&&void 0!==r?r:[]).forEach(n))};return(null!=e?e:[]).forEach((e=>{var t;return(null!==(t=e.rules)&&void 0!==t?t:[]).forEach((e=>{var t;return(null!==(t=e.atomicConditions)&&void 0!==t?t:[]).forEach((e=>{n(e.target),n(e.predicate)}))}))})),t},exports.collectTouchedComponentIds=function(e){const t=new Set;return(null!=e?e:[]).forEach((e=>{var n;(null!==(n=e.componentIds)&&void 0!==n?n:[]).forEach((e=>t.add(e)))})),t},exports.evaluateAll=function(e,t){const n={};return(null!=e?e:[]).forEach((e=>{var r;s(e,t)&&(null!==(r=e.componentIds)&&void 0!==r?r:[]).forEach((t=>{n[t]=e.action}))})),n},exports.evaluateCondition=s,exports.isEmpty=o,exports.toBoolean=n,exports.toFloat=e,exports.toSlice=r,exports.toString=t;
|
|
2
2
|
//# sourceMappingURL=evaluator.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"evaluator.js","sources":["../../../../src/lib/helpers/realtime-conditions/evaluator.ts"],"sourcesContent":["import type {\n RealtimeAtomicCondition,\n RealtimeComponentsCondition,\n RealtimeOperand,\n RealtimeOperator,\n RealtimeRule,\n} from '../../types';\n\n/**\n * Snapshot of on-screen form values keyed by their full context key\n * (e.g. `form.phone`). The mixin maintains this snapshot as the user types.\n */\nexport type FormSnapshot = Record<string, unknown>;\n\n/* ------------------------------------------------------------------ */\n/* type-conversion helpers — mirror the Go cutils.AnyTo* semantics */\n/* ------------------------------------------------------------------ */\n\nexport function toFloat(v: unknown): { value: number; ok: boolean } {\n if (typeof v === 'number' && Number.isFinite(v)) {\n return { value: v, ok: true };\n }\n if (typeof v === 'boolean') {\n return { value: v ? 1 : 0, ok: true };\n }\n if (typeof v === 'string') {\n if (v.trim() === '') return { value: 0, ok: false };\n const n = Number(v);\n if (Number.isFinite(n)) return { value: n, ok: true };\n }\n return { value: 0, ok: false };\n}\n\nexport function toString(v: unknown): string {\n if (v === null || v === undefined) return '';\n if (typeof v === 'string') return v;\n if (typeof v === 'boolean') return v ? 'true' : 'false';\n if (typeof v === 'number') return Number.isFinite(v) ? String(v) : '';\n return String(v);\n}\n\nexport function toBoolean(v: unknown): { value: boolean; ok: boolean } {\n if (typeof v === 'boolean') return { value: v, ok: true };\n if (typeof v === 'string') {\n if (v === 'true') return { value: true, ok: true };\n if (v === 'false') return { value: false, ok: true };\n }\n if (typeof v === 'number') {\n return { value: v !== 0, ok: true };\n }\n return { value: false, ok: false };\n}\n\nexport function toSlice(v: unknown): unknown[] | null {\n if (Array.isArray(v)) return v;\n if (typeof v === 'string') return v.split(',');\n return null;\n}\n\nexport function isEmpty(v: unknown): boolean {\n if (v === null || v === undefined) return true;\n if (typeof v === 'string') return v === '';\n if (Array.isArray(v)) return v.length === 0;\n if (typeof v === 'object') return Object.keys(v as object).length === 0;\n return false;\n}\n\n/* ------------------------------------------------------------------ */\n/* operator implementations */\n/* ------------------------------------------------------------------ */\n\ntype OperatorFn = (target: unknown, predicate: unknown) => boolean;\n\n// Compiled regex cache for `matches`. Patterns come from the server (trusted),\n// and the same condition is re-evaluated on every input event, so caching by\n// pattern source avoids redundant RegExp construction on each keystroke.\nconst matchesRegexCache = new Map<string, RegExp | null>();\nfunction compileMatchesPattern(source: string): RegExp | null {\n if (matchesRegexCache.has(source)) {\n return matchesRegexCache.get(source) ?? null;\n }\n let compiled: RegExp | null;\n try {\n compiled = new RegExp(source);\n } catch {\n compiled = null;\n }\n matchesRegexCache.set(source, compiled);\n return compiled;\n}\n\nconst operators: Record<RealtimeOperator, OperatorFn> = {\n equal: (target, predicate) =>\n target === predicate || toString(target) === toString(predicate),\n 'not-equal': (target, predicate) =>\n target !== predicate && toString(target) !== toString(predicate),\n contains: (target, predicate) => {\n if (Array.isArray(target)) return target.includes(predicate);\n if (typeof target === 'string') return target.includes(toString(predicate));\n return false;\n },\n 'greater-than': (target, predicate) => {\n const targetNum = toFloat(target);\n const predicateNum = toFloat(predicate);\n return (\n targetNum.ok && predicateNum.ok && targetNum.value > predicateNum.value\n );\n },\n 'greater-than-or-equal': (target, predicate) => {\n const targetNum = toFloat(target);\n const predicateNum = toFloat(predicate);\n return (\n targetNum.ok && predicateNum.ok && targetNum.value >= predicateNum.value\n );\n },\n 'less-than': (target, predicate) => {\n const targetNum = toFloat(target);\n const predicateNum = toFloat(predicate);\n return (\n targetNum.ok && predicateNum.ok && targetNum.value < predicateNum.value\n );\n },\n 'less-than-or-equal': (target, predicate) => {\n const targetNum = toFloat(target);\n const predicateNum = toFloat(predicate);\n return (\n targetNum.ok && predicateNum.ok && targetNum.value <= predicateNum.value\n );\n },\n empty: (target) => isEmpty(target),\n 'not-empty': (target) => !isEmpty(target),\n 'is-true': (target) => {\n const asBool = toBoolean(target);\n return asBool.ok && asBool.value;\n },\n 'is-false': (target) => {\n const asBool = toBoolean(target);\n return asBool.ok && !asBool.value;\n },\n in: (target, predicate) => {\n const slice = toSlice(predicate);\n return slice !== null && slice.includes(target);\n },\n // Mirrors `in`: bad input → false, not true.\n 'not-in': (target, predicate) => {\n const slice = toSlice(predicate);\n return slice !== null && !slice.includes(target);\n },\n matches: (target, predicate) => {\n if (typeof target !== 'string') return false;\n const regex = compileMatchesPattern(toString(predicate));\n return regex !== null && regex.test(target);\n },\n};\n\n/* ------------------------------------------------------------------ */\n/* atomic & rule evaluation */\n/* ------------------------------------------------------------------ */\n\nfunction resolveOperand(\n operand: RealtimeOperand | undefined,\n snapshot: FormSnapshot,\n): unknown {\n if (!operand) return undefined;\n if (operand.kind === 'form' && operand.form) {\n return snapshot[operand.form];\n }\n if (operand.kind === 'list') {\n // Each item may itself be a form placeholder or a pre-resolved literal,\n // so resolve recursively. The server emits this shape when an\n // `in` / `not-in` / `contains` predicate is an array containing a\n // `{{form.X}}` reference to an on-screen key.\n return (operand.items ?? []).map((item) => resolveOperand(item, snapshot));\n }\n return operand.value;\n}\n\nfunction evaluateAtomic(\n atom: RealtimeAtomicCondition,\n snapshot: FormSnapshot,\n): boolean {\n const fn = operators[atom.operator as RealtimeOperator];\n if (!fn) return false;\n\n const target = resolveOperand(atom.target, snapshot);\n const predicate = resolveOperand(atom.predicate, snapshot);\n return fn(target, predicate);\n}\n\nfunction evaluateRule(rule: RealtimeRule, snapshot: FormSnapshot): boolean {\n const atomics = rule.atomicConditions ?? [];\n if (!atomics.length) return false;\n if (rule.logicalOr) {\n return atomics.some((a) => evaluateAtomic(a, snapshot));\n }\n return atomics.every((a) => evaluateAtomic(a, snapshot));\n}\n\n/** Evaluates a single condition group: returns true if any of its rules fire. */\nexport function evaluateCondition(\n condition: RealtimeComponentsCondition,\n snapshot: FormSnapshot,\n): boolean {\n return (condition.rules ?? []).some((r) => evaluateRule(r, snapshot));\n}\n\n/**\n * Evaluates all condition groups and returns, for each targeted component, the\n * action of the LAST firing group. Components where no group fires are absent\n * from the result.\n *\n * \"Last match wins\" mirrors the BE evaluator: when two groups target the same\n * component with different actions, the BE assigns\n * `componentsState[id] = cc.Then.Action` unconditionally in declaration order,\n * so a later CC's action overwrites an earlier one. The SDK matches this so\n * the two layers can't disagree on which action a component ends up with.\n */\nexport function evaluateAll(\n conditions: RealtimeComponentsCondition[] | undefined,\n snapshot: FormSnapshot,\n): Record<string, string> {\n const result: Record<string, string> = {};\n (conditions ?? []).forEach((c) => {\n if (!evaluateCondition(c, snapshot)) return;\n (c.componentIds ?? []).forEach((id) => {\n result[id] = c.action;\n });\n });\n return result;\n}\n\n/**\n * Returns the set of component IDs targeted by any condition group. The\n * applier uses this to know which components belong to the realtime layer.\n */\nexport function collectTouchedComponentIds(\n conditions: RealtimeComponentsCondition[] | undefined,\n): Set<string> {\n const out = new Set<string>();\n (conditions ?? []).forEach((c) => {\n (c.componentIds ?? []).forEach((id) => out.add(id));\n });\n return out;\n}\n\n/**\n * Returns every form key (e.g. `form.phone`) referenced by any operand in\n * any rule. The mixin uses this on mount to know which DOM inputs to read so\n * it can seed the snapshot from rendered defaults that the server can't see.\n */\nexport function collectReferencedFormKeys(\n conditions: RealtimeComponentsCondition[] | undefined,\n): Set<string> {\n const out = new Set<string>();\n const walkOperand = (operand: RealtimeOperand | undefined) => {\n if (!operand) return;\n if (operand.kind === 'form' && operand.form) {\n out.add(operand.form);\n } else if (operand.kind === 'list') {\n (operand.items ?? []).forEach(walkOperand);\n }\n };\n (conditions ?? []).forEach((c) =>\n (c.rules ?? []).forEach((r) =>\n (r.atomicConditions ?? []).forEach((a) => {\n walkOperand(a.target);\n walkOperand(a.predicate);\n }),\n ),\n );\n return out;\n}\n"],"names":["toFloat","v","Number","isFinite","value","ok","trim","n","toString","String","toBoolean","toSlice","Array","isArray","split","isEmpty","length","Object","keys","matchesRegexCache","Map","operators","equal","target","predicate","contains","includes","targetNum","predicateNum","empty","asBool","in","slice","matches","regex","source","has","_a","get","compiled","RegExp","_b","set","compileMatchesPattern","test","resolveOperand","operand","snapshot","kind","form","items","map","item","evaluateAtomic","atom","fn","operator","evaluateCondition","condition","rules","some","r","rule","atomics","atomicConditions","logicalOr","a","every","evaluateRule","conditions","out","Set","walkOperand","add","forEach","c","componentIds","id","result","action"],"mappings":"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"}
|
|
1
|
+
{"version":3,"file":"evaluator.js","sources":["../../../../src/lib/helpers/realtime-conditions/evaluator.ts"],"sourcesContent":["import type {\n RealtimeAtomicCondition,\n RealtimeComponentsCondition,\n RealtimeOperand,\n RealtimeOperator,\n RealtimeRule,\n} from '../../types';\n\n/**\n * Snapshot of on-screen form values keyed by their full context key\n * (e.g. `form.phone`). The mixin maintains this snapshot as the user types.\n */\nexport type FormSnapshot = Record<string, unknown>;\n\n/* ------------------------------------------------------------------ */\n/* type-conversion helpers — mirror the Go cutils.AnyTo* semantics */\n/* ------------------------------------------------------------------ */\n\nexport function toFloat(v: unknown): { value: number; ok: boolean } {\n if (typeof v === 'number' && Number.isFinite(v)) {\n return { value: v, ok: true };\n }\n if (typeof v === 'boolean') {\n return { value: v ? 1 : 0, ok: true };\n }\n if (typeof v === 'string') {\n if (v.trim() === '') return { value: 0, ok: false };\n const n = Number(v);\n if (Number.isFinite(n)) return { value: n, ok: true };\n }\n return { value: 0, ok: false };\n}\n\nexport function toString(v: unknown): string {\n if (v === null || v === undefined) return '';\n if (typeof v === 'string') return v;\n if (typeof v === 'boolean') return v ? 'true' : 'false';\n if (typeof v === 'number') return Number.isFinite(v) ? String(v) : '';\n return String(v);\n}\n\nexport function toBoolean(v: unknown): { value: boolean; ok: boolean } {\n if (typeof v === 'boolean') return { value: v, ok: true };\n if (typeof v === 'string') {\n if (v === 'true') return { value: true, ok: true };\n if (v === 'false') return { value: false, ok: true };\n }\n if (typeof v === 'number') {\n return { value: v !== 0, ok: true };\n }\n return { value: false, ok: false };\n}\n\nexport function toSlice(v: unknown): unknown[] | null {\n if (Array.isArray(v)) return v;\n if (typeof v === 'string') return v.split(',');\n return null;\n}\n\nexport function isEmpty(v: unknown): boolean {\n if (v === null || v === undefined) return true;\n if (typeof v === 'string') return v === '';\n if (Array.isArray(v)) return v.length === 0;\n if (typeof v === 'object') return Object.keys(v as object).length === 0;\n return false;\n}\n\n/* ------------------------------------------------------------------ */\n/* operator implementations */\n/* ------------------------------------------------------------------ */\n\ntype OperatorFn = (target: unknown, predicate: unknown) => boolean;\n\n// Compiled regex cache for `matches`. Patterns come from the server (trusted),\n// and the same condition is re-evaluated on every input event, so caching by\n// pattern source avoids redundant RegExp construction on each keystroke.\nconst matchesRegexCache = new Map<string, RegExp | null>();\nfunction compileMatchesPattern(source: string): RegExp | null {\n if (matchesRegexCache.has(source)) {\n return matchesRegexCache.get(source) ?? null;\n }\n let compiled: RegExp | null;\n try {\n compiled = new RegExp(source);\n } catch {\n compiled = null;\n }\n matchesRegexCache.set(source, compiled);\n return compiled;\n}\n\nconst operators: Record<RealtimeOperator, OperatorFn> = {\n equal: (target, predicate) =>\n target === predicate || toString(target) === toString(predicate),\n 'not-equal': (target, predicate) =>\n target !== predicate && toString(target) !== toString(predicate),\n contains: (target, predicate) => {\n if (Array.isArray(target)) return target.includes(predicate);\n if (typeof target === 'string') return target.includes(toString(predicate));\n return false;\n },\n // Mirrors `contains`: bad input → false, not true.\n 'doesnt-contains': (target, predicate) => {\n if (Array.isArray(target)) return !target.includes(predicate);\n if (typeof target === 'string')\n return !target.includes(toString(predicate));\n return false;\n },\n 'greater-than': (target, predicate) => {\n const targetNum = toFloat(target);\n const predicateNum = toFloat(predicate);\n return (\n targetNum.ok && predicateNum.ok && targetNum.value > predicateNum.value\n );\n },\n 'greater-than-or-equal': (target, predicate) => {\n const targetNum = toFloat(target);\n const predicateNum = toFloat(predicate);\n return (\n targetNum.ok && predicateNum.ok && targetNum.value >= predicateNum.value\n );\n },\n 'less-than': (target, predicate) => {\n const targetNum = toFloat(target);\n const predicateNum = toFloat(predicate);\n return (\n targetNum.ok && predicateNum.ok && targetNum.value < predicateNum.value\n );\n },\n 'less-than-or-equal': (target, predicate) => {\n const targetNum = toFloat(target);\n const predicateNum = toFloat(predicate);\n return (\n targetNum.ok && predicateNum.ok && targetNum.value <= predicateNum.value\n );\n },\n empty: (target) => isEmpty(target),\n 'not-empty': (target) => !isEmpty(target),\n 'is-true': (target) => {\n const asBool = toBoolean(target);\n return asBool.ok && asBool.value;\n },\n 'is-false': (target) => {\n const asBool = toBoolean(target);\n return asBool.ok && !asBool.value;\n },\n in: (target, predicate) => {\n const slice = toSlice(predicate);\n return slice !== null && slice.includes(target);\n },\n // Mirrors `in`: bad input → false, not true.\n 'not-in': (target, predicate) => {\n const slice = toSlice(predicate);\n return slice !== null && !slice.includes(target);\n },\n matches: (target, predicate) => {\n if (typeof target !== 'string') return false;\n const regex = compileMatchesPattern(toString(predicate));\n return regex !== null && regex.test(target);\n },\n};\n\n/* ------------------------------------------------------------------ */\n/* atomic & rule evaluation */\n/* ------------------------------------------------------------------ */\n\nfunction resolveOperand(\n operand: RealtimeOperand | undefined,\n snapshot: FormSnapshot,\n): unknown {\n if (!operand) return undefined;\n if (operand.kind === 'form' && operand.form) {\n return snapshot[operand.form];\n }\n if (operand.kind === 'list') {\n // Each item may itself be a form placeholder or a pre-resolved literal,\n // so resolve recursively. The server emits this shape when an\n // `in` / `not-in` / `contains` predicate is an array containing a\n // `{{form.X}}` reference to an on-screen key.\n return (operand.items ?? []).map((item) => resolveOperand(item, snapshot));\n }\n return operand.value;\n}\n\nfunction evaluateAtomic(\n atom: RealtimeAtomicCondition,\n snapshot: FormSnapshot,\n): boolean {\n const fn = operators[atom.operator as RealtimeOperator];\n if (!fn) return false;\n\n const target = resolveOperand(atom.target, snapshot);\n const predicate = resolveOperand(atom.predicate, snapshot);\n return fn(target, predicate);\n}\n\nfunction evaluateRule(rule: RealtimeRule, snapshot: FormSnapshot): boolean {\n const atomics = rule.atomicConditions ?? [];\n if (!atomics.length) return false;\n if (rule.logicalOr) {\n return atomics.some((a) => evaluateAtomic(a, snapshot));\n }\n return atomics.every((a) => evaluateAtomic(a, snapshot));\n}\n\n/** Evaluates a single condition group: returns true if any of its rules fire. */\nexport function evaluateCondition(\n condition: RealtimeComponentsCondition,\n snapshot: FormSnapshot,\n): boolean {\n return (condition.rules ?? []).some((r) => evaluateRule(r, snapshot));\n}\n\n/**\n * Evaluates all condition groups and returns, for each targeted component, the\n * action of the LAST firing group. Components where no group fires are absent\n * from the result.\n *\n * \"Last match wins\" mirrors the BE evaluator: when two groups target the same\n * component with different actions, the BE assigns\n * `componentsState[id] = cc.Then.Action` unconditionally in declaration order,\n * so a later CC's action overwrites an earlier one. The SDK matches this so\n * the two layers can't disagree on which action a component ends up with.\n */\nexport function evaluateAll(\n conditions: RealtimeComponentsCondition[] | undefined,\n snapshot: FormSnapshot,\n): Record<string, string> {\n const result: Record<string, string> = {};\n (conditions ?? []).forEach((c) => {\n if (!evaluateCondition(c, snapshot)) return;\n (c.componentIds ?? []).forEach((id) => {\n result[id] = c.action;\n });\n });\n return result;\n}\n\n/**\n * Returns the set of component IDs targeted by any condition group. The\n * applier uses this to know which components belong to the realtime layer.\n */\nexport function collectTouchedComponentIds(\n conditions: RealtimeComponentsCondition[] | undefined,\n): Set<string> {\n const out = new Set<string>();\n (conditions ?? []).forEach((c) => {\n (c.componentIds ?? []).forEach((id) => out.add(id));\n });\n return out;\n}\n\n/**\n * Returns every form key (e.g. `form.phone`) referenced by any operand in\n * any rule. The mixin uses this on mount to know which DOM inputs to read so\n * it can seed the snapshot from rendered defaults that the server can't see.\n */\nexport function collectReferencedFormKeys(\n conditions: RealtimeComponentsCondition[] | undefined,\n): Set<string> {\n const out = new Set<string>();\n const walkOperand = (operand: RealtimeOperand | undefined) => {\n if (!operand) return;\n if (operand.kind === 'form' && operand.form) {\n out.add(operand.form);\n } else if (operand.kind === 'list') {\n (operand.items ?? []).forEach(walkOperand);\n }\n };\n (conditions ?? []).forEach((c) =>\n (c.rules ?? []).forEach((r) =>\n (r.atomicConditions ?? []).forEach((a) => {\n walkOperand(a.target);\n walkOperand(a.predicate);\n }),\n ),\n );\n return out;\n}\n"],"names":["toFloat","v","Number","isFinite","value","ok","trim","n","toString","String","toBoolean","toSlice","Array","isArray","split","isEmpty","length","Object","keys","matchesRegexCache","Map","operators","equal","target","predicate","contains","includes","targetNum","predicateNum","empty","asBool","in","slice","matches","regex","source","has","_a","get","compiled","RegExp","_b","set","compileMatchesPattern","test","resolveOperand","operand","snapshot","kind","form","items","map","item","evaluateAtomic","atom","fn","operator","evaluateCondition","condition","rules","some","r","rule","atomics","atomicConditions","logicalOr","a","every","evaluateRule","conditions","out","Set","walkOperand","add","forEach","c","componentIds","id","result","action"],"mappings":"aAkBM,SAAUA,EAAQC,GACtB,GAAiB,iBAANA,GAAkBC,OAAOC,SAASF,GAC3C,MAAO,CAAEG,MAAOH,EAAGI,IAAI,GAEzB,GAAiB,kBAANJ,EACT,MAAO,CAAEG,MAAOH,EAAI,EAAI,EAAGI,IAAI,GAEjC,GAAiB,iBAANJ,EAAgB,CACzB,GAAiB,KAAbA,EAAEK,OAAe,MAAO,CAAEF,MAAO,EAAGC,IAAI,GAC5C,MAAME,EAAIL,OAAOD,GACjB,GAAIC,OAAOC,SAASI,GAAI,MAAO,CAAEH,MAAOG,EAAGF,IAAI,EAChD,CACD,MAAO,CAAED,MAAO,EAAGC,IAAI,EACzB,CAEM,SAAUG,EAASP,GACvB,OAAIA,QAAsC,GACzB,iBAANA,EAAuBA,EACjB,kBAANA,EAAwBA,EAAI,OAAS,QAC/B,iBAANA,EAAuBC,OAAOC,SAASF,GAAKQ,OAAOR,GAAK,GAC5DQ,OAAOR,EAChB,CAEM,SAAUS,EAAUT,GACxB,GAAiB,kBAANA,EAAiB,MAAO,CAAEG,MAAOH,EAAGI,IAAI,GACnD,GAAiB,iBAANJ,EAAgB,CACzB,GAAU,SAANA,EAAc,MAAO,CAAEG,OAAO,EAAMC,IAAI,GAC5C,GAAU,UAANJ,EAAe,MAAO,CAAEG,OAAO,EAAOC,IAAI,EAC/C,CACD,MAAiB,iBAANJ,EACF,CAAEG,MAAa,IAANH,EAASI,IAAI,GAExB,CAAED,OAAO,EAAOC,IAAI,EAC7B,CAEM,SAAUM,EAAQV,GACtB,OAAIW,MAAMC,QAAQZ,GAAWA,EACZ,iBAANA,EAAuBA,EAAEa,MAAM,KACnC,IACT,CAEM,SAAUC,EAAQd,GACtB,OAAIA,UACa,iBAANA,EAA6B,KAANA,EAC9BW,MAAMC,QAAQZ,GAAwB,IAAbA,EAAEe,OACd,iBAANf,GAA2D,IAApCgB,OAAOC,KAAKjB,GAAae,OAE7D,CAWA,MAAMG,EAAoB,IAAIC,IAe9B,MAAMC,EAAkD,CACtDC,MAAO,CAACC,EAAQC,IACdD,IAAWC,GAAahB,EAASe,KAAYf,EAASgB,GACxD,YAAa,CAACD,EAAQC,IACpBD,IAAWC,GAAahB,EAASe,KAAYf,EAASgB,GACxDC,SAAU,CAACF,EAAQC,IACbZ,MAAMC,QAAQU,GAAgBA,EAAOG,SAASF,GAC5B,iBAAXD,GAA4BA,EAAOG,SAASlB,EAASgB,IAIlE,kBAAmB,CAACD,EAAQC,IACtBZ,MAAMC,QAAQU,IAAiBA,EAAOG,SAASF,GAC7B,iBAAXD,IACDA,EAAOG,SAASlB,EAASgB,IAGrC,eAAgB,CAACD,EAAQC,KACvB,MAAMG,EAAY3B,EAAQuB,GACpBK,EAAe5B,EAAQwB,GAC7B,OACEG,EAAUtB,IAAMuB,EAAavB,IAAMsB,EAAUvB,MAAQwB,EAAaxB,KAClE,EAEJ,wBAAyB,CAACmB,EAAQC,KAChC,MAAMG,EAAY3B,EAAQuB,GACpBK,EAAe5B,EAAQwB,GAC7B,OACEG,EAAUtB,IAAMuB,EAAavB,IAAMsB,EAAUvB,OAASwB,EAAaxB,KACnE,EAEJ,YAAa,CAACmB,EAAQC,KACpB,MAAMG,EAAY3B,EAAQuB,GACpBK,EAAe5B,EAAQwB,GAC7B,OACEG,EAAUtB,IAAMuB,EAAavB,IAAMsB,EAAUvB,MAAQwB,EAAaxB,KAClE,EAEJ,qBAAsB,CAACmB,EAAQC,KAC7B,MAAMG,EAAY3B,EAAQuB,GACpBK,EAAe5B,EAAQwB,GAC7B,OACEG,EAAUtB,IAAMuB,EAAavB,IAAMsB,EAAUvB,OAASwB,EAAaxB,KACnE,EAEJyB,MAAQN,GAAWR,EAAQQ,GAC3B,YAAcA,IAAYR,EAAQQ,GAClC,UAAYA,IACV,MAAMO,EAASpB,EAAUa,GACzB,OAAOO,EAAOzB,IAAMyB,EAAO1B,KAAK,EAElC,WAAamB,IACX,MAAMO,EAASpB,EAAUa,GACzB,OAAOO,EAAOzB,KAAOyB,EAAO1B,KAAK,EAEnC2B,GAAI,CAACR,EAAQC,KACX,MAAMQ,EAAQrB,EAAQa,GACtB,OAAiB,OAAVQ,GAAkBA,EAAMN,SAASH,EAAO,EAGjD,SAAU,CAACA,EAAQC,KACjB,MAAMQ,EAAQrB,EAAQa,GACtB,OAAiB,OAAVQ,IAAmBA,EAAMN,SAASH,EAAO,EAElDU,QAAS,CAACV,EAAQC,KAChB,GAAsB,iBAAXD,EAAqB,OAAO,EACvC,MAAMW,EAhFV,SAA+BC,SAC7B,GAAIhB,EAAkBiB,IAAID,GACxB,OAAwC,QAAjCE,EAAAlB,EAAkBmB,IAAIH,UAAW,IAAAE,EAAAA,EAAA,KAE1C,IAAIE,EACJ,IACEA,EAAW,IAAIC,OAAOL,EACvB,CAAC,MAAAM,GACAF,EAAW,IACZ,CAED,OADApB,EAAkBuB,IAAIP,EAAQI,GACvBA,CACT,CAoEkBI,CAAsBnC,EAASgB,IAC7C,OAAiB,OAAVU,GAAkBA,EAAMU,KAAKrB,EAAO,GAQ/C,SAASsB,EACPC,EACAC,SAEA,GAAKD,EACL,MAAqB,SAAjBA,EAAQE,MAAmBF,EAAQG,KAC9BF,EAASD,EAAQG,MAEL,SAAjBH,EAAQE,MAKe,UAAjBF,EAAQI,aAAS,IAAAb,EAAAA,EAAA,IAAIc,KAAKC,GAASP,EAAeO,EAAML,KAE3DD,EAAQ1C,KACjB,CAEA,SAASiD,EACPC,EACAP,GAEA,MAAMQ,EAAKlC,EAAUiC,EAAKE,UAC1B,IAAKD,EAAI,OAAO,EAIhB,OAAOA,EAFQV,EAAeS,EAAK/B,OAAQwB,GACzBF,EAAeS,EAAK9B,UAAWuB,GAEnD,CAYgB,SAAAU,EACdC,EACAX,SAEA,OAA2B,UAAnBW,EAAUC,aAAS,IAAAtB,EAAAA,EAAA,IAAIuB,MAAMC,GAdvC,SAAsBC,EAAoBf,SACxC,MAAMgB,EAA+B,QAArB1B,EAAAyB,EAAKE,wBAAgB,IAAA3B,EAAAA,EAAI,GACzC,QAAK0B,EAAQ/C,SACT8C,EAAKG,UACAF,EAAQH,MAAMM,GAAMb,EAAea,EAAGnB,KAExCgB,EAAQI,OAAOD,GAAMb,EAAea,EAAGnB,KAChD,CAO6CqB,CAAaP,EAAGd,IAC7D,mCA8CM,SACJsB,GAEA,MAAMC,EAAM,IAAIC,IACVC,EAAe1B,UACdA,IACgB,SAAjBA,EAAQE,MAAmBF,EAAQG,KACrCqB,EAAIG,IAAI3B,EAAQG,MACU,SAAjBH,EAAQE,OACC,QAAjBX,EAAAS,EAAQI,aAAS,IAAAb,EAAAA,EAAA,IAAIqC,QAAQF,GAC/B,EAUH,OARCH,QAAAA,EAAc,IAAIK,SAASC,UAC1B,OAAY,QAAXtC,EAAAsC,EAAEhB,aAAS,IAAAtB,EAAAA,EAAA,IAAIqC,SAASb,UACvB,OAAuB,QAAtBxB,EAAAwB,EAAEG,wBAAoB,IAAA3B,EAAAA,EAAA,IAAIqC,SAASR,IAClCM,EAAYN,EAAE3C,QACdiD,EAAYN,EAAE1C,UAAU,GACxB,GACH,IAEI8C,CACT,qCApCM,SACJD,GAEA,MAAMC,EAAM,IAAIC,IAIhB,OAHCF,QAAAA,EAAc,IAAIK,SAASC,mBACzBtC,EAAAsC,EAAEC,4BAAgB,IAAIF,SAASG,GAAOP,EAAIG,IAAII,IAAI,IAE9CP,CACT,sBA1BgB,SACdD,EACAtB,GAEA,MAAM+B,EAAiC,CAAA,EAOvC,OANCT,QAAAA,EAAc,IAAIK,SAASC,UACrBlB,EAAkBkB,EAAG5B,KACP,QAAlBV,EAAAsC,EAAEC,oBAAgB,IAAAvC,EAAAA,EAAA,IAAIqC,SAASG,IAC9BC,EAAOD,GAAMF,EAAEI,MAAM,GACrB,IAEGD,CACT"}
|
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 type { JWTResponse } from '@descope/web-js-sdk';\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 type LastAuthState = NonNullable<\n NextFnReturnPromiseValue['data']['lastAuth']\n> & {\n loginId?: string;\n name?: string;\n lastUsedPerScreen?: Record<string, string>;\n};\n\nexport type RealtimeOperandKind = 'value' | 'form' | 'list';\n\n// Operators the SDK is allowed to evaluate locally. The server's\n// clientSupportedRealtimeOperators must stay in sync — anything outside this\n// list is pre-evaluated server-side and shipped as a value operand.\n//\n// is-email / is-phone are intentionally absent: the server validates them\n// with dedicated libraries (contact.IsValid*); the client has no equivalent,\n// so the server keeps these CCs server-only.\nexport type RealtimeOperator =\n | 'equal'\n | 'not-equal'\n | 'contains'\n | 'greater-than'\n | 'greater-than-or-equal'\n | 'less-than'\n | 'less-than-or-equal'\n | 'empty'\n | 'not-empty'\n | 'is-true'\n | 'is-false'\n | 'in'\n | 'not-in'\n | 'matches';\n\nexport interface RealtimeOperand {\n kind: RealtimeOperandKind;\n // Form is the context key the client looks up from the live form snapshot\n // (e.g. \"form.phone\"). Set only when kind === 'form'.\n form?: string;\n // Items is the operand list when kind === 'list'. Each element is a nested\n // operand — either a form placeholder or a resolved literal. Used when the\n // server detects an `in` / `not-in` / `contains` predicate whose array\n // contains `{{form.X}}` references; the client resolves them at eval time.\n items?: RealtimeOperand[];\n // Pre-resolved literal. Set only when kind === 'value', and may legitimately\n // be false / 0 / \"\" — do not treat absence as \"no value\" without checking\n // kind first.\n value?: unknown;\n}\n\nexport interface RealtimeAtomicCondition {\n operator: RealtimeOperator;\n target?: RealtimeOperand;\n predicate?: RealtimeOperand;\n}\n\nexport interface RealtimeRule {\n logicalOr?: boolean;\n atomicConditions: RealtimeAtomicCondition[];\n}\n\nexport interface RealtimeComponentsCondition {\n id?: string;\n componentIds: string[];\n action: string;\n rules: RealtimeRule[];\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 // map of component IDs to their state — the FULL last-wins verdict over\n // all CCs (server-only + client-eligible) the BE evaluated at screen-init.\n // Used by `applyComponentsState` for the first DOM paint.\n componentsState?: Record<string, string>;\n // Subset of `componentsState` contributed by SERVER-ONLY CCs — those the\n // client cannot re-evaluate locally (operators on the server-only\n // allow-list like `is-email`, or rules referencing context the client\n // doesn't have). Parallels `componentsState` in structure but excludes\n // contributions from client-eligible CCs that also ship in\n // `realtimeComponentsConditions`.\n //\n // The realtime layer uses this as the fallback action to restore when a\n // realtime CC stops firing on a touched component — without it the SDK\n // can't tell whether the action in `componentsState` came from a\n // server-only CC (must persist) or from a realtime CC also re-shipped\n // (must clear).\n //\n // Absent on old backends; new SDKs fall back to a legacy heuristic that\n // infers the same information from `componentsState`, so the old-BE /\n // new-SDK combination still works correctly.\n serverOnlyComponentsState?: Record<string, string>;\n // Client-evaluable visibility conditions, populated only by new backends.\n // Absent on old backends; new SDKs ignore when absent.\n realtimeComponentsConditions?: RealtimeComponentsCondition[];\n}\n\nexport type SSOQueryParams = {\n oidcIdpStateId?: string;\n samlIdpStateId?: string;\n wsfedIdpStateId?: string;\n samlIdpUsername?: string;\n descopeIdpInitiated?: boolean;\n ssoAppId?: string;\n customAppId?: string;\n thirdPartyAppId: string;\n thirdPartyAppStateId?: string;\n applicationScopes?: string;\n} & OIDCOptions;\n\nexport type OIDCOptions = {\n oidcLoginHint?: string;\n oidcPrompt?: string;\n oidcErrorRedirectUri?: string;\n oidcResource?: string;\n};\n\nexport type FlowState = {\n flowId: string;\n projectId: string;\n baseUrl: string;\n tenant: string;\n stepId: string;\n stepName: string;\n executionId: string;\n action: string;\n redirectTo: string;\n redirectIsPopup: boolean;\n openInNewTabUrl?: string;\n redirectUrl: string;\n screenId: string;\n screenState: ScreenState;\n token: string;\n code: string;\n isPopup: boolean;\n exchangeError: string;\n webauthnTransactionId: string;\n webauthnOptions: string;\n redirectAuthCodeChallenge: string;\n redirectAuthCallbackUrl: string;\n redirectAuthBackupCallbackUri: string;\n redirectAuthInitiator: string;\n deferredRedirect: boolean;\n deferredPolling: boolean;\n locale: string;\n samlIdpResponseUrl: string;\n samlIdpResponseSamlResponse: string;\n samlIdpResponseRelayState: string;\n wsFedIdpResponseUrl: string;\n wsFedIdpResponseWresult: string;\n wsFedIdpResponseWctx: string;\n nativeResponseType: string;\n nativePayload: Record<string, any>;\n reqTimestamp: number;\n} & SSOQueryParams;\n\nexport type StepState = {\n screenState: ScreenState;\n screenId: string;\n stepName: string;\n htmlFilename: string;\n htmlLocaleFilename: string;\n next: NextFn;\n direction: Direction | undefined;\n samlIdpUsername: string;\n action?: string;\n locale?: string;\n} & OIDCOptions;\n\nexport type CustomScreenState = Omit<\n ScreenState,\n 'cssVars' | 'componentsConfig' | 'inputs'\n> & {\n error?: {\n text: ScreenState['errorText'];\n type: ScreenState['errorType'];\n };\n action?: string;\n inboundAppApproveScopes?: {\n desc: string;\n id: string;\n required: boolean;\n }[];\n};\n\nexport type DebugState = {\n isDebug: boolean;\n};\n\nexport interface ScriptElement extends HTMLDivElement {\n moduleRes?: ScriptModule;\n}\n\nexport type ScriptModule = {\n /**\n * Unique identifier of the module.\n */\n id: string;\n /**\n * Notifies the module that it should start any profiling or monitoring.\n */\n start?: () => void;\n /**\n * Notifies the module that it should stop any profiling or monitoring.\n */\n stop?: () => void;\n /**\n * Presents the user with any required interaction to get a refreshed token or state,\n * e.g., a challenge or captcha.\n *\n * Modules should return a value of true if the presentation completed successfully,\n * false if it was cancelled by the user, and throw an error in case of failure.\n *\n * This is called before form submission (via a next call) after a button click.\n */\n present?: () => Promise<boolean>;\n /**\n * Refreshes any tokens or state that might be needed before form submission.\n *\n * Modules should throw an error in case of failure.\n */\n refresh?: () => Promise<void>;\n};\n\nexport type ClientScript = {\n id: string;\n initArgs: Record<string, any>;\n resultKey?: string;\n};\n\nexport type NextFn = KeepArgsByIndex<SdkFlowNext, [2, 5]> & {\n isCustomScreen?: boolean;\n};\nexport type NextFnReturnPromiseValue = Awaited<ReturnType<NextFn>>;\n\nexport type DebuggerMessage = {\n title: string;\n description?: string;\n};\n\nexport type FlowStateUpdateFn = (state: FlowState) => void;\n\ntype Operator =\n | 'equal'\n | 'not-equal'\n | 'contains'\n | 'greater-than'\n | 'greater-than-or-equal'\n | 'less-than'\n | 'less-than-or-equal'\n | 'empty'\n | 'not-empty'\n | 'is-true'\n | 'is-false'\n | 'in'\n | 'not-in'\n | 'in-range'\n | 'not-in-range'\n | 'devised-by';\n\nexport interface ClientConditionResult {\n screenId: string;\n screenName: string;\n clientScripts?: ClientScript[];\n componentsConfig?: ComponentsConfig;\n interactionId: string;\n}\n\nexport interface ClientCondition {\n operator: Operator;\n key: string;\n predicate?: string | number;\n met: ClientConditionResult;\n unmet?: ClientConditionResult;\n}\n\nexport type AutoFocusOptions = true | false | 'skipFirstScreen';\n\nexport type ThemeOptions = 'light' | 'dark' | 'os';\n\nexport type Key =\n | 'lastAuth.loginId'\n | 'idpInitiated'\n | 'externalToken'\n | 'abTestingKey';\n\ntype CheckFunction = (ctx: Context, predicate?: string | number) => boolean;\n\nexport type ConditionsMap = {\n [key in Key]: {\n [operator in Operator]?: CheckFunction;\n };\n};\n\nexport interface Context {\n loginId?: string;\n code?: string;\n token?: string;\n abTestingKey?: number;\n lastAuth?: LastAuthState;\n}\n\nexport type DescopeUI = Record<string, () => Promise<void>> & {\n componentsThemeManager: Record<string, any>;\n};\n\ntype Font = {\n family: string[];\n label: string;\n url?: string;\n};\n\ntype ThemeTemplate = {\n fonts: {\n font1: Font;\n font2: Font;\n };\n};\n\ntype ThemeColor = {\n main: string;\n dark: string;\n light: string;\n highlight: string;\n contrast: string;\n};\n\nexport type OverrideTheme = {\n globals?: {\n colors?: {\n primary?: ThemeColor;\n secondary?: ThemeColor;\n };\n };\n};\n\nexport type OverrideThemes = {\n dark?: OverrideTheme;\n light?: OverrideTheme;\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\nexport type CustomStorage = {\n getItem: (key: string) => string | null;\n setItem: (key: string, value: string) => void;\n removeItem: (key: string) => void;\n};\n\nexport type FlowJWTResponse = JWTResponse & {\n flowOutput?: Record<string, any>;\n};\n"],"names":["Direction"],"mappings":"aAoCA,IAAYA,EAAAA,QAGXA,eAAA,GAHWA,EAAAA,QAASA,YAATA,kBAGX,CAAA,IAFC,SAAA,WACAA,EAAA,QAAA"}
|
|
1
|
+
{"version":3,"file":"types.js","sources":["../../src/lib/types.ts"],"sourcesContent":["/* istanbul ignore file */\n\nimport type { JWTResponse } from '@descope/web-js-sdk';\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 type LastAuthState = NonNullable<\n NextFnReturnPromiseValue['data']['lastAuth']\n> & {\n loginId?: string;\n name?: string;\n lastUsedPerScreen?: Record<string, string>;\n};\n\nexport type RealtimeOperandKind = 'value' | 'form' | 'list';\n\n// Operators the SDK is allowed to evaluate locally. The server's\n// clientSupportedRealtimeOperators must stay in sync — anything outside this\n// list is pre-evaluated server-side and shipped as a value operand.\n//\n// is-email / is-phone are intentionally absent: the server validates them\n// with dedicated libraries (contact.IsValid*); the client has no equivalent,\n// so the server keeps these CCs server-only.\nexport type RealtimeOperator =\n | 'equal'\n | 'not-equal'\n | 'contains'\n | 'doesnt-contains'\n | 'greater-than'\n | 'greater-than-or-equal'\n | 'less-than'\n | 'less-than-or-equal'\n | 'empty'\n | 'not-empty'\n | 'is-true'\n | 'is-false'\n | 'in'\n | 'not-in'\n | 'matches';\n\nexport interface RealtimeOperand {\n kind: RealtimeOperandKind;\n // Form is the context key the client looks up from the live form snapshot\n // (e.g. \"form.phone\"). Set only when kind === 'form'.\n form?: string;\n // Items is the operand list when kind === 'list'. Each element is a nested\n // operand — either a form placeholder or a resolved literal. Used when the\n // server detects an `in` / `not-in` / `contains` predicate whose array\n // contains `{{form.X}}` references; the client resolves them at eval time.\n items?: RealtimeOperand[];\n // Pre-resolved literal. Set only when kind === 'value', and may legitimately\n // be false / 0 / \"\" — do not treat absence as \"no value\" without checking\n // kind first.\n value?: unknown;\n}\n\nexport interface RealtimeAtomicCondition {\n operator: RealtimeOperator;\n target?: RealtimeOperand;\n predicate?: RealtimeOperand;\n}\n\nexport interface RealtimeRule {\n logicalOr?: boolean;\n atomicConditions: RealtimeAtomicCondition[];\n}\n\nexport interface RealtimeComponentsCondition {\n id?: string;\n componentIds: string[];\n action: string;\n rules: RealtimeRule[];\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 // map of component IDs to their state — the FULL last-wins verdict over\n // all CCs (server-only + client-eligible) the BE evaluated at screen-init.\n // Used by `applyComponentsState` for the first DOM paint.\n componentsState?: Record<string, string>;\n // Subset of `componentsState` contributed by SERVER-ONLY CCs — those the\n // client cannot re-evaluate locally (operators on the server-only\n // allow-list like `is-email`, or rules referencing context the client\n // doesn't have). Parallels `componentsState` in structure but excludes\n // contributions from client-eligible CCs that also ship in\n // `realtimeComponentsConditions`.\n //\n // The realtime layer uses this as the fallback action to restore when a\n // realtime CC stops firing on a touched component — without it the SDK\n // can't tell whether the action in `componentsState` came from a\n // server-only CC (must persist) or from a realtime CC also re-shipped\n // (must clear).\n //\n // Absent on old backends; new SDKs fall back to a legacy heuristic that\n // infers the same information from `componentsState`, so the old-BE /\n // new-SDK combination still works correctly.\n serverOnlyComponentsState?: Record<string, string>;\n // Client-evaluable visibility conditions, populated only by new backends.\n // Absent on old backends; new SDKs ignore when absent.\n realtimeComponentsConditions?: RealtimeComponentsCondition[];\n}\n\nexport type SSOQueryParams = {\n oidcIdpStateId?: string;\n samlIdpStateId?: string;\n wsfedIdpStateId?: string;\n samlIdpUsername?: string;\n descopeIdpInitiated?: boolean;\n ssoAppId?: string;\n customAppId?: string;\n thirdPartyAppId: string;\n thirdPartyAppStateId?: string;\n applicationScopes?: string;\n} & OIDCOptions;\n\nexport type OIDCOptions = {\n oidcLoginHint?: string;\n oidcPrompt?: string;\n oidcErrorRedirectUri?: string;\n oidcResource?: string;\n};\n\nexport type FlowState = {\n flowId: string;\n projectId: string;\n baseUrl: string;\n tenant: string;\n stepId: string;\n stepName: string;\n executionId: string;\n action: string;\n redirectTo: string;\n redirectIsPopup: boolean;\n openInNewTabUrl?: string;\n redirectUrl: string;\n screenId: string;\n screenState: ScreenState;\n token: string;\n code: string;\n isPopup: boolean;\n exchangeError: string;\n webauthnTransactionId: string;\n webauthnOptions: string;\n redirectAuthCodeChallenge: string;\n redirectAuthCallbackUrl: string;\n redirectAuthBackupCallbackUri: string;\n redirectAuthInitiator: string;\n deferredRedirect: boolean;\n deferredPolling: boolean;\n locale: string;\n samlIdpResponseUrl: string;\n samlIdpResponseSamlResponse: string;\n samlIdpResponseRelayState: string;\n wsFedIdpResponseUrl: string;\n wsFedIdpResponseWresult: string;\n wsFedIdpResponseWctx: string;\n nativeResponseType: string;\n nativePayload: Record<string, any>;\n reqTimestamp: number;\n} & SSOQueryParams;\n\nexport type StepState = {\n screenState: ScreenState;\n screenId: string;\n stepName: string;\n htmlFilename: string;\n htmlLocaleFilename: string;\n next: NextFn;\n direction: Direction | undefined;\n samlIdpUsername: string;\n action?: string;\n locale?: string;\n} & OIDCOptions;\n\nexport type CustomScreenState = Omit<\n ScreenState,\n 'cssVars' | 'componentsConfig' | 'inputs'\n> & {\n error?: {\n text: ScreenState['errorText'];\n type: ScreenState['errorType'];\n };\n action?: string;\n inboundAppApproveScopes?: {\n desc: string;\n id: string;\n required: boolean;\n }[];\n};\n\nexport type DebugState = {\n isDebug: boolean;\n};\n\nexport interface ScriptElement extends HTMLDivElement {\n moduleRes?: ScriptModule;\n}\n\nexport type ScriptModule = {\n /**\n * Unique identifier of the module.\n */\n id: string;\n /**\n * Notifies the module that it should start any profiling or monitoring.\n */\n start?: () => void;\n /**\n * Notifies the module that it should stop any profiling or monitoring.\n */\n stop?: () => void;\n /**\n * Presents the user with any required interaction to get a refreshed token or state,\n * e.g., a challenge or captcha.\n *\n * Modules should return a value of true if the presentation completed successfully,\n * false if it was cancelled by the user, and throw an error in case of failure.\n *\n * This is called before form submission (via a next call) after a button click.\n */\n present?: () => Promise<boolean>;\n /**\n * Refreshes any tokens or state that might be needed before form submission.\n *\n * Modules should throw an error in case of failure.\n */\n refresh?: () => Promise<void>;\n};\n\nexport type ClientScript = {\n id: string;\n initArgs: Record<string, any>;\n resultKey?: string;\n};\n\nexport type NextFn = KeepArgsByIndex<SdkFlowNext, [2, 5]> & {\n isCustomScreen?: boolean;\n};\nexport type NextFnReturnPromiseValue = Awaited<ReturnType<NextFn>>;\n\nexport type DebuggerMessage = {\n title: string;\n description?: string;\n};\n\nexport type FlowStateUpdateFn = (state: FlowState) => void;\n\ntype Operator =\n | 'equal'\n | 'not-equal'\n | 'contains'\n | 'greater-than'\n | 'greater-than-or-equal'\n | 'less-than'\n | 'less-than-or-equal'\n | 'empty'\n | 'not-empty'\n | 'is-true'\n | 'is-false'\n | 'in'\n | 'not-in'\n | 'in-range'\n | 'not-in-range'\n | 'devised-by';\n\nexport interface ClientConditionResult {\n screenId: string;\n screenName: string;\n clientScripts?: ClientScript[];\n componentsConfig?: ComponentsConfig;\n interactionId: string;\n}\n\nexport interface ClientCondition {\n operator: Operator;\n key: string;\n predicate?: string | number;\n met: ClientConditionResult;\n unmet?: ClientConditionResult;\n}\n\nexport type AutoFocusOptions = true | false | 'skipFirstScreen';\n\nexport type ThemeOptions = 'light' | 'dark' | 'os';\n\nexport type Key =\n | 'lastAuth.loginId'\n | 'idpInitiated'\n | 'externalToken'\n | 'abTestingKey';\n\ntype CheckFunction = (ctx: Context, predicate?: string | number) => boolean;\n\nexport type ConditionsMap = {\n [key in Key]: {\n [operator in Operator]?: CheckFunction;\n };\n};\n\nexport interface Context {\n loginId?: string;\n code?: string;\n token?: string;\n abTestingKey?: number;\n lastAuth?: LastAuthState;\n}\n\nexport type DescopeUI = Record<string, () => Promise<void>> & {\n componentsThemeManager: Record<string, any>;\n};\n\ntype Font = {\n family: string[];\n label: string;\n url?: string;\n};\n\ntype ThemeTemplate = {\n fonts: {\n font1: Font;\n font2: Font;\n };\n};\n\ntype ThemeColor = {\n main: string;\n dark: string;\n light: string;\n highlight: string;\n contrast: string;\n};\n\nexport type OverrideTheme = {\n globals?: {\n colors?: {\n primary?: ThemeColor;\n secondary?: ThemeColor;\n };\n };\n};\n\nexport type OverrideThemes = {\n dark?: OverrideTheme;\n light?: OverrideTheme;\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\nexport type CustomStorage = {\n getItem: (key: string) => string | null;\n setItem: (key: string, value: string) => void;\n removeItem: (key: string) => void;\n};\n\nexport type FlowJWTResponse = JWTResponse & {\n flowOutput?: Record<string, any>;\n};\n"],"names":["Direction"],"mappings":"aAoCA,IAAYA,EAAAA,QAGXA,eAAA,GAHWA,EAAAA,QAASA,YAATA,kBAGX,CAAA,IAFC,SAAA,WACAA,EAAA,QAAA"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{__classPrivateFieldGet as t,__awaiter as e,__classPrivateFieldSet as i}from"tslib";import{compose as r}from"@descope/sdk-helpers";import{staticResourcesMixin as o}from"@descope/sdk-mixins/static-resources-mixin";import{themeMixin as s}from"@descope/sdk-mixins/theme-mixin";import{injectStyleMixin as n}from"@descope/sdk-mixins/inject-style-mixin";import{createSdk as a}from"@descope/web-js-sdk";import{ELEMENTS_TO_IGNORE_ENTER_KEY_ON as u}from"../constants/index.js";import{handleUrlParams as l,clearRunIdsFromUrl as d,camelCase as c,getRunIdsFromUrl as h,getContentUrl as f,fetchContent as g,withRetry as p}from"../helpers/helpers.js";import m from"../helpers/state.js";import"@descope/escape-markdown";import"../helpers/webauthn.js";import{setCustomStorage as b}from"../helpers/storage.js";import{transformFlowInputFormData as v,extractNestedAttribute as w}from"../helpers/flowInputs.js";import{formMountMixin as k}from"../mixins/formMountMixin.js";import{componentConditionsMixin as C}from"../mixins/componentConditionsMixin.js";import{CONFIG_FILENAME as y,PREV_VER_ASSETS_FOLDER as A}from"../constants/content.js";import{FETCH_EXCEPTION_ERROR_CODE as x}from"../constants/general.js";var I,j,E,L,S,U,M,O,W,D,P,N,F,K,R,T,B,H,J,V,q,$;const z=r(s,o,k,C,n)(HTMLElement);class Q extends z{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(),I.add(this),E.set(this,!1),L.set(this,void 0),this.flowStatus="initial",this.loggerWrapper={error:(e,i="")=>{this.logger.error(e,i,new Error),t(this,I,"m",$).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)}},S.set(this,new m),U.set(this,new m),M.set(this,{}),this.getComponentsContext=()=>t(this,M,"f"),this.nextRequestStatus=new m({isLoading:!1}),O.set(this,void 0),W.set(this,{popstate:t(this,I,"m",K).bind(this),componentsContext:t(this,I,"m",J).bind(this)}),D.set(this,void 0),this.getConfig=()=>e(this,void 0,void 0,(function*(){return(yield this.config)||{isMissingConfig:!0}})),i(this,D,r,"f"),t(this,I,"m",N).call(this)}get flowId(){return this.getAttribute("flow-id")}get client(){try{return JSON.parse(this.getAttribute("client"))||{}}catch(t){return{}}}get redirectUrl(){return this.getAttribute("redirect-url")||void 0}get debug(){return"true"===this.getAttribute("debug")}get locale(){return this.getAttribute("locale")||void 0}get autoFocus(){var t;const e=null!==(t=this.getAttribute("auto-focus"))&&void 0!==t?t:"true";return"skipFirstScreen"===e?e:"true"===e}get validateOnBlur(){return"true"===this.getAttribute("validate-on-blur")}get storeLastAuthenticatedUser(){var t;return"true"===(null!==(t=this.getAttribute("store-last-authenticated-user"))&&void 0!==t?t:"true")}get refreshCookieName(){return this.getAttribute("refresh-cookie-name")||""}get keepLastAuthenticatedUserAfterLogout(){return"true"===this.getAttribute("keep-last-authenticated-user-after-logout")}get storagePrefix(){return this.getAttribute("storage-prefix")||""}get preview(){return!!this.getAttribute("preview")}get formConfig(){return v(this.form)}get form(){return this.getAttribute("form")}get formConfigValues(){return w(this.formConfig,"value")}get outboundAppId(){return this.getAttribute("outbound-app-id")}get outboundAppScopes(){try{const t=JSON.parse(this.getAttribute("outbound-app-scopes"));return t||null}catch(t){return null}}get popupOrigin(){return this.getAttribute("popup-origin")}get customStorage(){return t(this,L,"f")}set customStorage(t){if(t&&"function"!=typeof t.getItem)throw new Error("Custom storage must have a getItem method");if(t&&"function"!=typeof t.setItem)throw new Error("Custom storage must have a setItem method");if(t&&"function"!=typeof t.removeItem)throw new Error("Custom storage must have a removeItem method");i(this,L,t,"f"),b(t)}get isRestartOnError(){return"true"===this.getAttribute("restart-on-error")}getExecutionContext(){return e(this,void 0,void 0,(function*(){const t=yield this.getConfig();return"executionContext"in t?t.executionContext:void 0}))}getProjectConfig(){return e(this,void 0,void 0,(function*(){const t=yield this.getConfig();return"projectConfig"in t?t.projectConfig:void 0}))}getFlowConfig(){return e(this,void 0,void 0,(function*(){var t,e;const i=yield this.getProjectConfig(),r=(null===(t=null==i?void 0:i.flows)||void 0===t?void 0:t[this.flowId])||{};return null!==(e=r.version)&&void 0!==e||(r.version=0),r}))}getTargetLocales(){return e(this,void 0,void 0,(function*(){const t=yield this.getFlowConfig();return((null==t?void 0:t.targetLocales)||[]).map((t=>t.toLowerCase()))}))}handleKeyPress(){this.logger.debug("Enable key press handler"),this.rootElement.onkeydown=t=>{var e,i,r;const o=!!(null===(e=this.shadowRoot.activeElement)||void 0===e?void 0:e.getAttribute("href")),s=u.includes(null!==(r=null===(i=this.shadowRoot.activeElement)||void 0===i?void 0:i.localName)&&void 0!==r?r:"");if("Enter"!==t.key||o||s)return;t.preventDefault();const n=this.rootElement.querySelectorAll("descope-button");if(1===n.length&&"false"!==n[0].getAttribute("auto-submit"))return void n[0].click();const a=Array.from(n).filter((t=>"true"===t.getAttribute("auto-submit")));if(1===a.length)return void a[0].click();const l=Array.from(n).filter((t=>"button"===t.getAttribute("data-type")));if(1===l.length)"false"!==l[0].getAttribute("auto-submit")&&l[0].click();else if(0===l.length){const t=Array.from(n).filter((t=>"sso"===t.getAttribute("data-type")));1===t.length&&"false"!==t[0].getAttribute("auto-submit")&&t[0].click()}}}disableKeyPressHandler(){this.logger.debug("Disable key press handler"),this.rootElement.onkeydown=null}getComponentsVersion(){return e(this,void 0,void 0,(function*(){var t;const e=yield this.getConfig(),i="projectConfig"in e?null===(t=e.projectConfig)||void 0===t?void 0:t.componentsVersion:{};return i||(this.logger.error("Did not get components version, using latest version"),"latest")}))}init(){const r=Object.create(null,{init:{get:()=>super.init}});return e(this,void 0,void 0,(function*(){var e;if(this.flowStatus="loading",["ready","error","success"].forEach((t=>this.addEventListener(t,(()=>{this.flowStatus=t})))),yield null===(e=r.init)||void 0===e?void 0:e.call(this),t(this,U,"f").subscribe(t(this,I,"m",q).bind(this)),t(this,U,"f").update({isDebug:this.debug}),t(this,I,"m",F).call(this),yield t(this,I,"m",B).call(this))return void this.loggerWrapper.error("This SDK version does not support your flows version","Make sure to upgrade your flows to the latest version or use an older SDK version");const o=yield this.getConfig();if("isMissingConfig"in o&&o.isMissingConfig)return void this.loggerWrapper.error("Cannot get config file","Make sure that your projectId & flowId are correct");const{executionId:s,stepId:n,token:a,code:u,isPopup:d,exchangeError:c,redirectAuthCallbackUrl:h,redirectAuthBackupCallbackUri:f,redirectAuthCodeChallenge:g,redirectAuthInitiator:p,ssoQueryParams:m}=l(this.flowId,this.loggerWrapper);window.addEventListener("popstate",t(this,W,"f").popstate),window.addEventListener("components-context",t(this,W,"f").componentsContext),t(this,S,"f").subscribe(t(this,I,"m",T).bind(this)),t(this,S,"f").update(Object.assign({projectId:this.projectId,flowId:this.flowId,baseUrl:this.baseUrl,tenant:this.tenantId,redirectUrl:this.redirectUrl,locale:this.locale,stepId:n,executionId:s,token:a,code:u,isPopup:d,exchangeError:c,redirectAuthCallbackUrl:h,redirectAuthBackupCallbackUri:f,redirectAuthCodeChallenge:g,redirectAuthInitiator:p},m)),i(this,E,!0,"f")}))}disconnectedCallback(){var e;t(this,S,"f").unsubscribeAll(),t(this,U,"f").unsubscribeAll(),t(this,I,"m",V).call(this),window.removeEventListener("popstate",t(this,W,"f").popstate),window.removeEventListener("components-context",t(this,W,"f").componentsContext),null===(e=super.disconnectedCallback)||void 0===e||e.call(this)}attributeChangedCallback(e,i,r){if(this.shadowRoot.isConnected&&t(this,E,"f")&&i!==r&&j.observedAttributes.includes(e)){t(this,I,"m",F).call(this);const o=null===i;t(this,S,"f").update((({stepId:t,executionId:i})=>{let s=t,n=i;return o||(n=null,s=null,d()),{[c(e)]:r,stepId:s,executionId:n}})),t(this,U,"f").update({isDebug:this.debug})}}}j=Q,E=new WeakMap,L=new WeakMap,S=new WeakMap,U=new WeakMap,M=new WeakMap,O=new WeakMap,W=new WeakMap,D=new WeakMap,I=new WeakSet,P=function(){this.injectStyle("\n :host {\n\t\t\twidth: 100%;\n display: block;\n\t\t}\n\n\t\t#root {\n\t\t\theight: 100%;\n display: flex;\n flex-direction: column;\n\t\t}\n\n #content-root {\n all: initial;\n transition: opacity 200ms ease-in-out;\n }\n\n\t\t#root[data-theme] {\n\t\t\tbackground-color: transparent;\n\t\t}\n\n\t\t.fade-out {\n\t\t\topacity: 0.1!important;\n\t\t}\n\n .hidden {\n display: none;\n }\n ")},N=function(){t(this,I,"m",P).call(this),this.slotElement=document.createElement("slot"),this.slotElement.classList.add("hidden"),this.rootElement.appendChild(this.slotElement)},F=function(){const t=["base-url","tenant","locale","debug","redirect-url","auto-focus","store-last-authenticated-user","refresh-cookie-name","keep-last-authenticated-user-after-logout","preview","storage-prefix","form","client","validate-on-blur","style-id","outbound-app-id","outbound-app-scopes","theme-override"];j.observedAttributes.forEach((e=>{if(!t.includes(e)&&!this[c(e)])throw Error(`${e} cannot be empty`)}))},K=function(){const{stepId:e,executionId:i}=h(this.flowId);t(this,S,"f").update({stepId:e,executionId:i})},R=function(i,r){a&&"function"==typeof a||this.logger.error("SDK was not loaded properly",a,JSON.stringify(a));const o=Object.assign(Object.assign({persistTokens:!0,preview:this.preview,storagePrefix:this.storagePrefix,storeLastAuthenticatedUser:this.storeLastAuthenticatedUser,keepLastAuthenticatedUserAfterLogout:this.keepLastAuthenticatedUserAfterLogout,refreshCookieName:this.refreshCookieName},j.sdkConfigOverrides),{projectId:i,baseUrl:r});t(this,L,"f")&&(o.customStorage=t(this,L,"f")),this.sdk=a(o),["start","next"].forEach((t=>{const i=this.sdk.flow[t],r=p(i,1e3,3);this.sdk.flow[t]=(...i)=>e(this,void 0,void 0,(function*(){try{return yield r(...i)}catch(e){return this.logger.error(`Error in sdk flow ${t} function`,e),{error:{errorCode:x,errorDescription:e.toString()}}}}))}))},T=function(i,r,o){return e(this,void 0,void 0,(function*(){const{projectId:e,baseUrl:r}=i;if(o("projectId")||o("baseUrl")){if(!e)return;t(this,I,"m",R).call(this,e,r)}t(this,D,"f").call(this,i)}))},B=function(){return e(this,void 0,void 0,(function*(){const e=yield this.getConfig();return"isMissingConfig"in e&&e.isMissingConfig&&(yield t(this,I,"m",H).call(this))}))},H=function(){return e(this,void 0,void 0,(function*(){const t=f({projectId:this.projectId,filename:y,assetsFolder:A,baseUrl:this.baseStaticUrl});try{return yield g(t,"json"),!0}catch(t){return!1}}))},J=function(e){i(this,M,Object.assign(Object.assign({},t(this,M,"f")),e.detail),"f")},V=function(){var e;null===(e=t(this,O,"f"))||void 0===e||e.remove(),i(this,O,null,"f")},q=function(r){return e(this,arguments,void 0,(function*({isDebug:e}){e?(i(this,O,document.createElement("descope-debugger"),"f"),Object.assign(t(this,O,"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,O,"f"))):t(this,I,"m",V).call(this)}))},$=function(e,i){var r;e&&this.debug&&(null===(r=t(this,O,"f"))||void 0===r||r.updateData({title:e,description:i}))},Q.sdkConfigOverrides={baseHeaders:{"x-descope-sdk-name":"web-component","x-descope-sdk-version":"3.68.0"}};export{Q as default};
|
|
1
|
+
import{__classPrivateFieldGet as t,__awaiter as e,__classPrivateFieldSet as i}from"tslib";import{compose as r}from"@descope/sdk-helpers";import{staticResourcesMixin as o}from"@descope/sdk-mixins/static-resources-mixin";import{themeMixin as s}from"@descope/sdk-mixins/theme-mixin";import{injectStyleMixin as n}from"@descope/sdk-mixins/inject-style-mixin";import{createSdk as a}from"@descope/web-js-sdk";import{ELEMENTS_TO_IGNORE_ENTER_KEY_ON as u}from"../constants/index.js";import{handleUrlParams as l,clearRunIdsFromUrl as d,camelCase as c,getRunIdsFromUrl as h,getContentUrl as f,fetchContent as g,withRetry as p}from"../helpers/helpers.js";import m from"../helpers/state.js";import"@descope/escape-markdown";import"../helpers/webauthn.js";import{setCustomStorage as b}from"../helpers/storage.js";import{transformFlowInputFormData as v,extractNestedAttribute as w}from"../helpers/flowInputs.js";import{formMountMixin as k}from"../mixins/formMountMixin.js";import{componentConditionsMixin as C}from"../mixins/componentConditionsMixin.js";import{CONFIG_FILENAME as y,PREV_VER_ASSETS_FOLDER as A}from"../constants/content.js";import{FETCH_EXCEPTION_ERROR_CODE as x}from"../constants/general.js";var I,j,E,L,S,U,M,O,W,D,P,N,F,K,R,T,B,H,J,V,q,$;const z=r(s,o,k,C,n)(HTMLElement);class Q extends z{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(),I.add(this),E.set(this,!1),L.set(this,void 0),this.flowStatus="initial",this.loggerWrapper={error:(e,i="")=>{this.logger.error(e,i,new Error),t(this,I,"m",$).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)}},S.set(this,new m),U.set(this,new m),M.set(this,{}),this.getComponentsContext=()=>t(this,M,"f"),this.nextRequestStatus=new m({isLoading:!1}),O.set(this,void 0),W.set(this,{popstate:t(this,I,"m",K).bind(this),componentsContext:t(this,I,"m",J).bind(this)}),D.set(this,void 0),this.getConfig=()=>e(this,void 0,void 0,(function*(){return(yield this.config)||{isMissingConfig:!0}})),i(this,D,r,"f"),t(this,I,"m",N).call(this)}get flowId(){return this.getAttribute("flow-id")}get client(){try{return JSON.parse(this.getAttribute("client"))||{}}catch(t){return{}}}get redirectUrl(){return this.getAttribute("redirect-url")||void 0}get debug(){return"true"===this.getAttribute("debug")}get locale(){return this.getAttribute("locale")||void 0}get autoFocus(){var t;const e=null!==(t=this.getAttribute("auto-focus"))&&void 0!==t?t:"true";return"skipFirstScreen"===e?e:"true"===e}get validateOnBlur(){return"true"===this.getAttribute("validate-on-blur")}get storeLastAuthenticatedUser(){var t;return"true"===(null!==(t=this.getAttribute("store-last-authenticated-user"))&&void 0!==t?t:"true")}get refreshCookieName(){return this.getAttribute("refresh-cookie-name")||""}get keepLastAuthenticatedUserAfterLogout(){return"true"===this.getAttribute("keep-last-authenticated-user-after-logout")}get storagePrefix(){return this.getAttribute("storage-prefix")||""}get preview(){return!!this.getAttribute("preview")}get formConfig(){return v(this.form)}get form(){return this.getAttribute("form")}get formConfigValues(){return w(this.formConfig,"value")}get outboundAppId(){return this.getAttribute("outbound-app-id")}get outboundAppScopes(){try{const t=JSON.parse(this.getAttribute("outbound-app-scopes"));return t||null}catch(t){return null}}get popupOrigin(){return this.getAttribute("popup-origin")}get customStorage(){return t(this,L,"f")}set customStorage(t){if(t&&"function"!=typeof t.getItem)throw new Error("Custom storage must have a getItem method");if(t&&"function"!=typeof t.setItem)throw new Error("Custom storage must have a setItem method");if(t&&"function"!=typeof t.removeItem)throw new Error("Custom storage must have a removeItem method");i(this,L,t,"f"),b(t)}get isRestartOnError(){return"true"===this.getAttribute("restart-on-error")}getExecutionContext(){return e(this,void 0,void 0,(function*(){const t=yield this.getConfig();return"executionContext"in t?t.executionContext:void 0}))}getProjectConfig(){return e(this,void 0,void 0,(function*(){const t=yield this.getConfig();return"projectConfig"in t?t.projectConfig:void 0}))}getFlowConfig(){return e(this,void 0,void 0,(function*(){var t,e;const i=yield this.getProjectConfig(),r=(null===(t=null==i?void 0:i.flows)||void 0===t?void 0:t[this.flowId])||{};return null!==(e=r.version)&&void 0!==e||(r.version=0),r}))}getTargetLocales(){return e(this,void 0,void 0,(function*(){const t=yield this.getFlowConfig();return((null==t?void 0:t.targetLocales)||[]).map((t=>t.toLowerCase()))}))}handleKeyPress(){this.logger.debug("Enable key press handler"),this.rootElement.onkeydown=t=>{var e,i,r;const o=!!(null===(e=this.shadowRoot.activeElement)||void 0===e?void 0:e.getAttribute("href")),s=u.includes(null!==(r=null===(i=this.shadowRoot.activeElement)||void 0===i?void 0:i.localName)&&void 0!==r?r:"");if("Enter"!==t.key||o||s)return;t.preventDefault();const n=this.rootElement.querySelectorAll("descope-button");if(1===n.length&&"false"!==n[0].getAttribute("auto-submit"))return void n[0].click();const a=Array.from(n).filter((t=>"true"===t.getAttribute("auto-submit")));if(1===a.length)return void a[0].click();const l=Array.from(n).filter((t=>"button"===t.getAttribute("data-type")));if(1===l.length)"false"!==l[0].getAttribute("auto-submit")&&l[0].click();else if(0===l.length){const t=Array.from(n).filter((t=>"sso"===t.getAttribute("data-type")));1===t.length&&"false"!==t[0].getAttribute("auto-submit")&&t[0].click()}}}disableKeyPressHandler(){this.logger.debug("Disable key press handler"),this.rootElement.onkeydown=null}getComponentsVersion(){return e(this,void 0,void 0,(function*(){var t;const e=yield this.getConfig(),i="projectConfig"in e?null===(t=e.projectConfig)||void 0===t?void 0:t.componentsVersion:{};return i||(this.logger.error("Did not get components version, using latest version"),"latest")}))}init(){const r=Object.create(null,{init:{get:()=>super.init}});return e(this,void 0,void 0,(function*(){var e;if(this.flowStatus="loading",["ready","error","success"].forEach((t=>this.addEventListener(t,(()=>{this.flowStatus=t})))),yield null===(e=r.init)||void 0===e?void 0:e.call(this),t(this,U,"f").subscribe(t(this,I,"m",q).bind(this)),t(this,U,"f").update({isDebug:this.debug}),t(this,I,"m",F).call(this),yield t(this,I,"m",B).call(this))return void this.loggerWrapper.error("This SDK version does not support your flows version","Make sure to upgrade your flows to the latest version or use an older SDK version");const o=yield this.getConfig();if("isMissingConfig"in o&&o.isMissingConfig)return void this.loggerWrapper.error("Cannot get config file","Make sure that your projectId & flowId are correct");const{executionId:s,stepId:n,token:a,code:u,isPopup:d,exchangeError:c,redirectAuthCallbackUrl:h,redirectAuthBackupCallbackUri:f,redirectAuthCodeChallenge:g,redirectAuthInitiator:p,ssoQueryParams:m}=l(this.flowId,this.loggerWrapper);window.addEventListener("popstate",t(this,W,"f").popstate),window.addEventListener("components-context",t(this,W,"f").componentsContext),t(this,S,"f").subscribe(t(this,I,"m",T).bind(this)),t(this,S,"f").update(Object.assign({projectId:this.projectId,flowId:this.flowId,baseUrl:this.baseUrl,tenant:this.tenantId,redirectUrl:this.redirectUrl,locale:this.locale,stepId:n,executionId:s,token:a,code:u,isPopup:d,exchangeError:c,redirectAuthCallbackUrl:h,redirectAuthBackupCallbackUri:f,redirectAuthCodeChallenge:g,redirectAuthInitiator:p},m)),i(this,E,!0,"f")}))}disconnectedCallback(){var e;t(this,S,"f").unsubscribeAll(),t(this,U,"f").unsubscribeAll(),t(this,I,"m",V).call(this),window.removeEventListener("popstate",t(this,W,"f").popstate),window.removeEventListener("components-context",t(this,W,"f").componentsContext),null===(e=super.disconnectedCallback)||void 0===e||e.call(this)}attributeChangedCallback(e,i,r){if(this.shadowRoot.isConnected&&t(this,E,"f")&&i!==r&&j.observedAttributes.includes(e)){t(this,I,"m",F).call(this);const o=null===i;t(this,S,"f").update((({stepId:t,executionId:i})=>{let s=t,n=i;return o||(n=null,s=null,d()),{[c(e)]:r,stepId:s,executionId:n}})),t(this,U,"f").update({isDebug:this.debug})}}}j=Q,E=new WeakMap,L=new WeakMap,S=new WeakMap,U=new WeakMap,M=new WeakMap,O=new WeakMap,W=new WeakMap,D=new WeakMap,I=new WeakSet,P=function(){this.injectStyle("\n :host {\n\t\t\twidth: 100%;\n display: block;\n\t\t}\n\n\t\t#root {\n\t\t\theight: 100%;\n display: flex;\n flex-direction: column;\n\t\t}\n\n #content-root {\n all: initial;\n transition: opacity 200ms ease-in-out;\n }\n\n\t\t#root[data-theme] {\n\t\t\tbackground-color: transparent;\n\t\t}\n\n\t\t.fade-out {\n\t\t\topacity: 0.1!important;\n\t\t}\n\n .hidden {\n display: none;\n }\n ")},N=function(){t(this,I,"m",P).call(this),this.slotElement=document.createElement("slot"),this.slotElement.classList.add("hidden"),this.rootElement.appendChild(this.slotElement)},F=function(){const t=["base-url","tenant","locale","debug","redirect-url","auto-focus","store-last-authenticated-user","refresh-cookie-name","keep-last-authenticated-user-after-logout","preview","storage-prefix","form","client","validate-on-blur","style-id","outbound-app-id","outbound-app-scopes","theme-override"];j.observedAttributes.forEach((e=>{if(!t.includes(e)&&!this[c(e)])throw Error(`${e} cannot be empty`)}))},K=function(){const{stepId:e,executionId:i}=h(this.flowId);t(this,S,"f").update({stepId:e,executionId:i})},R=function(i,r){a&&"function"==typeof a||this.logger.error("SDK was not loaded properly",a,JSON.stringify(a));const o=Object.assign(Object.assign({persistTokens:!0,preview:this.preview,storagePrefix:this.storagePrefix,storeLastAuthenticatedUser:this.storeLastAuthenticatedUser,keepLastAuthenticatedUserAfterLogout:this.keepLastAuthenticatedUserAfterLogout,refreshCookieName:this.refreshCookieName},j.sdkConfigOverrides),{projectId:i,baseUrl:r});t(this,L,"f")&&(o.customStorage=t(this,L,"f")),this.sdk=a(o),["start","next"].forEach((t=>{const i=this.sdk.flow[t],r=p(i,1e3,3);this.sdk.flow[t]=(...i)=>e(this,void 0,void 0,(function*(){try{return yield r(...i)}catch(e){return this.logger.error(`Error in sdk flow ${t} function`,e),{error:{errorCode:x,errorDescription:e.toString()}}}}))}))},T=function(i,r,o){return e(this,void 0,void 0,(function*(){const{projectId:e,baseUrl:r}=i;if(o("projectId")||o("baseUrl")){if(!e)return;t(this,I,"m",R).call(this,e,r)}t(this,D,"f").call(this,i)}))},B=function(){return e(this,void 0,void 0,(function*(){const e=yield this.getConfig();return"isMissingConfig"in e&&e.isMissingConfig&&(yield t(this,I,"m",H).call(this))}))},H=function(){return e(this,void 0,void 0,(function*(){const t=f({projectId:this.projectId,filename:y,assetsFolder:A,baseUrl:this.baseStaticUrl});try{return yield g(t,"json"),!0}catch(t){return!1}}))},J=function(e){i(this,M,Object.assign(Object.assign({},t(this,M,"f")),e.detail),"f")},V=function(){var e;null===(e=t(this,O,"f"))||void 0===e||e.remove(),i(this,O,null,"f")},q=function(r){return e(this,arguments,void 0,(function*({isDebug:e}){e?(i(this,O,document.createElement("descope-debugger"),"f"),Object.assign(t(this,O,"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,O,"f"))):t(this,I,"m",V).call(this)}))},$=function(e,i){var r;e&&this.debug&&(null===(r=t(this,O,"f"))||void 0===r||r.updateData({title:e,description:i}))},Q.sdkConfigOverrides={baseHeaders:{"x-descope-sdk-name":"web-component","x-descope-sdk-version":"3.69.1"}};export{Q as default};
|
|
2
2
|
//# sourceMappingURL=BaseDescopeWc.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{__classPrivateFieldGet as e,__classPrivateFieldSet as t,__awaiter as i,__rest as s}from"tslib";import{getUserLocale as o}from"@descope/sdk-helpers";import{ensureFingerprintIds as r,clearFingerprintData as n}from"@descope/web-js-sdk";import{RESPONSE_ACTIONS as l,CUSTOM_INTERACTIONS as a,URL_CODE_PARAM_NAME as d,URL_ERR_PARAM_NAME as c,URL_TOKEN_PARAM_NAME as p,URL_RUN_IDS_PARAM_NAME as h,SDK_SCRIPTS_LOAD_TIMEOUT as u,DESCOPE_ATTRIBUTE_EXCLUDE_FIELD as g,ELEMENT_TYPE_ATTRIBUTE as v,DESCOPE_ATTRIBUTE_OPT_IN_LAST_USED as m,DESCOPE_LAST_AUTH_BADGE_COMPONENT as f,DESCOPE_ATTRIBUTE_EXCLUDE_NEXT_BUTTON as b}from"../constants/index.js";import{timeoutPromise as w,withMemCache as S,leadingDebounce as y,showFirstScreenOnExecutionInit as I,injectSamlIdpForm as R,injectWsFedIdpForm as C,openCenteredPopup as W,getAnimationDirection as k,handleAutoFocus as O,transformStepStateForCustomScreen as x,getElementDescopeAttributes as E,getScriptResultPath as A,submitForm as j,transformScreenInputs as T,handleReportValidityOnBlur as P,getFirstNonEmptyValue as U,clearPreviousExternalInputs as L}from"../helpers/helpers.js";import F from"../helpers/state.js";import{disableWebauthnButtons as $,updateTemplateFromScreenState as N,setComponentsAutoDetectByGeo as M,setComponentsAutoDetectByLocale as q,setTOTPVariable as V,setNOTPVariable as D,setCssVars as B,updateScreenFromScreenState as K,replaceElementMessage as H}from"../helpers/templates.js";import{isConditionalLoginSupported as _}from"../helpers/webauthn.js";import{getABTestingKey as G}from"../helpers/abTestingKey.js";import{calculateConditions as J,calculateCondition as z}from"../helpers/conditions.js";import{setLastAuth as Q,getInFlightLastUsedPerScreen as X,clearInFlightLastAuth as Y,getLastAuth as Z,updateLastUsedPerScreen as ee}from"../helpers/lastAuth.js";import te from"./BaseDescopeWc.js";import{FETCH_EXCEPTION_ERROR_CODE as ie,FETCH_ERROR_RESPONSE_ERROR_CODE as se,FLOW_REQUESTED_IS_IN_OLD_VERSION_ERROR_CODE as oe,FLOW_TIMED_OUT_ERROR_CODE as re,POLLING_STATUS_NOT_FOUND_ERROR_CODE as ne}from"../constants/general.js";var le,ae,de,ce,pe,he,ue,ge,ve,me,fe,be,we,Se,ye,Ie,Re,Ce,We,ke,Oe,xe,Ee,Ae,je,Te,Pe,Ue,Le,Fe,$e,Ne,Me,qe,Ve,De,Be,Ke,He,_e;class Ge extends te{static set sdkConfigOverrides(e){te.sdkConfigOverrides=e}static get sdkConfigOverrides(){return te.sdkConfigOverrides}constructor(){const s=new F({deferredRedirect:!1,deferredPolling:!1});super(s.update.bind(s)),le.add(this),this.stepState=new F({}),ae.set(this,void 0),de.set(this,null),ce.set(this,null),pe.set(this,{visibilitychange:e(this,le,"m",he).bind(this)}),this.bridgeVersion=2,this.nativeCallbacks={},Se.set(this,!1),this.handleRedirect=e=>{window.location.assign(e)},Ie.set(this,(t=>{const i=()=>{this.contentRootElement.classList.toggle("hidden",t),this.slotElement.classList.toggle("hidden",!t),t&&(this.contentRootElement.innerHTML="")};t&&this.contentRootElement.hasChildNodes()?e(this,le,"m",Re).call(this,i):i()})),Ce.set(this,((s,o,r,n,d=!1)=>{const c=[re,ne];if(this.flowState.current.action===l.poll){if(e(this,ke,"f").call(this)&&document.hidden)return this.logger.debug("polling - Deferring polling until in foreground"),void this.flowState.update({deferredPolling:!0});this.logger.debug("polling - Scheduling polling request");const l=Date.now(),p=d?500:2e3;t(this,ae,setTimeout((()=>i(this,void 0,void 0,(function*(){var t,i;this.logger.debug("polling - Calling next");const h=this.sdk.flow.next(s,o,a.polling,r,n,{}),u=document.hidden&&!d&&Date.now()-l>p+500;let g;u&&this.logger.debug("polling - The polling seems to be throttled");try{const e=u?1e3:6e3;g=yield w(e,h)}catch(t){return this.logger.warn(`polling - The ${u?"throttled fetch":"fetch"} call timed out or was aborted`),void e(this,Ce,"f").call(this,s,o,r,n,u)}if((null===(t=null==g?void 0:g.error)||void 0===t?void 0:t.errorCode)===ie)return this.logger.debug("polling - Got a generic error due to exception in fetch call"),void e(this,Ce,"f").call(this,s,o,r,n);this.logger.debug("polling - Got a response"),(null==g?void 0:g.error)&&this.logger.debug("polling - Response has an error",JSON.stringify(g.error,null,4)),(null===(i=null==g?void 0:g.error)||void 0===i?void 0:i.errorCode)&&c.includes(g.error.errorCode)?this.logger.debug("polling - Stopping polling due to error"):e(this,Ce,"f").call(this,s,o,r,n),e(this,Oe,"f").call(this,g)}))),p),"f")}})),We.set(this,(()=>{clearTimeout(e(this,ae,"f")),t(this,ae,null,"f")})),ke.set(this,(()=>!!window.descopeBridge||/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent))),Oe.set(this,(i=>{var s,o,r,n,a,d,c,p,h,u,g,v,m;if(!(null==i?void 0:i.ok)){const t=null===(s=null==i?void 0:i.response)||void 0===s?void 0:s.url,l=`${null===(o=null==i?void 0:i.response)||void 0===o?void 0:o.status} - ${null===(r=null==i?void 0:i.response)||void 0===r?void 0:r.statusText}`;e(this,le,"m",He).call(this,"error",(null==i?void 0:i.error)||{errorCode:se,errorDescription:l,errorMessage:t}),this.loggerWrapper.error((null===(n=null==i?void 0:i.error)||void 0===n?void 0:n.errorDescription)||t,(null===(a=null==i?void 0:i.error)||void 0===a?void 0:a.errorMessage)||l);const c=null===(d=null==i?void 0:i.error)||void 0===d?void 0:d.errorCode;return void(c!==oe&&c!==re||!this.isRestartOnError||e(this,le,"m",we).call(this))}null===(p=null===(c=i.data)||void 0===c?void 0:c.runnerLogs)||void 0===p||p.forEach((e=>{const{level:t,title:i,log:s}=e;t&&this.loggerWrapper[t]?this.loggerWrapper[t](i,s):this.loggerWrapper.info(i,s)}));const f=null===(g=null===(u=null===(h=i.data)||void 0===h?void 0:h.screen)||void 0===u?void 0:u.state)||void 0===g?void 0:g.errorText;(null===(v=i.data)||void 0===v?void 0:v.error)?this.loggerWrapper.error(`[${i.data.error.code}]: ${i.data.error.description}`,`${f?`${f} - `:""}${i.data.error.message}`):f&&this.loggerWrapper.error(f);const{status:b,authInfo:w,lastAuth:S,action:y,openInNewTabUrl:I}=i.data;if(y!==l.poll&&e(this,We,"f").call(this),"completed"===b){this.storeLastAuthenticatedUser&&Q(Object.assign(Object.assign({},S),{lastUsedPerScreen:X()})),Y(this.loggerWrapper);const t=Object.assign({},w);return i.data.output&&Object.keys(i.data.output).length>0&&(t.flowOutput=i.data.output),void e(this,le,"m",He).call(this,"success",t)}this.storeLastAuthenticatedUser&&Q(S,!0),I&&window.open(I,"_blank");const{executionId:R,stepId:C,stepName:W,screen:k,redirect:O,webauthn:x,error:E,samlIdpResponse:A,wsFedIdpResponse:j,nativeResponse:T}=i.data,P=Date.now();y!==l.poll?(this.loggerWrapper.info(`Step "${W||`#${C}`}" is ${b}`,"",{screen:k,status:b,stepId:C,stepName:W,action:y,error:E}),(null===(m=k.state)||void 0===m?void 0:m.clientScripts)&&t(this,ce,this.loadSdkScripts(k.state.clientScripts),"f"),this.flowState.update({stepId:C,stepName:W,executionId:R,action:y,redirectTo:null==O?void 0:O.url,redirectIsPopup:null==O?void 0:O.isPopup,screenId:null==k?void 0:k.id,screenState:null==k?void 0:k.state,webauthnTransactionId:null==x?void 0:x.transactionId,webauthnOptions:null==x?void 0:x.options,samlIdpResponseUrl:null==A?void 0:A.url,samlIdpResponseSamlResponse:null==A?void 0:A.samlResponse,samlIdpResponseRelayState:null==A?void 0:A.relayState,wsFedIdpResponseUrl:null==j?void 0:j.url,wsFedIdpResponseWresult:null==j?void 0:j.wresult,wsFedIdpResponseWctx:null==j?void 0:j.wctx,nativeResponseType:null==T?void 0:T.type,nativePayload:null==T?void 0:T.payload,reqTimestamp:P})):this.flowState.update({action:y,reqTimestamp:P})})),xe.set(this,S((()=>i(this,void 0,void 0,(function*(){var e;try{const t=yield this.sdk.webauthn.signIn.start("",window.location.origin);return t.ok||this.loggerWrapper.warn("Webauthn start failed",null===(e=null==t?void 0:t.error)||void 0===e?void 0:e.errorMessage),t.data}catch(e){this.loggerWrapper.warn("Webauthn start failed",e.message)}}))))),Ue.set(this,null),Me.set(this,y(((t,s,o)=>i(this,void 0,void 0,(function*(){var i;if("true"===t.getAttribute("formnovalidate")||e(this,le,"m",Te).call(this)){const r=null==t?void 0:t.getAttribute("id");e(this,le,"m",De).call(this,t,r,o),e(this,le,"m",Le).call(this,t);const n=yield e(this,le,"m",Pe).call(this),l=E(t);this.nextRequestStatus.update({isLoading:!0});const a=Object.assign(Object.assign(Object.assign({},l),n),{origin:(null===(i=this.nativeOptions)||void 0===i?void 0:i.origin)||window.location.origin});yield s(r,a),this.nextRequestStatus.update({isLoading:!1}),e(this,le,"m",Fe).call(this,n)}}))))),this.flowState=s}nativeResume(t,i){var s,o,r,n,l,a;const u=JSON.parse(i);if("oauthWeb"===t||"sso"===t){let e,{exchangeCode:t}=u;if(!t){const i=new URL(u.url);t=null===(s=i.searchParams)||void 0===s?void 0:s.get(d),e=(null===(o=i.searchParams)||void 0===o?void 0:o.get(c))||void 0}null===(n=(r=this.nativeCallbacks).complete)||void 0===n||n.call(r,{exchangeCode:t,exchangeError:e,idpInitiated:!0})}else if("magicLink"===t){const t=new URL(u.url),i=t.searchParams.get(p),s=t.searchParams.get(h).split("_").pop();e(this,We,"f").call(this),this.flowState.update({token:i,stepId:s,action:void 0})}else if("beforeScreen"===t){const{screenResolve:e}=this.nativeCallbacks;this.nativeCallbacks.screenResolve=null;const{override:t}=u;t||(this.nativeCallbacks.screenNext=null),null==e||e(t)}else if("resumeScreen"===t){const{interactionId:e,form:t}=u,{screenNext:i}=this.nativeCallbacks;this.nativeCallbacks.screenNext=null,null==i||i(e,t)}else null===(a=(l=this.nativeCallbacks).complete)||void 0===a||a.call(l,u)}loadSdkScriptsModules(){const e=this.shadowRoot.querySelectorAll("div[data-script-id]");return Array.from(e).map((e=>e.moduleRes)).filter((e=>!!e))}loadSdkScripts(e){if(!(null==e?void 0:e.length))return null;const t=(e,t)=>i=>{this.dispatchEvent(new CustomEvent("components-context",{detail:{[A(e.id,e.resultKey)]:i},bubbles:!0,composed:!0})),t(e.id)};this.loggerWrapper.debug(`Preparing to load scripts: ${e.map((e=>e.id)).join(", ")}`);const s=Promise.all(null==e?void 0:e.map((e=>i(this,void 0,void 0,(function*(){var i,s,o;const r=this.shadowRoot.querySelector(`[data-script-id="${e.id}"]`);if(r){this.loggerWrapper.debug("Script already loaded",e.id);const{moduleRes:t}=r;return null===(i=null==t?void 0:t.start)||void 0===i||i.call(t),t}(null===(s=globalThis.descope)||void 0===s?void 0:s[e.id])||(yield this.injectNpmLib("@descope/flow-scripts","1.0.16",`dist/${e.id}.js`));const n=null===(o=globalThis.descope)||void 0===o?void 0:o[e.id];return new Promise(((i,s)=>{try{const s=n(e.initArgs,{baseUrl:this.baseUrl,ref:this},t(e,i),this.loggerWrapper);if(s){const t=document.createElement("div");t.setAttribute("data-script-id",e.id),t.moduleRes=s,this.shadowRoot.appendChild(t);const i=this.nextRequestStatus.subscribe((()=>{var o;this.loggerWrapper.debug("Stopping script",e.id),(null===(o=s.stop)||void 0===o?void 0:o.call(s))&&(this.nextRequestStatus.unsubscribe(i),this.loggerWrapper.debug("Removing script",e.id),this.shadowRoot.removeChild(t))}))}}catch(e){s(e)}}))}))))),o=new Promise((e=>{setTimeout((()=>{this.loggerWrapper.warn("SDK scripts loading timeout"),e(!0)}),u)}));return Promise.race([s,o])}get isDismissScreenErrorOnInput(){return"true"===this.getAttribute("dismiss-screen-error-on-input")}init(){if(!window.descopeBridge)return this._init();this.lazyInit=this._init}_init(){const t=Object.create(null,{init:{get:()=>super.init}});return i(this,void 0,void 0,(function*(){var i,s;this.shadowRoot.isConnected&&(null===(i=this.flowState)||void 0===i||i.subscribe(this.onFlowChange.bind(this)),e(this,le,"m",fe).call(this),window.addEventListener("visibilitychange",e(this,pe,"f").visibilitychange)),yield null===(s=t.init)||void 0===s?void 0:s.call(this)}))}disconnectedCallback(){var i;super.disconnectedCallback(),this.flowState.unsubscribeAll(),this.stepState.unsubscribeAll(),e(this,We,"f").call(this),null===(i=e(this,de,"f"))||void 0===i||i.abort(),t(this,de,null,"f"),window.removeEventListener("visibilitychange",e(this,pe,"f").visibilitychange)}getHtmlFilenameWithLocale(e,t){return i(this,void 0,void 0,(function*(){let i;const s=o(e),r=yield this.getTargetLocales();return r.includes(s.locale)?i=`${t}-${s.locale}.html`:r.includes(s.fallback)&&(i=`${t}-${s.fallback}.html`),i}))}getPageContent(e,t){return i(this,void 0,void 0,(function*(){if(t)try{const{body:e}=yield this.fetchStaticResource(t,"text");return e}catch(i){this.loggerWrapper.error(`Failed to fetch flow page from ${t}. Fallback to url ${e}`,i)}try{const{body:t}=yield this.fetchStaticResource(e,"text");return t}catch(e){this.loggerWrapper.error("Failed to fetch flow page",e.message)}return null}))}onFlowChange(d,c,p){return i(this,void 0,void 0,(function*(){var h,u;const{projectId:g,flowId:v,tenant:m,stepId:f,executionId:b,action:w,screenId:S,screenState:y,redirectTo:O,redirectIsPopup:x,redirectUrl:E,token:A,code:P,isPopup:U,exchangeError:L,webauthnTransactionId:F,webauthnOptions:$,redirectAuthCodeChallenge:N,redirectAuthCallbackUrl:M,redirectAuthBackupCallbackUri:q,redirectAuthInitiator:V,locale:D,samlIdpResponseUrl:B,samlIdpResponseSamlResponse:K,samlIdpResponseRelayState:H,wsFedIdpResponseUrl:_,wsFedIdpResponseWresult:Q,wsFedIdpResponseWctx:X,nativeResponseType:ee,nativePayload:te,reqTimestamp:ie}=d,se=s(d,["projectId","flowId","tenant","stepId","executionId","action","screenId","screenState","redirectTo","redirectIsPopup","redirectUrl","token","code","isPopup","exchangeError","webauthnTransactionId","webauthnOptions","redirectAuthCodeChallenge","redirectAuthCallbackUrl","redirectAuthBackupCallbackUri","redirectAuthInitiator","locale","samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState","wsFedIdpResponseUrl","wsFedIdpResponseWresult","wsFedIdpResponseWctx","nativeResponseType","nativePayload","reqTimestamp"]);let oe,re,ne;const ae=G(),{outboundAppId:pe}=this,{outboundAppScopes:he}=this,ue=this.sdk.getLastUserLoginId(),ge=yield this.getFlowConfig(),me=yield this.getProjectConfig(),fe=Object.entries(me.flows||{}).reduce(((e,[t,i])=>(e[t]=i.version,e)),{}),be=M&&N?{callbackUrl:M,codeChallenge:N,backupCallbackUri:q}:void 0,we=this.nativeOptions?{platform:this.nativeOptions.platform,bridgeVersion:this.nativeOptions.bridgeVersion,oauthProvider:this.nativeOptions.oauthProvider,oauthRedirect:this.nativeOptions.oauthRedirect,magicLinkRedirect:this.nativeOptions.magicLinkRedirect,ssoRedirect:this.nativeOptions.ssoRedirect,externalAuthRedirect:this.nativeOptions.externalAuthRedirect}:void 0;let Se={};if(!b){Y(this.loggerWrapper);const i=[...ge.clientScripts||[],...ge.sdkScripts||[]];if(ge.conditions){let e=[];({startScreenId:oe,conditionInteractionId:ne,startScreenName:re,clientScripts:e,componentsConfig:Se}=J({loginId:ue,code:P,token:A,abTestingKey:ae,lastAuth:Z(ue,this.loggerWrapper)},ge.conditions)),i.push(...e||[])}else ge.condition?({startScreenId:oe,conditionInteractionId:ne}=z(ge.condition,{loginId:ue,code:P,token:A,abTestingKey:ae,lastAuth:Z(ue,this.loggerWrapper)})):(re=ge.startScreenName,oe=ge.startScreenId);if(t(this,ce,this.loadSdkScripts(i),"f"),ge.fingerprintEnabled&&ge.fingerprintKey?yield r(ge.fingerprintKey,this.baseUrl):n(),!I(oe,se)){const t=yield this.sdk.flow.start(v,Object.assign(Object.assign(Object.assign(Object.assign({tenant:m,redirectAuth:be},se),{client:this.client}),E&&{redirectUrl:E}),{lastAuth:Z(ue,this.loggerWrapper),abTestingKey:ae,locale:o(D).locale,nativeOptions:we,outboundAppId:pe,outboundAppScopes:he}),ne,"",me.componentsVersion,fe,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),P?{exchangeCode:P,idpInitiated:!0}:{}),se.descopeIdpInitiated&&{idpInitiated:!0}),A?{token:A}:{}),se.oidcLoginHint?{externalId:se.oidcLoginHint}:{}));return e(this,Oe,"f").call(this,t),void("completed"!==(null===(h=null==t?void 0:t.data)||void 0===h?void 0:h.status)&&this.flowState.update({code:void 0,token:void 0}))}}if(this.loggerWrapper.debug("Before popup postmessage send",JSON.stringify({isPopup:U,code:P,exchangeError:L,isCodeChanged:p("code"),isExchangeErrorChanged:p("exchangeError")})),U&&(p("code")&&P||p("exchangeError")&&L))return void e(this,le,"m",_e).call(this,b,P,L);if(b&&(p("token")&&A||p("code")&&P||p("exchangeError")&&L)){const t=yield this.sdk.flow.next(b,f,a.submit,ge.version,me.componentsVersion,{token:A,exchangeCode:P,exchangeError:L});return e(this,Oe,"f").call(this,t),void this.flowState.update({token:void 0,code:void 0,exchangeError:void 0})}if(w===l.loadForm&&B&&["samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState"].some((e=>p(e)))){if(!K)return void this.loggerWrapper.error("Did not get saml idp params data to load");R(B,K,H||"",j)}if(w===l.loadForm&&_&&["wsFedIdpResponseUrl","wsFedIdpResponseWresult","wsFedIdpResponseWctx"].some((e=>p(e)))){if(!Q)return void this.loggerWrapper.error("Did not get wsfed idp params data to load");C(_,Q,X||"",j)}if(w===l.redirect&&(p("redirectTo")||p("deferredRedirect"))){if(!O)return void this.loggerWrapper.error("Did not get redirect url");if("no-op"===O)return;if("android"===V&&document.hidden)return void this.flowState.update({deferredRedirect:!0});if(this.loggerWrapper.debug(`Redirect is popup ${x}`),x){this.loggerWrapper.debug("Opening redirect in popup");const t=W(O,"?",598,700),i=this.shouldUsePopupPostMessage();i&&(t.name=`descope-wc|${window.location.origin}`),this.loggerWrapper.debug("Popup communication method: "+(i?"postMessage":"BroadcastChannel"));const s=e=>{this.loggerWrapper.debug("Received popup message",JSON.stringify(e.data));const t=i?this.popupOrigin:window.location.origin;if(e.origin!==t)return void this.loggerWrapper.debug(`Ignoring message from unexpected origin. received: "${e.origin}", expected: "${t}"`);const{action:s,data:o}=e.data||{};"code"===s&&this.flowState.update({code:o.code,exchangeError:o.exchangeError})};let o;this.loggerWrapper.debug("Starting popup closed detection");const r=setInterval((()=>{t.closed&&(this.loggerWrapper.debug("Popup closed, dispatching popupclosed event"),clearInterval(r),e(this,le,"m",He).call(this,"popupclosed",{}),this.loggerWrapper.debug("Cleaning up popup listeners"),null==o||o())}),1e3);if(i)window.addEventListener("message",s),o=()=>{this.loggerWrapper.debug("Cleaning up popup postMessage listener"),window.removeEventListener("message",s)};else{this.loggerWrapper.debug("Creating broadcast channel");const e=new BroadcastChannel(b);e.onmessage=s,o=()=>{this.loggerWrapper.debug("Closing channel"),e.close()}}}else this.handleRedirect(O),this.flowState.update({redirectTo:"no-op"}),e(this,le,"m",He).call(this,"popupclosed",{});return}if(w===l.webauthnCreate||w===l.webauthnGet){if(!F||!$)return void this.loggerWrapper.error("Did not get webauthn transaction id or options");let i,s,o,r;null===(u=e(this,de,"f"))||void 0===u||u.abort(),t(this,de,null,"f");try{i=w===l.webauthnCreate?yield this.sdk.webauthn.helpers.create($):yield this.sdk.webauthn.helpers.get($)}catch(e){"InvalidStateError"===e.name?this.loggerWrapper.warn("WebAuthn operation failed",e.message):"NotAllowedError"!==e.name&&this.loggerWrapper.error(e.message),s=e.name,o=e.reason,r=e.message}const n=yield this.sdk.flow.next(b,f,a.submit,ge.version,me.componentsVersion,{transactionId:F,response:i,failure:s,failureReason:o,failureMessage:r});e(this,Oe,"f").call(this,n)}if(w===l.nativeBridge)return this.nativeCallbacks.complete=t=>i(this,void 0,void 0,(function*(){const i=yield this.sdk.flow.next(b,f,a.submit,ge.version,me.componentsVersion,t);e(this,Oe,"f").call(this,i)})),e(this,le,"m",ve).call(this,ee,te),void setTimeout((()=>{this.dispatchEvent(new Event("popupclosed"))}),500);if((p("action")||p("deferredPolling"))&&e(this,Ce,"f").call(this,b,f,ge.version,me.componentsVersion),!S&&!oe)return void this.loggerWrapper.warn("No screen was found to show");const Ie=oe||S,Re=yield this.getHtmlFilenameWithLocale(D,Ie),{oidcLoginHint:We,oidcPrompt:ke,oidcErrorRedirectUri:xe,oidcResource:Ee,samlIdpUsername:Ae}=se,je={direction:k(f,c.stepId),screenState:Object.assign(Object.assign({},y),{form:Object.assign(Object.assign({},this.formConfigValues),null==y?void 0:y.form),lastAuth:{loginId:ue,name:this.sdk.getLastUserDisplayName()||ue},componentsConfig:Object.assign(Object.assign(Object.assign({},ge.componentsConfig),Se),null==y?void 0:y.componentsConfig)}),htmlFilename:`${Ie}.html`,htmlLocaleFilename:Re,screenId:Ie,stepName:d.stepName||re,samlIdpUsername:Ae,oidcLoginHint:We,oidcPrompt:ke,oidcErrorRedirectUri:xe,oidcResource:Ee,action:w,locale:o(D).locale},Te=Z(ue,this.loggerWrapper);I(oe,se)?je.next=(t,s)=>i(this,void 0,void 0,(function*(){const i=(null==ge?void 0:ge.clientScripts)||[];yield e(this,le,"m",qe).call(this,i);const r=yield this.sdk.flow.start(v,Object.assign(Object.assign(Object.assign(Object.assign({tenant:m,redirectAuth:be},se),{lastAuth:Te,preview:this.preview,abTestingKey:ae,client:this.client}),E&&{redirectUrl:E}),{locale:o(D).locale,nativeOptions:we,outboundAppId:pe,outboundAppScopes:he}),ne,t,me.componentsVersion,fe,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),this.getComponentsContext()),T(s)),P&&{exchangeCode:P,idpInitiated:!0}),se.descopeIdpInitiated&&{idpInitiated:!0}),A&&{token:A}),je.next.isCustomScreen);return e(this,Oe,"f").call(this,r),r})):(p("projectId")||p("baseUrl")||p("executionId")||p("stepId"))&&(je.next=(t,s)=>i(this,void 0,void 0,(function*(){const i=(null==y?void 0:y.clientScripts)||[];yield e(this,le,"m",qe).call(this,i);const o=yield this.sdk.flow.next(b,f,t,ge.version,me.componentsVersion,Object.assign(Object.assign({},this.getComponentsContext()),T(s)),je.next.isCustomScreen);return e(this,Oe,"f").call(this,o),o}))),this.loggerWrapper.debug("Got a screen with id",je.screenId),yield e(this,le,"m",ye).call(this,je),this.stepState.update(je)}))}onStepChange(t,s){return i(this,void 0,void 0,(function*(){var o,r,n;const{htmlFilename:l,htmlLocaleFilename:d,direction:c,next:p,screenState:h,screenId:u}=t;this.loggerWrapper.debug("Rendering a flow screen");const g=document.createElement("template");g.innerHTML=yield this.getPageContent(l,d);const m=g.content.cloneNode(!0),f=this.loadDescopeUiComponents(g);this.sdk.webauthn.helpers.isSupported()?yield e(this,le,"m",Ae).call(this,m,p):$(m),!t.samlIdpUsername||(null===(o=h.form)||void 0===o?void 0:o.loginId)||(null===(r=h.form)||void 0===r?void 0:r.email)||(h.form||(h.form={}),h.form.loginId=t.samlIdpUsername,h.form.email=t.samlIdpUsername),N(m,h,this.formConfig,this.loggerWrapper),this.applyComponentsState(m,null==h?void 0:h.componentsState);const{geo:b}=null!==(n=yield this.getExecutionContext())&&void 0!==n?n:{};M(m,b),q(m,t.locale);const w=()=>i(this,void 0,void 0,(function*(){var i,o;yield f;const r=this.contentRootElement;V(r,null===(i=null==h?void 0:h.totp)||void 0===i?void 0:i.image),D(r,null===(o=null==h?void 0:h.notp)||void 0===o?void 0:o.image),B(r,m,h.cssVars,this.loggerWrapper),r.replaceChildren(m);const n=!s.htmlFilename;setTimeout((()=>{e(this,le,"m",$e).call(this),this.validateOnBlur&&P(r),K(r,h),this.initRealtimeConditions(r,h),e(this,le,"m",je).call(this,{isFirstScreen:n,isCustomScreen:!1,stepName:t.stepName}),O(r,this.autoFocus,n),e(this,le,"m",Be).call(this,u)})),e(this,le,"m",Ke).call(this,p,u);r.querySelector(`[${v}="polling"]`)&&p(a.polling,{})}));c?e(this,le,"m",Re).call(this,w):w()}))}getInputs(){return Array.from(this.shadowRoot.querySelectorAll(`*:not(slot)[name]:not([${g}])`))}shouldUsePopupPostMessage(){if(!this.popupOrigin)return!1;try{new URL(this.popupOrigin)}catch(e){return!1}return!0}}ae=new WeakMap,de=new WeakMap,ce=new WeakMap,pe=new WeakMap,Se=new WeakMap,Ie=new WeakMap,Ce=new WeakMap,We=new WeakMap,ke=new WeakMap,Oe=new WeakMap,xe=new WeakMap,Ue=new WeakMap,Me=new WeakMap,le=new WeakSet,he=function(){document.hidden||setTimeout((()=>{this.flowState.update({deferredRedirect:!1,deferredPolling:!1})}),300)},ue=function(t,s,o){return i(this,void 0,void 0,(function*(){var i;return(null===(i=this.nativeOptions)||void 0===i?void 0:i.bridgeVersion)>=2&&new Promise((i=>{this.nativeCallbacks.screenNext=o,this.nativeCallbacks.screenResolve=i,e(this,le,"m",ve).call(this,"beforeScreen",{screen:t,context:s})}))}))},ge=function(t){var i;(null===(i=this.nativeOptions)||void 0===i?void 0:i.bridgeVersion)>=2&&e(this,le,"m",ve).call(this,"afterScreen",{screen:t})},ve=function(t,i){e(this,le,"m",He).call(this,"bridge",{type:t,payload:i})},me=function({errorText:e,errorType:t}){const i=()=>{var i;let s=e;try{s=(null===(i=this.errorTransformer)||void 0===i?void 0:i.call(this,{text:e,type:t}))||e}catch(e){this.loggerWrapper.error("Error transforming error message",e.message)}H(this.contentRootElement,"error-message",s)};this.addEventListener("screen-updated",i,{once:!0}),i()},fe=function(){var t,i,o;null===(t=this.stepState)||void 0===t||t.subscribe(this.onStepChange.bind(this),(e=>{var t=e.screenState,i=s(void 0===t?{}:t,["errorText","errorType"]),o=s(e,["screenState"]);return Object.assign(Object.assign({},o),{screenState:i})})),null===(i=this.stepState)||void 0===i||i.subscribe(e(this,le,"m",me).bind(this),(e=>{var t,i;return{errorText:null===(t=null==e?void 0:e.screenState)||void 0===t?void 0:t.errorText,errorType:null===(i=null==e?void 0:e.screenState)||void 0===i?void 0:i.errorType}}),{forceUpdate:!0}),null===(o=this.stepState)||void 0===o||o.subscribe(e(this,le,"m",be).bind(this),(e=>{var t,i;return{errorText:null===(t=null==e?void 0:e.screenState)||void 0===t?void 0:t.errorText,errorType:null===(i=null==e?void 0:e.screenState)||void 0===i?void 0:i.errorType}}),{forceUpdate:!0})},be=function({errorText:e,errorType:t}){(t||e)&&(this.contentRootElement.querySelectorAll('descope-passcode[data-auto-submit="true"]').forEach((e=>{e.shadowRoot.querySelectorAll("descope-text-field[data-id]").forEach((e=>{e.value=""}))})),O(this.contentRootElement,this.autoFocus,!1))},we=function(){return i(this,void 0,void 0,(function*(){this.loggerWrapper.debug("Trying to restart the flow");const e=yield this.getComponentsVersion();this.reset();e===(yield this.getComponentsVersion())?(this.loggerWrapper.debug("Components version was not changed, restarting flow"),this.flowState.update({stepId:null,executionId:null})):this.loggerWrapper.error("Components version mismatch, please reload the page")}))},ye=function(o){return i(this,void 0,void 0,(function*(){var i;const r=Object.assign(Object.assign({},this.stepState.current),o),{next:n,stepName:l}=r,a=s(r,["next","stepName"]),d=x(a);let c=yield e(this,le,"m",ue).call(this,l,d,n);c||(c=Boolean(yield null===(i=this.onScreenUpdate)||void 0===i?void 0:i.call(this,l,d,n,this)));const p=!this.stepState.current.htmlFilename;if(e(this,Ie,"f").call(this,c),n&&(n.isCustomScreen=c),e(this,Se,"f")!==c){const[i,s]=["flow","custom"].sort((()=>c?-1:1));this.loggerWrapper.debug(`Switching from ${s} screen to ${i} screen`),t(this,Se,c,"f"),c?this.stepState.unsubscribeAll():e(this,le,"m",fe).call(this)}c?(this.loggerWrapper.debug("Showing a custom screen"),e(this,le,"m",je).call(this,{isFirstScreen:p,isCustomScreen:c,stepName:o.stepName}),this.disableKeyPressHandler()):this.handleKeyPress(),this.stepState.forceUpdate=c}))},Re=function(e){this.contentRootElement.addEventListener("transitionend",(()=>{this.loggerWrapper.debug("page switch transition end"),this.contentRootElement.classList.remove("fade-out"),e()}),{once:!0}),this.loggerWrapper.debug("page switch transition start"),this.contentRootElement.classList.add("fade-out")},Ee=function(e){const t=e.getAttribute("name");if(!["email"].includes(t)){const i=`user-${t}`;e.setAttribute("name",i),e.addEventListener("input",(()=>{e.setAttribute("name",e.value?t:i)}))}},Ae=function(s,o){return i(this,void 0,void 0,(function*(){var r;null===(r=e(this,de,"f"))||void 0===r||r.abort();const n=s.querySelector('*[autocomplete="webauthn"]');if(n&&(yield _())){const{options:s,transactionId:r}=(yield e(this,xe,"f").call(this))||{};s&&r&&(e(this,le,"m",Ee).call(this,n),t(this,de,new AbortController,"f"),this.sdk.webauthn.helpers.conditional(s,e(this,de,"f")).then((e=>i(this,void 0,void 0,(function*(){o(n.id,{transactionId:r,response:e})})))).catch((e=>{"AbortError"!==e.name&&this.loggerWrapper.error("Conditional login failed",e.message)})))}}))},je=function({isFirstScreen:t,isCustomScreen:i,stepName:s}){t&&e(this,le,"m",He).call(this,"ready",{}),i||e(this,le,"m",ge).call(this,s),e(this,le,"m",He).call(this,"page-updated",{screenName:s}),e(this,le,"m",He).call(this,"screen-updated",{screenName:s})},Te=function(){let e=!0;return Array.from(this.shadowRoot.querySelectorAll("*[name]")).reverse().forEach((t=>{var i,s;"slot"===t.localName||t.classList.contains("hidden")||(null===(i=t.reportValidity)||void 0===i||i.call(t),e&&(e=null===(s=t.checkValidity)||void 0===s?void 0:s.call(t)))})),e},Pe=function(){return i(this,void 0,void 0,(function*(){const e=this.getInputs();return(yield Promise.all(e.map((e=>i(this,void 0,void 0,(function*(){return{name:e.getAttribute("name"),value:e.value}})))))).reduce(((e,t)=>Object.assign(Object.assign({},e),{[t.name]:t.value})),{})}))},Le=function(s){const o=Array.from(this.contentRootElement.querySelectorAll(':not([disabled]), [disabled="false"]')).filter((e=>e!==s)),r=()=>i(this,void 0,void 0,(function*(){this.loggerWrapper.debug("Restoring components state"),this.removeEventListener("popupclosed",r),s.removeAttribute("loading"),o.forEach((e=>{e.removeAttribute("disabled")}));const e=yield this.getFlowConfig(),t=[...e.clientScripts||[],...e.sdkScripts||[]];this.loadSdkScripts(t)})),n=()=>{var i;window.removeEventListener("pageshow",e(this,Ue,"f")),t(this,Ue,(e=>{e.persisted&&(this.logger.debug("Page was loaded from cache, restoring components state"),r())}),"f"),window.addEventListener("pageshow",e(this,Ue,"f"),{once:!0});const s=null===(i=this.stepState)||void 0===i?void 0:i.subscribe(((e,t)=>{e===t&&r(),this.removeEventListener("popupclosed",r),this.stepState.unsubscribe(s)}),(e=>e.screenId),{forceUpdate:!0})},l=this.nextRequestStatus.subscribe((({isLoading:e})=>{e?(this.addEventListener("popupclosed",r,{once:!0}),s.setAttribute("loading","true"),o.forEach((e=>e.setAttribute("disabled","true")))):(this.nextRequestStatus.unsubscribe(l),n())}))},Fe=function(e={}){var t,i;const s=U(e,["externalId","email","phone"]),o=U(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)}},$e=function(){L();this.contentRootElement.querySelectorAll('[external-input="true"]').forEach((t=>e(this,le,"m",Ne).call(this,t)))},Ne=function(e){if(!e)return;e.querySelectorAll("input").forEach((t=>{const i=t.getAttribute("slot"),s=`input-${e.id}-${i}`,o=document.createElement("slot");o.setAttribute("name",s),o.setAttribute("slot",i),e.appendChild(o),t.setAttribute("slot",s),this.appendChild(t)}))},qe=function(t){return i(this,void 0,void 0,(function*(){if(e(this,ce,"f")){this.loggerWrapper.debug("Waiting for sdk scripts to load");const t=Date.now();yield e(this,ce,"f"),this.loggerWrapper.debug("Sdk scripts loaded for",(Date.now()-t).toString())}const i=this.loadSdkScriptsModules(),s=t.map((e=>e.id));for(const e of i)if(s.includes(e.id))try{if("function"==typeof e.present){(yield e.present())||this.loggerWrapper.debug(`Sdk script ${e.id} was cancelled`)}}catch(t){this.loggerWrapper.error(`Failed to present ${e.id} script module`,t.message)}const o=[];for(const e of i)"function"==typeof e.refresh&&o.push(e.refresh());if(o.length>0)try{yield w(u,Promise.all(o),null)}catch(e){this.loggerWrapper.error("Failed to refresh script module",e.message)}}))},Ve=function(t,i){this.contentRootElement.querySelectorAll('descope-passcode[data-auto-submit="true"]').forEach((s=>{s.addEventListener("input",(()=>{var o;(null===(o=s.checkValidity)||void 0===o?void 0:o.call(s))&&e(this,Me,"f").call(this,s,t,i)}))}))},De=function(e,t,i){t&&i&&"true"===e.getAttribute(m)&&ee(i,t,this.loggerWrapper)},Be=function(e){var t;const i=this.sdk.getLastUserLoginId(),s=null===(t=Z(i,this.loggerWrapper).lastUsedPerScreen)||void 0===t?void 0:t[e];if(!s)return;const o=this.contentRootElement.querySelector(f),r=this.contentRootElement.querySelector(`#${CSS.escape(s)}`);o&&r&&(r.replaceWith(o),o.appendChild(r))},Ke=function(t,i){this.contentRootElement.querySelectorAll(`descope-button:not([${b}]), [data-type="button"]:not([${b}]`).forEach((s=>{s.onclick=()=>{e(this,Me,"f").call(this,s,t,i)}})),e(this,le,"m",Ve).call(this,t,i),this.isDismissScreenErrorOnInput&&this.contentRootElement.querySelectorAll(`*[name]:not([${g}])`).forEach((e=>{e.addEventListener("input",(()=>{this.stepState.update((e=>Object.assign(Object.assign({},e),{screenState:Object.assign(Object.assign({},e.screenState),{errorText:"",errorType:""})})))}))}))},He=function(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t}))},_e=function(e,t,i){var s;const[o,r]=(null===(s=window.name)||void 0===s?void 0:s.split("|"))||[],n={data:{code:t,exchangeError:i},action:"code"};if("descope-wc"===o&&r){this.loggerWrapper.debug("Using postMessage fallback to notify opener in origin",r);try{window.opener.postMessage(n,r)}catch(e){this.loggerWrapper.error("Failed to send postMessage fallback (likely COOP isolation)",null==e?void 0:e.message)}}else{this.loggerWrapper.debug("Creating popup channel",e);const t=new BroadcastChannel(e);t.postMessage(n),t.close()}try{window.close()}catch(e){}};export{Ge as default};
|
|
1
|
+
import{__classPrivateFieldGet as e,__classPrivateFieldSet as t,__awaiter as i,__rest as s}from"tslib";import{getUserLocale as o}from"@descope/sdk-helpers";import{ensureFingerprintIds as r,clearFingerprintData as n}from"@descope/web-js-sdk";import{RESPONSE_ACTIONS as l,CUSTOM_INTERACTIONS as a,URL_CODE_PARAM_NAME as d,URL_ERR_PARAM_NAME as c,URL_TOKEN_PARAM_NAME as p,URL_RUN_IDS_PARAM_NAME as h,SDK_SCRIPTS_LOAD_TIMEOUT as u,DESCOPE_ATTRIBUTE_EXCLUDE_FIELD as g,ELEMENT_TYPE_ATTRIBUTE as v,DESCOPE_ATTRIBUTE_OPT_IN_LAST_USED as m,DESCOPE_LAST_AUTH_BADGE_COMPONENT as f,DESCOPE_ATTRIBUTE_EXCLUDE_NEXT_BUTTON as b}from"../constants/index.js";import{timeoutPromise as w,withMemCache as S,leadingDebounce as y,showFirstScreenOnExecutionInit as I,injectSamlIdpForm as R,injectWsFedIdpForm as C,openCenteredPopup as W,getAnimationDirection as k,handleAutoFocus as O,transformStepStateForCustomScreen as x,getElementDescopeAttributes as E,getScriptResultPath as A,submitForm as j,transformScreenInputs as T,handleReportValidityOnBlur as P,getFirstNonEmptyValue as U,clearPreviousExternalInputs as L}from"../helpers/helpers.js";import F from"../helpers/state.js";import{disableWebauthnButtons as $,updateTemplateFromScreenState as N,setComponentsAutoDetectByGeo as M,setComponentsAutoDetectByLocale as q,setTOTPVariable as V,setNOTPVariable as D,setCssVars as B,updateScreenFromScreenState as K,replaceElementMessage as H}from"../helpers/templates.js";import{isConditionalLoginSupported as _}from"../helpers/webauthn.js";import{getABTestingKey as G}from"../helpers/abTestingKey.js";import{calculateConditions as J,calculateCondition as z}from"../helpers/conditions.js";import{setLastAuth as Q,getInFlightLastUsedPerScreen as X,clearInFlightLastAuth as Y,getLastAuth as Z,updateLastUsedPerScreen as ee}from"../helpers/lastAuth.js";import te from"./BaseDescopeWc.js";import{FETCH_EXCEPTION_ERROR_CODE as ie,FETCH_ERROR_RESPONSE_ERROR_CODE as se,FLOW_REQUESTED_IS_IN_OLD_VERSION_ERROR_CODE as oe,FLOW_TIMED_OUT_ERROR_CODE as re,POLLING_STATUS_NOT_FOUND_ERROR_CODE as ne}from"../constants/general.js";var le,ae,de,ce,pe,he,ue,ge,ve,me,fe,be,we,Se,ye,Ie,Re,Ce,We,ke,Oe,xe,Ee,Ae,je,Te,Pe,Ue,Le,Fe,$e,Ne,Me,qe,Ve,De,Be,Ke,He,_e;class Ge extends te{static set sdkConfigOverrides(e){te.sdkConfigOverrides=e}static get sdkConfigOverrides(){return te.sdkConfigOverrides}constructor(){const s=new F({deferredRedirect:!1,deferredPolling:!1});super(s.update.bind(s)),le.add(this),this.stepState=new F({}),ae.set(this,void 0),de.set(this,null),ce.set(this,null),pe.set(this,{visibilitychange:e(this,le,"m",he).bind(this)}),this.bridgeVersion=2,this.nativeCallbacks={},Se.set(this,!1),this.handleRedirect=e=>{window.location.assign(e)},Ie.set(this,(t=>{const i=()=>{this.contentRootElement.classList.toggle("hidden",t),this.slotElement.classList.toggle("hidden",!t),t&&(this.contentRootElement.innerHTML="")};t&&this.contentRootElement.hasChildNodes()?e(this,le,"m",Re).call(this,i):i()})),Ce.set(this,((s,o,r,n,d=!1)=>{const c=[re,ne];if(this.flowState.current.action===l.poll){if(e(this,ke,"f").call(this)&&document.hidden)return this.logger.debug("polling - Deferring polling until in foreground"),void this.flowState.update({deferredPolling:!0});this.logger.debug("polling - Scheduling polling request");const l=Date.now(),p=d?500:2e3;t(this,ae,setTimeout((()=>i(this,void 0,void 0,(function*(){var t,i;this.logger.debug("polling - Calling next");const h=this.sdk.flow.next(s,o,a.polling,r,n,{}),u=document.hidden&&!d&&Date.now()-l>p+500;let g;u&&this.logger.debug("polling - The polling seems to be throttled");try{const e=u?1e3:6e3;g=yield w(e,h)}catch(t){return this.logger.warn(`polling - The ${u?"throttled fetch":"fetch"} call timed out or was aborted`),void e(this,Ce,"f").call(this,s,o,r,n,u)}if((null===(t=null==g?void 0:g.error)||void 0===t?void 0:t.errorCode)===ie)return this.logger.debug("polling - Got a generic error due to exception in fetch call"),void e(this,Ce,"f").call(this,s,o,r,n);this.logger.debug("polling - Got a response"),(null==g?void 0:g.error)&&this.logger.debug("polling - Response has an error",JSON.stringify(g.error,null,4)),(null===(i=null==g?void 0:g.error)||void 0===i?void 0:i.errorCode)&&c.includes(g.error.errorCode)?this.logger.debug("polling - Stopping polling due to error"):e(this,Ce,"f").call(this,s,o,r,n),e(this,Oe,"f").call(this,g)}))),p),"f")}})),We.set(this,(()=>{clearTimeout(e(this,ae,"f")),t(this,ae,null,"f")})),ke.set(this,(()=>!!window.descopeBridge||/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent))),Oe.set(this,(i=>{var s,o,r,n,a,d,c,p,h,u,g,v,m;if(!(null==i?void 0:i.ok)){const t=null===(s=null==i?void 0:i.response)||void 0===s?void 0:s.url,l=`${null===(o=null==i?void 0:i.response)||void 0===o?void 0:o.status} - ${null===(r=null==i?void 0:i.response)||void 0===r?void 0:r.statusText}`;e(this,le,"m",He).call(this,"error",(null==i?void 0:i.error)||{errorCode:se,errorDescription:l,errorMessage:t}),this.loggerWrapper.error((null===(n=null==i?void 0:i.error)||void 0===n?void 0:n.errorDescription)||t,(null===(a=null==i?void 0:i.error)||void 0===a?void 0:a.errorMessage)||l);const c=null===(d=null==i?void 0:i.error)||void 0===d?void 0:d.errorCode;return void(c!==oe&&c!==re||!this.isRestartOnError||e(this,le,"m",we).call(this))}null===(p=null===(c=i.data)||void 0===c?void 0:c.runnerLogs)||void 0===p||p.forEach((e=>{const{level:t,title:i,log:s}=e;t&&this.loggerWrapper[t]?this.loggerWrapper[t](i,s):this.loggerWrapper.info(i,s)}));const f=null===(g=null===(u=null===(h=i.data)||void 0===h?void 0:h.screen)||void 0===u?void 0:u.state)||void 0===g?void 0:g.errorText;(null===(v=i.data)||void 0===v?void 0:v.error)?this.loggerWrapper.error(`[${i.data.error.code}]: ${i.data.error.description}`,`${f?`${f} - `:""}${i.data.error.message}`):f&&this.loggerWrapper.error(f);const{status:b,authInfo:w,lastAuth:S,action:y,openInNewTabUrl:I}=i.data;if(y!==l.poll&&e(this,We,"f").call(this),"completed"===b){this.storeLastAuthenticatedUser&&Q(Object.assign(Object.assign({},S),{lastUsedPerScreen:X()})),Y(this.loggerWrapper);const t=Object.assign({},w);return i.data.output&&Object.keys(i.data.output).length>0&&(t.flowOutput=i.data.output),void e(this,le,"m",He).call(this,"success",t)}this.storeLastAuthenticatedUser&&Q(S,!0),I&&window.open(I,"_blank");const{executionId:R,stepId:C,stepName:W,screen:k,redirect:O,webauthn:x,error:E,samlIdpResponse:A,wsFedIdpResponse:j,nativeResponse:T}=i.data,P=Date.now();y!==l.poll?(this.loggerWrapper.info(`Step "${W||`#${C}`}" is ${b}`,"",{screen:k,status:b,stepId:C,stepName:W,action:y,error:E}),(null===(m=k.state)||void 0===m?void 0:m.clientScripts)&&t(this,ce,this.loadSdkScripts(k.state.clientScripts),"f"),this.flowState.update({stepId:C,stepName:W,executionId:R,action:y,redirectTo:null==O?void 0:O.url,redirectIsPopup:null==O?void 0:O.isPopup,screenId:null==k?void 0:k.id,screenState:null==k?void 0:k.state,webauthnTransactionId:null==x?void 0:x.transactionId,webauthnOptions:null==x?void 0:x.options,samlIdpResponseUrl:null==A?void 0:A.url,samlIdpResponseSamlResponse:null==A?void 0:A.samlResponse,samlIdpResponseRelayState:null==A?void 0:A.relayState,wsFedIdpResponseUrl:null==j?void 0:j.url,wsFedIdpResponseWresult:null==j?void 0:j.wresult,wsFedIdpResponseWctx:null==j?void 0:j.wctx,nativeResponseType:null==T?void 0:T.type,nativePayload:null==T?void 0:T.payload,reqTimestamp:P})):this.flowState.update({action:y,reqTimestamp:P})})),xe.set(this,S((()=>i(this,void 0,void 0,(function*(){var e;try{const t=yield this.sdk.webauthn.signIn.start("",window.location.origin);return t.ok||this.loggerWrapper.warn("Webauthn start failed",null===(e=null==t?void 0:t.error)||void 0===e?void 0:e.errorMessage),t.data}catch(e){this.loggerWrapper.warn("Webauthn start failed",e.message)}}))))),Ue.set(this,null),Me.set(this,y(((t,s,o)=>i(this,void 0,void 0,(function*(){var i;if("true"===t.getAttribute("formnovalidate")||e(this,le,"m",Te).call(this)){const r=null==t?void 0:t.getAttribute("id");e(this,le,"m",De).call(this,t,r,o),e(this,le,"m",Le).call(this,t);const n=yield e(this,le,"m",Pe).call(this),l=E(t);this.nextRequestStatus.update({isLoading:!0});const a=Object.assign(Object.assign(Object.assign({},l),n),{origin:(null===(i=this.nativeOptions)||void 0===i?void 0:i.origin)||window.location.origin});yield s(r,a),this.nextRequestStatus.update({isLoading:!1}),e(this,le,"m",Fe).call(this,n)}}))))),this.flowState=s}nativeResume(t,i){var s,o,r,n,l,a;const u=JSON.parse(i);if("oauthWeb"===t||"sso"===t){let e,{exchangeCode:t}=u;if(!t){const i=new URL(u.url);t=null===(s=i.searchParams)||void 0===s?void 0:s.get(d),e=(null===(o=i.searchParams)||void 0===o?void 0:o.get(c))||void 0}null===(n=(r=this.nativeCallbacks).complete)||void 0===n||n.call(r,{exchangeCode:t,exchangeError:e,idpInitiated:!0})}else if("magicLink"===t){const t=new URL(u.url),i=t.searchParams.get(p),s=t.searchParams.get(h).split("_").pop();e(this,We,"f").call(this),this.flowState.update({token:i,stepId:s,action:void 0})}else if("beforeScreen"===t){const{screenResolve:e}=this.nativeCallbacks;this.nativeCallbacks.screenResolve=null;const{override:t}=u;t||(this.nativeCallbacks.screenNext=null),null==e||e(t)}else if("resumeScreen"===t){const{interactionId:e,form:t}=u,{screenNext:i}=this.nativeCallbacks;this.nativeCallbacks.screenNext=null,null==i||i(e,t)}else null===(a=(l=this.nativeCallbacks).complete)||void 0===a||a.call(l,u)}loadSdkScriptsModules(){const e=this.shadowRoot.querySelectorAll("div[data-script-id]");return Array.from(e).map((e=>e.moduleRes)).filter((e=>!!e))}loadSdkScripts(e){if(!(null==e?void 0:e.length))return null;const t=(e,t)=>i=>{this.dispatchEvent(new CustomEvent("components-context",{detail:{[A(e.id,e.resultKey)]:i},bubbles:!0,composed:!0})),t(e.id)};this.loggerWrapper.debug(`Preparing to load scripts: ${e.map((e=>e.id)).join(", ")}`);const s=Promise.all(null==e?void 0:e.map((e=>i(this,void 0,void 0,(function*(){var i,s,o;const r=this.shadowRoot.querySelector(`[data-script-id="${e.id}"]`);if(r){this.loggerWrapper.debug("Script already loaded",e.id);const{moduleRes:t}=r;return null===(i=null==t?void 0:t.start)||void 0===i||i.call(t),t}(null===(s=globalThis.descope)||void 0===s?void 0:s[e.id])||(yield this.injectNpmLib("@descope/flow-scripts","1.0.17",`dist/${e.id}.js`));const n=null===(o=globalThis.descope)||void 0===o?void 0:o[e.id];return new Promise(((i,s)=>{try{const s=n(e.initArgs,{baseUrl:this.baseUrl,ref:this},t(e,i),this.loggerWrapper);if(s){const t=document.createElement("div");t.setAttribute("data-script-id",e.id),t.moduleRes=s,this.shadowRoot.appendChild(t);const i=this.nextRequestStatus.subscribe((()=>{var o;this.loggerWrapper.debug("Stopping script",e.id),(null===(o=s.stop)||void 0===o?void 0:o.call(s))&&(this.nextRequestStatus.unsubscribe(i),this.loggerWrapper.debug("Removing script",e.id),this.shadowRoot.removeChild(t))}))}}catch(e){s(e)}}))}))))),o=new Promise((e=>{setTimeout((()=>{this.loggerWrapper.warn("SDK scripts loading timeout"),e(!0)}),u)}));return Promise.race([s,o])}get isDismissScreenErrorOnInput(){return"true"===this.getAttribute("dismiss-screen-error-on-input")}init(){if(!window.descopeBridge)return this._init();this.lazyInit=this._init}_init(){const t=Object.create(null,{init:{get:()=>super.init}});return i(this,void 0,void 0,(function*(){var i,s;this.shadowRoot.isConnected&&(null===(i=this.flowState)||void 0===i||i.subscribe(this.onFlowChange.bind(this)),e(this,le,"m",fe).call(this),window.addEventListener("visibilitychange",e(this,pe,"f").visibilitychange)),yield null===(s=t.init)||void 0===s?void 0:s.call(this)}))}disconnectedCallback(){var i;super.disconnectedCallback(),this.flowState.unsubscribeAll(),this.stepState.unsubscribeAll(),e(this,We,"f").call(this),null===(i=e(this,de,"f"))||void 0===i||i.abort(),t(this,de,null,"f"),window.removeEventListener("visibilitychange",e(this,pe,"f").visibilitychange)}getHtmlFilenameWithLocale(e,t){return i(this,void 0,void 0,(function*(){let i;const s=o(e),r=yield this.getTargetLocales();return r.includes(s.locale)?i=`${t}-${s.locale}.html`:r.includes(s.fallback)&&(i=`${t}-${s.fallback}.html`),i}))}getPageContent(e,t){return i(this,void 0,void 0,(function*(){if(t)try{const{body:e}=yield this.fetchStaticResource(t,"text");return e}catch(i){this.loggerWrapper.error(`Failed to fetch flow page from ${t}. Fallback to url ${e}`,i)}try{const{body:t}=yield this.fetchStaticResource(e,"text");return t}catch(e){this.loggerWrapper.error("Failed to fetch flow page",e.message)}return null}))}onFlowChange(d,c,p){return i(this,void 0,void 0,(function*(){var h,u;const{projectId:g,flowId:v,tenant:m,stepId:f,executionId:b,action:w,screenId:S,screenState:y,redirectTo:O,redirectIsPopup:x,redirectUrl:E,token:A,code:P,isPopup:U,exchangeError:L,webauthnTransactionId:F,webauthnOptions:$,redirectAuthCodeChallenge:N,redirectAuthCallbackUrl:M,redirectAuthBackupCallbackUri:q,redirectAuthInitiator:V,locale:D,samlIdpResponseUrl:B,samlIdpResponseSamlResponse:K,samlIdpResponseRelayState:H,wsFedIdpResponseUrl:_,wsFedIdpResponseWresult:Q,wsFedIdpResponseWctx:X,nativeResponseType:ee,nativePayload:te,reqTimestamp:ie}=d,se=s(d,["projectId","flowId","tenant","stepId","executionId","action","screenId","screenState","redirectTo","redirectIsPopup","redirectUrl","token","code","isPopup","exchangeError","webauthnTransactionId","webauthnOptions","redirectAuthCodeChallenge","redirectAuthCallbackUrl","redirectAuthBackupCallbackUri","redirectAuthInitiator","locale","samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState","wsFedIdpResponseUrl","wsFedIdpResponseWresult","wsFedIdpResponseWctx","nativeResponseType","nativePayload","reqTimestamp"]);let oe,re,ne;const ae=G(),{outboundAppId:pe}=this,{outboundAppScopes:he}=this,ue=this.sdk.getLastUserLoginId(),ge=yield this.getFlowConfig(),me=yield this.getProjectConfig(),fe=Object.entries(me.flows||{}).reduce(((e,[t,i])=>(e[t]=i.version,e)),{}),be=M&&N?{callbackUrl:M,codeChallenge:N,backupCallbackUri:q}:void 0,we=this.nativeOptions?{platform:this.nativeOptions.platform,bridgeVersion:this.nativeOptions.bridgeVersion,oauthProvider:this.nativeOptions.oauthProvider,oauthRedirect:this.nativeOptions.oauthRedirect,magicLinkRedirect:this.nativeOptions.magicLinkRedirect,ssoRedirect:this.nativeOptions.ssoRedirect,externalAuthRedirect:this.nativeOptions.externalAuthRedirect}:void 0;let Se={};if(!b){Y(this.loggerWrapper);const i=[...ge.clientScripts||[],...ge.sdkScripts||[]];if(ge.conditions){let e=[];({startScreenId:oe,conditionInteractionId:ne,startScreenName:re,clientScripts:e,componentsConfig:Se}=J({loginId:ue,code:P,token:A,abTestingKey:ae,lastAuth:Z(ue,this.loggerWrapper)},ge.conditions)),i.push(...e||[])}else ge.condition?({startScreenId:oe,conditionInteractionId:ne}=z(ge.condition,{loginId:ue,code:P,token:A,abTestingKey:ae,lastAuth:Z(ue,this.loggerWrapper)})):(re=ge.startScreenName,oe=ge.startScreenId);if(t(this,ce,this.loadSdkScripts(i),"f"),ge.fingerprintEnabled&&ge.fingerprintKey?yield r(ge.fingerprintKey,this.baseUrl):n(),!I(oe,se)){const t=yield this.sdk.flow.start(v,Object.assign(Object.assign(Object.assign(Object.assign({tenant:m,redirectAuth:be},se),{client:this.client}),E&&{redirectUrl:E}),{lastAuth:Z(ue,this.loggerWrapper),abTestingKey:ae,locale:o(D).locale,nativeOptions:we,outboundAppId:pe,outboundAppScopes:he}),ne,"",me.componentsVersion,fe,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),P?{exchangeCode:P,idpInitiated:!0}:{}),se.descopeIdpInitiated&&{idpInitiated:!0}),A?{token:A}:{}),se.oidcLoginHint?{externalId:se.oidcLoginHint}:{}));return e(this,Oe,"f").call(this,t),void("completed"!==(null===(h=null==t?void 0:t.data)||void 0===h?void 0:h.status)&&this.flowState.update({code:void 0,token:void 0}))}}if(this.loggerWrapper.debug("Before popup postmessage send",JSON.stringify({isPopup:U,code:P,exchangeError:L,isCodeChanged:p("code"),isExchangeErrorChanged:p("exchangeError")})),U&&(p("code")&&P||p("exchangeError")&&L))return void e(this,le,"m",_e).call(this,b,P,L);if(b&&(p("token")&&A||p("code")&&P||p("exchangeError")&&L)){const t=yield this.sdk.flow.next(b,f,a.submit,ge.version,me.componentsVersion,{token:A,exchangeCode:P,exchangeError:L});return e(this,Oe,"f").call(this,t),void this.flowState.update({token:void 0,code:void 0,exchangeError:void 0})}if(w===l.loadForm&&B&&["samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState"].some((e=>p(e)))){if(!K)return void this.loggerWrapper.error("Did not get saml idp params data to load");R(B,K,H||"",j)}if(w===l.loadForm&&_&&["wsFedIdpResponseUrl","wsFedIdpResponseWresult","wsFedIdpResponseWctx"].some((e=>p(e)))){if(!Q)return void this.loggerWrapper.error("Did not get wsfed idp params data to load");C(_,Q,X||"",j)}if(w===l.redirect&&(p("redirectTo")||p("deferredRedirect"))){if(!O)return void this.loggerWrapper.error("Did not get redirect url");if("no-op"===O)return;if("android"===V&&document.hidden)return void this.flowState.update({deferredRedirect:!0});if(this.loggerWrapper.debug(`Redirect is popup ${x}`),x){this.loggerWrapper.debug("Opening redirect in popup");const t=W(O,"?",598,700),i=this.shouldUsePopupPostMessage();i&&(t.name=`descope-wc|${window.location.origin}`),this.loggerWrapper.debug("Popup communication method: "+(i?"postMessage":"BroadcastChannel"));const s=e=>{this.loggerWrapper.debug("Received popup message",JSON.stringify(e.data));const t=i?this.popupOrigin:window.location.origin;if(e.origin!==t)return void this.loggerWrapper.debug(`Ignoring message from unexpected origin. received: "${e.origin}", expected: "${t}"`);const{action:s,data:o}=e.data||{};"code"===s&&this.flowState.update({code:o.code,exchangeError:o.exchangeError})};let o;this.loggerWrapper.debug("Starting popup closed detection");const r=setInterval((()=>{t.closed&&(this.loggerWrapper.debug("Popup closed, dispatching popupclosed event"),clearInterval(r),e(this,le,"m",He).call(this,"popupclosed",{}),this.loggerWrapper.debug("Cleaning up popup listeners"),null==o||o())}),1e3);if(i)window.addEventListener("message",s),o=()=>{this.loggerWrapper.debug("Cleaning up popup postMessage listener"),window.removeEventListener("message",s)};else{this.loggerWrapper.debug("Creating broadcast channel");const e=new BroadcastChannel(b);e.onmessage=s,o=()=>{this.loggerWrapper.debug("Closing channel"),e.close()}}}else this.handleRedirect(O),this.flowState.update({redirectTo:"no-op"}),e(this,le,"m",He).call(this,"popupclosed",{});return}if(w===l.webauthnCreate||w===l.webauthnGet){if(!F||!$)return void this.loggerWrapper.error("Did not get webauthn transaction id or options");let i,s,o,r;null===(u=e(this,de,"f"))||void 0===u||u.abort(),t(this,de,null,"f");try{i=w===l.webauthnCreate?yield this.sdk.webauthn.helpers.create($):yield this.sdk.webauthn.helpers.get($)}catch(e){"InvalidStateError"===e.name?this.loggerWrapper.warn("WebAuthn operation failed",e.message):"NotAllowedError"!==e.name&&this.loggerWrapper.error(e.message),s=e.name,o=e.reason,r=e.message}const n=yield this.sdk.flow.next(b,f,a.submit,ge.version,me.componentsVersion,{transactionId:F,response:i,failure:s,failureReason:o,failureMessage:r});e(this,Oe,"f").call(this,n)}if(w===l.nativeBridge)return this.nativeCallbacks.complete=t=>i(this,void 0,void 0,(function*(){const i=yield this.sdk.flow.next(b,f,a.submit,ge.version,me.componentsVersion,t);e(this,Oe,"f").call(this,i)})),e(this,le,"m",ve).call(this,ee,te),void setTimeout((()=>{this.dispatchEvent(new Event("popupclosed"))}),500);if((p("action")||p("deferredPolling"))&&e(this,Ce,"f").call(this,b,f,ge.version,me.componentsVersion),!S&&!oe)return void this.loggerWrapper.warn("No screen was found to show");const Ie=oe||S,Re=yield this.getHtmlFilenameWithLocale(D,Ie),{oidcLoginHint:We,oidcPrompt:ke,oidcErrorRedirectUri:xe,oidcResource:Ee,samlIdpUsername:Ae}=se,je={direction:k(f,c.stepId),screenState:Object.assign(Object.assign({},y),{form:Object.assign(Object.assign({},this.formConfigValues),null==y?void 0:y.form),lastAuth:{loginId:ue,name:this.sdk.getLastUserDisplayName()||ue},componentsConfig:Object.assign(Object.assign(Object.assign({},ge.componentsConfig),Se),null==y?void 0:y.componentsConfig)}),htmlFilename:`${Ie}.html`,htmlLocaleFilename:Re,screenId:Ie,stepName:d.stepName||re,samlIdpUsername:Ae,oidcLoginHint:We,oidcPrompt:ke,oidcErrorRedirectUri:xe,oidcResource:Ee,action:w,locale:o(D).locale},Te=Z(ue,this.loggerWrapper);I(oe,se)?je.next=(t,s)=>i(this,void 0,void 0,(function*(){const i=(null==ge?void 0:ge.clientScripts)||[];yield e(this,le,"m",qe).call(this,i);const r=yield this.sdk.flow.start(v,Object.assign(Object.assign(Object.assign(Object.assign({tenant:m,redirectAuth:be},se),{lastAuth:Te,preview:this.preview,abTestingKey:ae,client:this.client}),E&&{redirectUrl:E}),{locale:o(D).locale,nativeOptions:we,outboundAppId:pe,outboundAppScopes:he}),ne,t,me.componentsVersion,fe,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),this.getComponentsContext()),T(s)),P&&{exchangeCode:P,idpInitiated:!0}),se.descopeIdpInitiated&&{idpInitiated:!0}),A&&{token:A}),je.next.isCustomScreen);return e(this,Oe,"f").call(this,r),r})):(p("projectId")||p("baseUrl")||p("executionId")||p("stepId"))&&(je.next=(t,s)=>i(this,void 0,void 0,(function*(){const i=(null==y?void 0:y.clientScripts)||[];yield e(this,le,"m",qe).call(this,i);const o=yield this.sdk.flow.next(b,f,t,ge.version,me.componentsVersion,Object.assign(Object.assign({},this.getComponentsContext()),T(s)),je.next.isCustomScreen);return e(this,Oe,"f").call(this,o),o}))),this.loggerWrapper.debug("Got a screen with id",je.screenId),yield e(this,le,"m",ye).call(this,je),this.stepState.update(je)}))}onStepChange(t,s){return i(this,void 0,void 0,(function*(){var o,r,n;const{htmlFilename:l,htmlLocaleFilename:d,direction:c,next:p,screenState:h,screenId:u}=t;this.loggerWrapper.debug("Rendering a flow screen");const g=document.createElement("template");g.innerHTML=yield this.getPageContent(l,d);const m=g.content.cloneNode(!0),f=this.loadDescopeUiComponents(g);this.sdk.webauthn.helpers.isSupported()?yield e(this,le,"m",Ae).call(this,m,p):$(m),!t.samlIdpUsername||(null===(o=h.form)||void 0===o?void 0:o.loginId)||(null===(r=h.form)||void 0===r?void 0:r.email)||(h.form||(h.form={}),h.form.loginId=t.samlIdpUsername,h.form.email=t.samlIdpUsername),N(m,h,this.formConfig,this.loggerWrapper),this.applyComponentsState(m,null==h?void 0:h.componentsState);const{geo:b}=null!==(n=yield this.getExecutionContext())&&void 0!==n?n:{};M(m,b),q(m,t.locale);const w=()=>i(this,void 0,void 0,(function*(){var i,o;yield f;const r=this.contentRootElement;V(r,null===(i=null==h?void 0:h.totp)||void 0===i?void 0:i.image),D(r,null===(o=null==h?void 0:h.notp)||void 0===o?void 0:o.image),B(r,m,h.cssVars,this.loggerWrapper),r.replaceChildren(m);const n=!s.htmlFilename;setTimeout((()=>{e(this,le,"m",$e).call(this),this.validateOnBlur&&P(r),K(r,h),this.initRealtimeConditions(r,h),e(this,le,"m",je).call(this,{isFirstScreen:n,isCustomScreen:!1,stepName:t.stepName}),O(r,this.autoFocus,n),e(this,le,"m",Be).call(this,u)})),e(this,le,"m",Ke).call(this,p,u);r.querySelector(`[${v}="polling"]`)&&p(a.polling,{})}));c?e(this,le,"m",Re).call(this,w):w()}))}getInputs(){return Array.from(this.shadowRoot.querySelectorAll(`*:not(slot)[name]:not([${g}])`))}shouldUsePopupPostMessage(){if(!this.popupOrigin)return!1;try{new URL(this.popupOrigin)}catch(e){return!1}return!0}}ae=new WeakMap,de=new WeakMap,ce=new WeakMap,pe=new WeakMap,Se=new WeakMap,Ie=new WeakMap,Ce=new WeakMap,We=new WeakMap,ke=new WeakMap,Oe=new WeakMap,xe=new WeakMap,Ue=new WeakMap,Me=new WeakMap,le=new WeakSet,he=function(){document.hidden||setTimeout((()=>{this.flowState.update({deferredRedirect:!1,deferredPolling:!1})}),300)},ue=function(t,s,o){return i(this,void 0,void 0,(function*(){var i;return(null===(i=this.nativeOptions)||void 0===i?void 0:i.bridgeVersion)>=2&&new Promise((i=>{this.nativeCallbacks.screenNext=o,this.nativeCallbacks.screenResolve=i,e(this,le,"m",ve).call(this,"beforeScreen",{screen:t,context:s})}))}))},ge=function(t){var i;(null===(i=this.nativeOptions)||void 0===i?void 0:i.bridgeVersion)>=2&&e(this,le,"m",ve).call(this,"afterScreen",{screen:t})},ve=function(t,i){e(this,le,"m",He).call(this,"bridge",{type:t,payload:i})},me=function({errorText:e,errorType:t}){const i=()=>{var i;let s=e;try{s=(null===(i=this.errorTransformer)||void 0===i?void 0:i.call(this,{text:e,type:t}))||e}catch(e){this.loggerWrapper.error("Error transforming error message",e.message)}H(this.contentRootElement,"error-message",s)};this.addEventListener("screen-updated",i,{once:!0}),i()},fe=function(){var t,i,o;null===(t=this.stepState)||void 0===t||t.subscribe(this.onStepChange.bind(this),(e=>{var t=e.screenState,i=s(void 0===t?{}:t,["errorText","errorType"]),o=s(e,["screenState"]);return Object.assign(Object.assign({},o),{screenState:i})})),null===(i=this.stepState)||void 0===i||i.subscribe(e(this,le,"m",me).bind(this),(e=>{var t,i;return{errorText:null===(t=null==e?void 0:e.screenState)||void 0===t?void 0:t.errorText,errorType:null===(i=null==e?void 0:e.screenState)||void 0===i?void 0:i.errorType}}),{forceUpdate:!0}),null===(o=this.stepState)||void 0===o||o.subscribe(e(this,le,"m",be).bind(this),(e=>{var t,i;return{errorText:null===(t=null==e?void 0:e.screenState)||void 0===t?void 0:t.errorText,errorType:null===(i=null==e?void 0:e.screenState)||void 0===i?void 0:i.errorType}}),{forceUpdate:!0})},be=function({errorText:e,errorType:t}){(t||e)&&(this.contentRootElement.querySelectorAll('descope-passcode[data-auto-submit="true"]').forEach((e=>{e.shadowRoot.querySelectorAll("descope-text-field[data-id]").forEach((e=>{e.value=""}))})),O(this.contentRootElement,this.autoFocus,!1))},we=function(){return i(this,void 0,void 0,(function*(){this.loggerWrapper.debug("Trying to restart the flow");const e=yield this.getComponentsVersion();this.reset();e===(yield this.getComponentsVersion())?(this.loggerWrapper.debug("Components version was not changed, restarting flow"),this.flowState.update({stepId:null,executionId:null})):this.loggerWrapper.error("Components version mismatch, please reload the page")}))},ye=function(o){return i(this,void 0,void 0,(function*(){var i;const r=Object.assign(Object.assign({},this.stepState.current),o),{next:n,stepName:l}=r,a=s(r,["next","stepName"]),d=x(a);let c=yield e(this,le,"m",ue).call(this,l,d,n);c||(c=Boolean(yield null===(i=this.onScreenUpdate)||void 0===i?void 0:i.call(this,l,d,n,this)));const p=!this.stepState.current.htmlFilename;if(e(this,Ie,"f").call(this,c),n&&(n.isCustomScreen=c),e(this,Se,"f")!==c){const[i,s]=["flow","custom"].sort((()=>c?-1:1));this.loggerWrapper.debug(`Switching from ${s} screen to ${i} screen`),t(this,Se,c,"f"),c?this.stepState.unsubscribeAll():e(this,le,"m",fe).call(this)}c?(this.loggerWrapper.debug("Showing a custom screen"),e(this,le,"m",je).call(this,{isFirstScreen:p,isCustomScreen:c,stepName:o.stepName}),this.disableKeyPressHandler()):this.handleKeyPress(),this.stepState.forceUpdate=c}))},Re=function(e){this.contentRootElement.addEventListener("transitionend",(()=>{this.loggerWrapper.debug("page switch transition end"),this.contentRootElement.classList.remove("fade-out"),e()}),{once:!0}),this.loggerWrapper.debug("page switch transition start"),this.contentRootElement.classList.add("fade-out")},Ee=function(e){const t=e.getAttribute("name");if(!["email"].includes(t)){const i=`user-${t}`;e.setAttribute("name",i),e.addEventListener("input",(()=>{e.setAttribute("name",e.value?t:i)}))}},Ae=function(s,o){return i(this,void 0,void 0,(function*(){var r;null===(r=e(this,de,"f"))||void 0===r||r.abort();const n=s.querySelector('*[autocomplete="webauthn"]');if(n&&(yield _())){const{options:s,transactionId:r}=(yield e(this,xe,"f").call(this))||{};s&&r&&(e(this,le,"m",Ee).call(this,n),t(this,de,new AbortController,"f"),this.sdk.webauthn.helpers.conditional(s,e(this,de,"f")).then((e=>i(this,void 0,void 0,(function*(){o(n.id,{transactionId:r,response:e})})))).catch((e=>{"AbortError"!==e.name&&this.loggerWrapper.error("Conditional login failed",e.message)})))}}))},je=function({isFirstScreen:t,isCustomScreen:i,stepName:s}){t&&e(this,le,"m",He).call(this,"ready",{}),i||e(this,le,"m",ge).call(this,s),e(this,le,"m",He).call(this,"page-updated",{screenName:s}),e(this,le,"m",He).call(this,"screen-updated",{screenName:s})},Te=function(){let e=!0;return Array.from(this.shadowRoot.querySelectorAll("*[name]")).reverse().forEach((t=>{var i,s;"slot"===t.localName||t.classList.contains("hidden")||(null===(i=t.reportValidity)||void 0===i||i.call(t),e&&(e=null===(s=t.checkValidity)||void 0===s?void 0:s.call(t)))})),e},Pe=function(){return i(this,void 0,void 0,(function*(){const e=this.getInputs();return(yield Promise.all(e.map((e=>i(this,void 0,void 0,(function*(){return{name:e.getAttribute("name"),value:e.value}})))))).reduce(((e,t)=>Object.assign(Object.assign({},e),{[t.name]:t.value})),{})}))},Le=function(s){const o=Array.from(this.contentRootElement.querySelectorAll(':not([disabled]), [disabled="false"]')).filter((e=>e!==s)),r=()=>i(this,void 0,void 0,(function*(){this.loggerWrapper.debug("Restoring components state"),this.removeEventListener("popupclosed",r),s.removeAttribute("loading"),o.forEach((e=>{e.removeAttribute("disabled")}));const e=yield this.getFlowConfig(),t=[...e.clientScripts||[],...e.sdkScripts||[]];this.loadSdkScripts(t)})),n=()=>{var i;window.removeEventListener("pageshow",e(this,Ue,"f")),t(this,Ue,(e=>{e.persisted&&(this.logger.debug("Page was loaded from cache, restoring components state"),r())}),"f"),window.addEventListener("pageshow",e(this,Ue,"f"),{once:!0});const s=null===(i=this.stepState)||void 0===i?void 0:i.subscribe(((e,t)=>{e===t&&r(),this.removeEventListener("popupclosed",r),this.stepState.unsubscribe(s)}),(e=>e.screenId),{forceUpdate:!0})},l=this.nextRequestStatus.subscribe((({isLoading:e})=>{e?(this.addEventListener("popupclosed",r,{once:!0}),s.setAttribute("loading","true"),o.forEach((e=>e.setAttribute("disabled","true")))):(this.nextRequestStatus.unsubscribe(l),n())}))},Fe=function(e={}){var t,i;const s=U(e,["externalId","email","phone"]),o=U(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)}},$e=function(){L();this.contentRootElement.querySelectorAll('[external-input="true"]').forEach((t=>e(this,le,"m",Ne).call(this,t)))},Ne=function(e){if(!e)return;e.querySelectorAll("input").forEach((t=>{const i=t.getAttribute("slot"),s=`input-${e.id}-${i}`,o=document.createElement("slot");o.setAttribute("name",s),o.setAttribute("slot",i),e.appendChild(o),t.setAttribute("slot",s),this.appendChild(t)}))},qe=function(t){return i(this,void 0,void 0,(function*(){if(e(this,ce,"f")){this.loggerWrapper.debug("Waiting for sdk scripts to load");const t=Date.now();yield e(this,ce,"f"),this.loggerWrapper.debug("Sdk scripts loaded for",(Date.now()-t).toString())}const i=this.loadSdkScriptsModules(),s=t.map((e=>e.id));for(const e of i)if(s.includes(e.id))try{if("function"==typeof e.present){(yield e.present())||this.loggerWrapper.debug(`Sdk script ${e.id} was cancelled`)}}catch(t){this.loggerWrapper.error(`Failed to present ${e.id} script module`,t.message)}const o=[];for(const e of i)"function"==typeof e.refresh&&o.push(e.refresh());if(o.length>0)try{yield w(u,Promise.all(o),null)}catch(e){this.loggerWrapper.error("Failed to refresh script module",e.message)}}))},Ve=function(t,i){this.contentRootElement.querySelectorAll('descope-passcode[data-auto-submit="true"]').forEach((s=>{s.addEventListener("input",(()=>{var o;(null===(o=s.checkValidity)||void 0===o?void 0:o.call(s))&&e(this,Me,"f").call(this,s,t,i)}))}))},De=function(e,t,i){t&&i&&"true"===e.getAttribute(m)&&ee(i,t,this.loggerWrapper)},Be=function(e){var t;const i=this.sdk.getLastUserLoginId(),s=null===(t=Z(i,this.loggerWrapper).lastUsedPerScreen)||void 0===t?void 0:t[e];if(!s)return;const o=this.contentRootElement.querySelector(f),r=this.contentRootElement.querySelector(`#${CSS.escape(s)}`);o&&r&&(r.replaceWith(o),o.appendChild(r))},Ke=function(t,i){this.contentRootElement.querySelectorAll(`descope-button:not([${b}]), [data-type="button"]:not([${b}]`).forEach((s=>{s.onclick=()=>{e(this,Me,"f").call(this,s,t,i)}})),e(this,le,"m",Ve).call(this,t,i),this.isDismissScreenErrorOnInput&&this.contentRootElement.querySelectorAll(`*[name]:not([${g}])`).forEach((e=>{e.addEventListener("input",(()=>{this.stepState.update((e=>Object.assign(Object.assign({},e),{screenState:Object.assign(Object.assign({},e.screenState),{errorText:"",errorType:""})})))}))}))},He=function(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t}))},_e=function(e,t,i){var s;const[o,r]=(null===(s=window.name)||void 0===s?void 0:s.split("|"))||[],n={data:{code:t,exchangeError:i},action:"code"};if("descope-wc"===o&&r){this.loggerWrapper.debug("Using postMessage fallback to notify opener in origin",r);try{window.opener.postMessage(n,r)}catch(e){this.loggerWrapper.error("Failed to send postMessage fallback (likely COOP isolation)",null==e?void 0:e.message)}}else{this.loggerWrapper.debug("Creating popup channel",e);const t=new BroadcastChannel(e);t.postMessage(n),t.close()}try{window.close()}catch(e){}};export{Ge as default};
|
|
2
2
|
//# sourceMappingURL=DescopeWc.js.map
|