@descope/web-component 4.5.1 → 4.5.2
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/debugger-wc.js.map +1 -1
- package/dist/cjs/descope-wc/BaseDescopeWc.js +1 -1
- package/dist/cjs/descope-wc/BaseDescopeWc.js.map +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/abTestingKey.js.map +1 -1
- package/dist/cjs/helpers/conditions.js.map +1 -1
- package/dist/cjs/helpers/flowInputs.js.map +1 -1
- package/dist/cjs/helpers/helpers.js.map +1 -1
- package/dist/cjs/helpers/lastAuth.js.map +1 -1
- package/dist/cjs/helpers/oidcSession.js.map +1 -1
- package/dist/cjs/helpers/positionHelpers.js.map +1 -1
- package/dist/cjs/helpers/realtime-conditions/applier.js.map +1 -1
- package/dist/cjs/helpers/realtime-conditions/evaluator.js.map +1 -1
- package/dist/cjs/helpers/state.js.map +1 -1
- package/dist/cjs/helpers/storage.js.map +1 -1
- package/dist/cjs/helpers/templates.js.map +1 -1
- package/dist/cjs/helpers/webauthn.js.map +1 -1
- package/dist/cjs/mixins/componentConditionsMixin.js.map +1 -1
- package/dist/cjs/mixins/duplicateFlowWarningMixin.js.map +1 -1
- package/dist/cjs/mixins/formMountMixin.js.map +1 -1
- package/dist/cjs/mixins/passwordManagerMixin.js.map +1 -1
- package/dist/cjs/mixins/validationTrackingMixin.js.map +1 -1
- package/dist/cjs/types.js.map +1 -1
- package/dist/esm/constants/customScreens.js.map +1 -1
- package/dist/esm/debugger-wc.js.map +1 -1
- package/dist/esm/descope-wc/BaseDescopeWc.js +1 -1
- package/dist/esm/descope-wc/BaseDescopeWc.js.map +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/abTestingKey.js.map +1 -1
- package/dist/esm/helpers/conditions.js.map +1 -1
- package/dist/esm/helpers/flowInputs.js.map +1 -1
- package/dist/esm/helpers/helpers.js +1 -1
- package/dist/esm/helpers/helpers.js.map +1 -1
- package/dist/esm/helpers/lastAuth.js +1 -1
- package/dist/esm/helpers/lastAuth.js.map +1 -1
- package/dist/esm/helpers/oidcSession.js +1 -1
- package/dist/esm/helpers/oidcSession.js.map +1 -1
- package/dist/esm/helpers/positionHelpers.js.map +1 -1
- package/dist/esm/helpers/realtime-conditions/applier.js.map +1 -1
- package/dist/esm/helpers/realtime-conditions/evaluator.js.map +1 -1
- package/dist/esm/helpers/state.js.map +1 -1
- package/dist/esm/helpers/storage.js.map +1 -1
- package/dist/esm/helpers/templates.js.map +1 -1
- package/dist/esm/helpers/webauthn.js.map +1 -1
- package/dist/esm/mixins/componentConditionsMixin.js.map +1 -1
- package/dist/esm/mixins/duplicateFlowWarningMixin.js.map +1 -1
- package/dist/esm/mixins/formMountMixin.js.map +1 -1
- package/dist/esm/mixins/passwordManagerMixin.js.map +1 -1
- package/dist/esm/mixins/validationTrackingMixin.js.map +1 -1
- package/dist/esm/types.js.map +1 -1
- package/dist/index.js +2 -2
- package/package.json +2 -2
|
@@ -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 // 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","evaluateAll","conditions","result","forEach","c","componentIds","id","action","collectTouchedComponentIds","out","Set","add","collectReferencedFormKeys","walkOperand"],"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,GAA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vC,OANCD,QAAAA,EAAc,IAAIE,SAASC,UACrBhB,EAAkBgB,EAAG1B,KACP,QAAlBV,EAAAoC,EAAEC,oBAAgB,IAAArC,EAAAA,EAAA,IAAImC,SAASG,IAC9BJ,EAAOI,GAAMF,EAAEG,MAAM,GACrB,IAEGL,CACT,CAMM,SAAUM,EACdP,GAEA,MAAMQ,EAAM,IAAIC,IAIhB,OAHCT,QAAAA,EAAc,IAAIE,SAASC,mBACzBpC,EAAAoC,EAAEC,4BAAgB,IAAIF,SAASG,GAAOG,EAAIE,IAAIL,IAAI,IAE9CG,CACT,CAOM,SAAUG,EACdX,GAEA,MAAMQ,EAAM,IAAIC,IACVG,EAAepC,UACdA,IACgB,SAAjBA,EAAQE,MAAmBF,EAAQG,KACrC6B,EAAIE,IAAIlC,EAAQG,MACU,SAAjBH,EAAQE,OACC,QAAjBX,EAAAS,EAAQI,aAAS,IAAAb,EAAAA,EAAA,IAAImC,QAAQU,GAC/B,EAUH,OARCZ,QAAAA,EAAc,IAAIE,SAASC,UAC1B,OAAY,QAAXpC,EAAAoC,EAAEd,aAAS,IAAAtB,EAAAA,EAAA,IAAImC,SAASX,UACvB,OAAuB,QAAtBxB,EAAAwB,EAAEG,wBAAoB,IAAA3B,EAAAA,EAAA,IAAImC,SAASN,IAClCgB,EAAYhB,EAAE3C,QACd2D,EAAYhB,EAAE1C,UAAU,GACxB,GACH,IAEIsD,CACT"}
|
|
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","evaluateAll","conditions","result","forEach","c","componentIds","id","action","collectTouchedComponentIds","out","Set","add","collectReferencedFormKeys","walkOperand"],"mappings":"AAkBM,SAAUA,EAAQC,GACtB,GAAiB,iBAANA,GAAkBC,OAAOC,SAASF,GAC3C,MAAO,CAAEG,MAAOH,EA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D,GAAMb,EAAea,EAAGnB,KAChD,CAO6CqB,CAAaP,EAAGd,IAC7D,CAaM,SAAUsB,EACdC,EACAvB,GAEA,MAAMwB,EAAiC,CAAA,EAOvC,OANCD,QAAAA,EAAc,IAAIE,SAASC,UACrBhB,EAAkBgB,EAAG1B,KACX,QAAdV,EAAAoC,EAAEC,oBAAY,IAAArC,EAAAA,EAAI,IAAImC,SAASG,IAC9BJ,EAAOI,GAAMF,EAAEG,MAAM,GACrB,IAEGL,CACT,CAMM,SAAUM,EACdP,GAEA,MAAMQ,EAAM,IAAIC,IAIhB,OAHCT,QAAAA,EAAc,IAAIE,SAASC,mBACzBpC,EAAAoC,EAAEC,4BAAgB,IAAIF,SAASG,GAAOG,EAAIE,IAAIL,IAAI,IAE9CG,CACT,CAOM,SAAUG,EACdX,GAEA,MAAMQ,EAAM,IAAIC,IACVG,EAAepC,UACdA,IACgB,SAAjBA,EAAQE,MAAmBF,EAAQG,KACrC6B,EAAIE,IAAIlC,EAAQG,MACU,SAAjBH,EAAQE,OACH,QAAbX,EAAAS,EAAQI,aAAK,IAAAb,EAAAA,EAAI,IAAImC,QAAQU,GAChC,EAUF,OARCZ,QAAAA,EAAc,IAAIE,SAASC,UAC1B,OAAQ,QAAPpC,EAAAoC,EAAEd,aAAK,IAAAtB,EAAAA,EAAI,IAAImC,SAASX,UACvB,OAAmB,QAAlBxB,EAAAwB,EAAEG,wBAAgB,IAAA3B,EAAAA,EAAI,IAAImC,SAASN,IAClCgB,EAAYhB,EAAE3C,QACd2D,EAAYhB,EAAE1C,UAAU,GACxB,GACH,IAEIsD,CACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"state.js","sources":["../../../src/lib/helpers/state.ts"],"sourcesContent":["import { createIsChanged } from './helpers';\n\ntype StateObject = Record<string, any>;\n\n// eslint-disable-next-line import/exports-last\nexport type SubscribeCb<T> = (\n state: T,\n prevState: T,\n isChanged: ReturnType<typeof createIsChanged>,\n) => void | Promise<void>;\n\ntype UpdateStateCb<T> = (state: T) => Partial<T>;\n\ntype Subscribers<T> = Record<\n string,\n {\n cb: SubscribeCb<ReturnType<SelectorCb<T>>>;\n selector: SelectorCb<T>;\n forceUpdate: boolean;\n }\n>;\n\nexport type SelectorCb<T> = (state: T) => any;\n\nexport type IsChanged<T> = Parameters<SubscribeCb<T>>[2];\n\nfunction isPlainObject(maybeObj: any) {\n if (typeof maybeObj !== 'object' || maybeObj === null) return false;\n const proto = Object.getPrototypeOf(maybeObj);\n return proto === Object.prototype || proto === null;\n}\n\nfunction compareObjects(\n objectA: Record<string, any>,\n objectB: Record<string, any>,\n) {\n const aProperties = Object.getOwnPropertyNames(objectA);\n const bProperties = Object.getOwnPropertyNames(objectB);\n\n if (aProperties.length !== bProperties.length) {\n return false;\n }\n\n for (let i = 0; i < aProperties.length; i += 1) {\n const propName = aProperties[i];\n\n const valA = objectA[propName];\n const valB = objectB[propName];\n if (valA === null || valB === null) {\n if (valA !== valB) {\n return false;\n }\n } else if (typeof valA === 'object' && typeof valB === 'object') {\n // compare nested objects\n if (!compareObjects(valA, valB)) {\n return false;\n }\n } else if (valA !== valB) {\n return false;\n }\n }\n\n return true;\n}\n\nclass State<T extends StateObject> {\n #state: T;\n\n #subscribers: Subscribers<T> = {};\n\n #token = 0;\n\n #forceUpdateAll = true;\n\n constructor(init: T = {} as T, { forceUpdate = false } = {}) {\n this.#state = init;\n this.#forceUpdateAll = forceUpdate;\n }\n\n get current() {\n return { ...this.#state };\n }\n\n set forceUpdate(forceUpdate: boolean) {\n this.#forceUpdateAll = forceUpdate;\n }\n\n update = (newState: Partial<T> | UpdateStateCb<T>) => {\n const internalNewState =\n typeof newState === 'function' ? newState(this.#state) : newState;\n\n const nextState = { ...this.#state, ...internalNewState };\n const prevState = this.#state;\n this.#state = nextState;\n Object.freeze(this.#state);\n\n setTimeout(() => {\n Object.values(this.#subscribers).forEach(\n ({ cb, selector, forceUpdate }) => {\n const partialPrevState = selector(prevState);\n const partialNextState = selector(nextState);\n\n if (\n this.#forceUpdateAll ||\n forceUpdate ||\n (isPlainObject(partialNextState)\n ? !compareObjects(partialPrevState, partialNextState)\n : partialPrevState !== partialNextState)\n ) {\n cb(\n partialNextState,\n partialPrevState,\n createIsChanged(partialNextState, partialPrevState),\n );\n }\n },\n );\n }, 0);\n };\n\n subscribe<R extends any | Partial<T>>(\n cb: SubscribeCb<R>,\n selector: (state: T) => R = (state: T) => state as unknown as R,\n { forceUpdate = false }: { forceUpdate?: boolean } = {},\n ) {\n this.#token += 1;\n this.#subscribers[this.#token] = { cb, selector, forceUpdate };\n\n return this.#token.toString();\n }\n\n unsubscribe(token: string) {\n const isFound = !!this.#subscribers[token];\n\n if (isFound) {\n delete this.#subscribers[token];\n }\n\n return isFound;\n }\n\n unsubscribeAll() {\n this.#subscribers = {};\n\n return true;\n }\n}\n\nexport default State;\n"],"names":["compareObjects","objectA","objectB","aProperties","Object","getOwnPropertyNames","bProperties","length","i","propName","valA","valB","State","constructor","init","forceUpdate","_State_state","set","this","_State_subscribers","_State_token","_State_forceUpdateAll","update","newState","internalNewState","__classPrivateFieldGet","nextState","prevState","__classPrivateFieldSet","freeze","setTimeout","values","forEach","cb","selector","partialPrevState","partialNextState","maybeObj","proto","getPrototypeOf","prototype","isPlainObject","createIsChanged","current","assign","subscribe","state","toString","unsubscribe","token","isFound","unsubscribeAll"],"mappings":"sIAgCA,SAASA,EACPC,EACAC,GAEA,MAAMC,EAAcC,OAAOC,oBAAoBJ,GACzCK,EAAcF,OAAOC,oBAAoBH,GAE/C,GAAIC,EAAYI,SAAWD,EAAYC,OACrC,OAAO,EAGT,IAAK,IAAIC,EAAI,EAAGA,EAAIL,EAAYI,OAAQC,GAAK,EAAG,CAC9C,MAAMC,EAAWN,EAAYK,GAEvBE,EAAOT,EAAQQ,GACfE,EAAOT,EAAQO,GACrB,GAAa,OAATC,GAA0B,OAATC,GACnB,GAAID,IAASC,EACX,OAAO,OAEJ,GAAoB,iBAATD,GAAqC,iBAATC,GAE5C,IAAKX,EAAeU,EAAMC,GACxB,OAAO,OAEJ,GAAID,IAASC,EAClB,OAAO,
|
|
1
|
+
{"version":3,"file":"state.js","sources":["../../../src/lib/helpers/state.ts"],"sourcesContent":["import { createIsChanged } from './helpers';\n\ntype StateObject = Record<string, any>;\n\n// eslint-disable-next-line import/exports-last\nexport type SubscribeCb<T> = (\n state: T,\n prevState: T,\n isChanged: ReturnType<typeof createIsChanged>,\n) => void | Promise<void>;\n\ntype UpdateStateCb<T> = (state: T) => Partial<T>;\n\ntype Subscribers<T> = Record<\n string,\n {\n cb: SubscribeCb<ReturnType<SelectorCb<T>>>;\n selector: SelectorCb<T>;\n forceUpdate: boolean;\n }\n>;\n\nexport type SelectorCb<T> = (state: T) => any;\n\nexport type IsChanged<T> = Parameters<SubscribeCb<T>>[2];\n\nfunction isPlainObject(maybeObj: any) {\n if (typeof maybeObj !== 'object' || maybeObj === null) return false;\n const proto = Object.getPrototypeOf(maybeObj);\n return proto === Object.prototype || proto === null;\n}\n\nfunction compareObjects(\n objectA: Record<string, any>,\n objectB: Record<string, any>,\n) {\n const aProperties = Object.getOwnPropertyNames(objectA);\n const bProperties = Object.getOwnPropertyNames(objectB);\n\n if (aProperties.length !== bProperties.length) {\n return false;\n }\n\n for (let i = 0; i < aProperties.length; i += 1) {\n const propName = aProperties[i];\n\n const valA = objectA[propName];\n const valB = objectB[propName];\n if (valA === null || valB === null) {\n if (valA !== valB) {\n return false;\n }\n } else if (typeof valA === 'object' && typeof valB === 'object') {\n // compare nested objects\n if (!compareObjects(valA, valB)) {\n return false;\n }\n } else if (valA !== valB) {\n return false;\n }\n }\n\n return true;\n}\n\nclass State<T extends StateObject> {\n #state: T;\n\n #subscribers: Subscribers<T> = {};\n\n #token = 0;\n\n #forceUpdateAll = true;\n\n constructor(init: T = {} as T, { forceUpdate = false } = {}) {\n this.#state = init;\n this.#forceUpdateAll = forceUpdate;\n }\n\n get current() {\n return { ...this.#state };\n }\n\n set forceUpdate(forceUpdate: boolean) {\n this.#forceUpdateAll = forceUpdate;\n }\n\n update = (newState: Partial<T> | UpdateStateCb<T>) => {\n const internalNewState =\n typeof newState === 'function' ? newState(this.#state) : newState;\n\n const nextState = { ...this.#state, ...internalNewState };\n const prevState = this.#state;\n this.#state = nextState;\n Object.freeze(this.#state);\n\n setTimeout(() => {\n Object.values(this.#subscribers).forEach(\n ({ cb, selector, forceUpdate }) => {\n const partialPrevState = selector(prevState);\n const partialNextState = selector(nextState);\n\n if (\n this.#forceUpdateAll ||\n forceUpdate ||\n (isPlainObject(partialNextState)\n ? !compareObjects(partialPrevState, partialNextState)\n : partialPrevState !== partialNextState)\n ) {\n cb(\n partialNextState,\n partialPrevState,\n createIsChanged(partialNextState, partialPrevState),\n );\n }\n },\n );\n }, 0);\n };\n\n subscribe<R extends any | Partial<T>>(\n cb: SubscribeCb<R>,\n selector: (state: T) => R = (state: T) => state as unknown as R,\n { forceUpdate = false }: { forceUpdate?: boolean } = {},\n ) {\n this.#token += 1;\n this.#subscribers[this.#token] = { cb, selector, forceUpdate };\n\n return this.#token.toString();\n }\n\n unsubscribe(token: string) {\n const isFound = !!this.#subscribers[token];\n\n if (isFound) {\n delete this.#subscribers[token];\n }\n\n return isFound;\n }\n\n unsubscribeAll() {\n this.#subscribers = {};\n\n return true;\n }\n}\n\nexport default State;\n"],"names":["compareObjects","objectA","objectB","aProperties","Object","getOwnPropertyNames","bProperties","length","i","propName","valA","valB","State","constructor","init","forceUpdate","_State_state","set","this","_State_subscribers","_State_token","_State_forceUpdateAll","update","newState","internalNewState","__classPrivateFieldGet","nextState","prevState","__classPrivateFieldSet","freeze","setTimeout","values","forEach","cb","selector","partialPrevState","partialNextState","maybeObj","proto","getPrototypeOf","prototype","isPlainObject","createIsChanged","current","assign","subscribe","state","toString","unsubscribe","token","isFound","unsubscribeAll"],"mappings":"sIAgCA,SAASA,EACPC,EACAC,GAEA,MAAMC,EAAcC,OAAOC,oBAAoBJ,GACzCK,EAAcF,OAAOC,oBAAoBH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EH,GACA,EAAE,EA1CLP,EAAAV,KAAIF,EAAUF,EAAI,KAClBc,EAAAV,KAAIG,EAAmBN,EAAW,IACpC,CAEA,WAAI4B,GACF,OAAAvC,OAAAwC,OAAA,CAAA,EAAYnB,EAAAP,KAAIF,EAAA,KAClB,CAEA,eAAID,CAAYA,GACda,EAAAV,KAAIG,EAAmBN,EAAW,IACpC,CAmCA,SAAA8B,CACEZ,EACAC,EAA6BY,GAAaA,GAC1C/B,YAAEA,GAAc,GAAqC,IAKrD,OAHAa,EAAAV,KAAAE,EAAAK,EAAAP,KAAAE,EAAA,KAAe,OACfK,EAAAP,KAAIC,EAAA,KAAcM,EAAAP,KAAIE,EAAA,MAAW,CAAEa,KAAIC,WAAUnB,eAE1CU,EAAAP,KAAIE,EAAA,KAAQ2B,UACrB,CAEA,WAAAC,CAAYC,GACV,MAAMC,IAAYzB,EAAAP,KAAIC,EAAA,KAAc8B,GAMpC,OAJIC,UACKzB,EAAAP,KAAIC,EAAA,KAAc8B,GAGpBC,CACT,CAEA,cAAAC,GAGE,OAFAvB,EAAAV,KAAIC,EAAgB,CAAA,EAAE,MAEf,CACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"storage.js","sources":["../../../src/lib/helpers/storage.ts"],"sourcesContent":["// Storage helper functions for web-component package\n// These functions provide a consistent interface for storage operations\n// Currently uses localStorage, but structured to support custom storage in the future\n\nimport type { CustomStorage } from '../types';\n\n// this is a singleton\n// but in order to keep the code clean\n// it was implemented in this way\nlet customStorage: CustomStorage | undefined;\n\n/**\n * Set an item in storage\n */\nexport const setStorageItem = (key: string, value: string): void => {\n if (customStorage) {\n customStorage.setItem(key, value);\n } else if (typeof window?.localStorage !== 'undefined') {\n window.localStorage.setItem(key, value);\n }\n};\n\n/**\n * Get an item from storage\n */\nexport const getStorageItem = (key: string): string | null => {\n if (customStorage) {\n return customStorage.getItem(key);\n }\n\n if (typeof window?.localStorage !== 'undefined') {\n return window.localStorage.getItem(key);\n }\n return null;\n};\n\n/**\n * Remove an item from storage\n */\nexport const removeStorageItem = (key: string): void => {\n if (customStorage) {\n customStorage.removeItem(key);\n } else if (typeof window?.localStorage !== 'undefined') {\n window.localStorage.removeItem(key);\n }\n};\n\n/**\n * Set custom storage for the web-component package\n */\nexport const setCustomStorage = (storage: CustomStorage) => {\n customStorage = storage;\n};\n\n/**\n * Reset custom storage (for testing)\n */\nexport const resetCustomStorage = () => {\n customStorage = undefined;\n};\n"],"names":["customStorage","setStorageItem","key","value","setItem","window","localStorage","getStorageItem","getItem","removeStorageItem","removeItem","setCustomStorage","storage"],"mappings":"AASA,IAAIA,QAKSC,EAAiB,CAACC,EAAaC,KACtCH,EACFA,EAAcI,QAAQF,EAAKC,QACc,KAAnB,OAANE,aAAM,IAANA,YAAM,EAANA,OAAQC,eACxBD,OAAOC,aAAaF,QAAQF,EAAKC,
|
|
1
|
+
{"version":3,"file":"storage.js","sources":["../../../src/lib/helpers/storage.ts"],"sourcesContent":["// Storage helper functions for web-component package\n// These functions provide a consistent interface for storage operations\n// Currently uses localStorage, but structured to support custom storage in the future\n\nimport type { CustomStorage } from '../types';\n\n// this is a singleton\n// but in order to keep the code clean\n// it was implemented in this way\nlet customStorage: CustomStorage | undefined;\n\n/**\n * Set an item in storage\n */\nexport const setStorageItem = (key: string, value: string): void => {\n if (customStorage) {\n customStorage.setItem(key, value);\n } else if (typeof window?.localStorage !== 'undefined') {\n window.localStorage.setItem(key, value);\n }\n};\n\n/**\n * Get an item from storage\n */\nexport const getStorageItem = (key: string): string | null => {\n if (customStorage) {\n return customStorage.getItem(key);\n }\n\n if (typeof window?.localStorage !== 'undefined') {\n return window.localStorage.getItem(key);\n }\n return null;\n};\n\n/**\n * Remove an item from storage\n */\nexport const removeStorageItem = (key: string): void => {\n if (customStorage) {\n customStorage.removeItem(key);\n } else if (typeof window?.localStorage !== 'undefined') {\n window.localStorage.removeItem(key);\n }\n};\n\n/**\n * Set custom storage for the web-component package\n */\nexport const setCustomStorage = (storage: CustomStorage) => {\n customStorage = storage;\n};\n\n/**\n * Reset custom storage (for testing)\n */\nexport const resetCustomStorage = () => {\n customStorage = undefined;\n};\n"],"names":["customStorage","setStorageItem","key","value","setItem","window","localStorage","getStorageItem","getItem","removeStorageItem","removeItem","setCustomStorage","storage"],"mappings":"AASA,IAAIA,QAKSC,EAAiB,CAACC,EAAaC,KACtCH,EACFA,EAAcI,QAAQF,EAAKC,QACc,KAAnB,OAANE,aAAM,IAANA,YAAM,EAANA,OAAQC,eACxBD,OAAOC,aAAaF,QAAQF,EAAKC,EACnC,EAMWI,EAAkBL,GACzBF,EACKA,EAAcQ,QAAQN,QAGK,KAAnB,OAANG,aAAM,IAANA,YAAM,EAANA,OAAQC,cACVD,OAAOC,aAAaE,QAAQN,GAE9B,KAMIO,EAAqBP,IAC5BF,EACFA,EAAcU,WAAWR,QACgB,KAAnB,OAANG,aAAM,IAANA,YAAM,EAANA,OAAQC,eACxBD,OAAOC,aAAaI,WAAWR,EACjC,EAMWS,EAAoBC,IAC/BZ,EAAgBY,CAAO"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"templates.js","sources":["../../../src/lib/helpers/templates.ts"],"sourcesContent":["import { escapeMarkdown } from '@descope/escape-markdown';\nimport {\n ELEMENT_TYPE_ATTRIBUTE,\n DESCOPE_ATTRIBUTE_EXCLUDE_FIELD,\n HAS_DYNAMIC_VALUES_ATTR_NAME,\n} from '../constants';\nimport { ComponentsConfig, CssVars, ScreenState } from '../types';\nimport { shouldHandleMarkdown } from './helpers';\n\nconst ALLOWED_INPUT_CONFIG_ATTRS = ['disabled'];\n\nexport const replaceElementMessage = (\n baseEle: HTMLElement,\n eleType: string,\n message = '',\n) => {\n const eleList = baseEle.querySelectorAll(\n `[${ELEMENT_TYPE_ATTRIBUTE}=\"${eleType}\"]`,\n );\n eleList.forEach((ele: HTMLElement) => {\n // eslint-disable-next-line no-param-reassign\n ele.textContent = message;\n ele.classList[message ? 'remove' : 'add']('hide');\n });\n};\n\n/**\n * Replace the 'value' attribute of screen inputs with screen state's inputs.\n * For example: if base element contains '<input name=\"key1\" ...>' and screen input is in form of { key1: 'val1' },\n * it will add 'val1' as the input value\n */\nconst replaceElementInputs = (\n baseEle: HTMLElement,\n screenInputs: Record<string, string>,\n) => {\n Object.entries(screenInputs || {}).forEach(([name, value]) => {\n const inputEls = Array.from(\n baseEle.querySelectorAll(\n `*[name=\"${name}\"]:not([${DESCOPE_ATTRIBUTE_EXCLUDE_FIELD}])`,\n ),\n ) as HTMLInputElement[];\n inputEls.forEach((inputEle) => {\n // eslint-disable-next-line no-param-reassign\n inputEle.value = value;\n });\n });\n};\n\n/**\n * Get object nested path.\n * Examples:\n * - getByPath({ { a { b: 'rob' } }, 'a.b') => 'hey rob'\n * - getByPath({}, 'a.b') => ''\n */\nconst getByPath = (obj: Record<string, any>, path: string) =>\n path.split('.').reduce((prev, next) => prev?.[next] || '', obj);\n\n/**\n * Apply template language on text, based on screen state.\n * Examples:\n * - 'hey {{a.b}}', { a { b: 'rob' }} => 'hey rob'\n * - 'hey {{not.exists}}', {} => 'hey '\n */\nconst applyTemplates = (\n text: string,\n screenState?: Record<string, any>,\n handleMarkdown?: boolean,\n): string =>\n text.replace(/{{(.+?)}}/g, (_, match) =>\n handleMarkdown\n ? escapeMarkdown(getByPath(screenState, match))\n : getByPath(screenState, match),\n );\n\n/**\n * Replace the templates of content of inner text/link elements with screen state data\n */\nconst replaceElementTemplates = (\n baseEle: DocumentFragment,\n screenState?: Record<string, any>,\n) => {\n const eleList = baseEle.querySelectorAll(\n 'descope-text,descope-link,descope-enriched-text,descope-code-snippet',\n );\n eleList.forEach((inEle: HTMLElement) => {\n const handleMarkdown = shouldHandleMarkdown(inEle.localName);\n // eslint-disable-next-line no-param-reassign\n inEle.textContent = applyTemplates(\n inEle.textContent,\n screenState,\n handleMarkdown,\n );\n const href = inEle.getAttribute('href');\n if (href) {\n inEle.setAttribute('href', applyTemplates(href, screenState));\n }\n });\n};\n\nconst replaceTemplateDynamicAttrValues = (\n baseEle: DocumentFragment,\n screenState?: Record<string, any>,\n) => {\n const eleList = baseEle.querySelectorAll(`[${HAS_DYNAMIC_VALUES_ATTR_NAME}]`);\n eleList.forEach((ele: HTMLElement) => {\n Array.from(ele.attributes).forEach((attr) => {\n // eslint-disable-next-line no-param-reassign\n attr.value = applyTemplates(attr.value, screenState);\n });\n });\n};\n\nconst replaceHrefByDataType = (\n baseEle: DocumentFragment,\n dataType: string,\n provisionUrl?: string,\n) => {\n const eleList = baseEle.querySelectorAll(\n `[${ELEMENT_TYPE_ATTRIBUTE}=\"${dataType}\"]`,\n );\n eleList.forEach((ele: HTMLLinkElement) => {\n // eslint-disable-next-line no-param-reassign\n ele.setAttribute('href', provisionUrl);\n });\n};\n\nconst setFormConfigValues = (\n baseEle: DocumentFragment,\n formData: Record<string, string>,\n) => {\n Object.entries(formData).forEach(([name, config]) => {\n const eles = baseEle.querySelectorAll(`[name=\"${name}\"]`);\n\n eles.forEach((ele) => {\n Object.entries(config).forEach(([attrName, attrValue]) => {\n if (ALLOWED_INPUT_CONFIG_ATTRS.includes(attrName)) {\n ele.setAttribute(attrName, attrValue);\n }\n });\n });\n });\n};\n\nexport const setCssVars = (\n rootEle: HTMLElement,\n nextPageTemplate: DocumentFragment,\n cssVars: CssVars,\n logger: {\n error: (message: string, description: string) => void;\n info: (message: string, description: string) => void;\n debug: (message: string, description: string) => void;\n },\n) => {\n if (!cssVars) {\n return;\n }\n\n Object.keys(cssVars).forEach((componentName) => {\n if (!nextPageTemplate.querySelector(componentName)) {\n logger.debug(\n `Skipping css vars for component \"${componentName}\"`,\n `Got css vars for component ${componentName} but Could not find it on next page`,\n );\n\n return;\n }\n const componentClass:\n | (CustomElementConstructor & { cssVarList: CssVars })\n | undefined = customElements.get(componentName) as any;\n\n if (!componentClass) {\n logger.debug(\n `Could not find component class for ${componentName}`,\n 'Check if the component is registered',\n );\n\n return;\n }\n\n Object.keys(cssVars[componentName]).forEach((cssVarKey) => {\n const componentCssVars = cssVars[componentName];\n const varName = componentClass?.cssVarList?.[cssVarKey];\n\n if (!varName) {\n logger.info(\n `Could not find css variable name for ${cssVarKey} in ${componentName}`,\n 'Check if the css variable is defined in the component',\n );\n return;\n }\n\n const value = componentCssVars[cssVarKey];\n\n rootEle.style.setProperty(varName, value);\n });\n });\n};\n\nconst setElementConfig = (\n baseEle: DocumentFragment,\n componentsConfig: ComponentsConfig,\n logger?: { error: (message: string, description: string) => void },\n) => {\n if (!componentsConfig) {\n return;\n }\n const { componentsDynamicAttrs, ...rest } = componentsConfig;\n\n const configMap = Object.keys(rest).reduce((acc, componentName) => {\n acc[`[name=${componentName}]`] = rest[componentName];\n return acc;\n }, {});\n\n if (componentsDynamicAttrs) {\n Object.keys(componentsDynamicAttrs).forEach((componentSelector) => {\n const componentDynamicAttrs = componentsDynamicAttrs[componentSelector];\n if (componentDynamicAttrs) {\n const { attributes } = componentDynamicAttrs;\n if (attributes && Object.keys(attributes).length) {\n configMap[componentSelector] = attributes;\n }\n }\n });\n }\n\n // collect components that needs configuration from DOM\n Object.keys(configMap).forEach((componentsSelector) => {\n baseEle.querySelectorAll(componentsSelector).forEach((comp) => {\n const config = configMap[componentsSelector];\n\n Object.keys(config).forEach((attr) => {\n let value = config[attr];\n\n if (typeof value !== 'string') {\n try {\n value = JSON.stringify(value);\n } catch (e) {\n logger.error(\n `Could not stringify value \"${value}\" for \"${attr}\"`,\n e.message,\n );\n value = '';\n }\n }\n\n comp.setAttribute(attr, value);\n });\n });\n });\n};\n\nconst setImageVariable = (\n rootEle: HTMLElement,\n name: string,\n image?: string,\n) => {\n const imageVarName = (\n customElements.get(name) as CustomElementConstructor & {\n cssVarList: Record<string, string>;\n }\n )?.cssVarList.url;\n\n if (image && imageVarName) {\n rootEle?.style?.setProperty(\n imageVarName,\n `url(data:image/jpg;base64,${image})`,\n );\n }\n};\n\n/**\n * Update a screen template based on the screen state\n * - Show/hide error messages\n * - Replace element templates ({{...}} syntax) with screen state object\n *\n * Note: applying `screenState.componentsState` (the server-applied baseline\n * hide/disable/read-only map) is owned by the `componentConditionsMixin`. The\n * host calls `this.applyComponentsState(...)` after this function returns and\n * before the fragment is mounted.\n */\nexport const updateTemplateFromScreenState = (\n baseEle: DocumentFragment,\n screenState?: ScreenState,\n flowInputs?: Record<string, string>,\n logger?: { error: (message: string, description: string) => void },\n) => {\n replaceHrefByDataType(baseEle, 'totp-link', screenState?.totp?.provisionUrl);\n replaceHrefByDataType(baseEle, 'notp-link', screenState?.notp?.redirectUrl);\n replaceElementTemplates(baseEle, screenState);\n setElementConfig(baseEle, screenState?.componentsConfig, logger);\n replaceTemplateDynamicAttrValues(baseEle, screenState);\n setFormConfigValues(baseEle, flowInputs);\n};\n\n/**\n * Update a screen based on a screen state\n * - Replace values of element inputs with screen state's inputs\n */\nexport const updateScreenFromScreenState = (\n baseEle: HTMLElement,\n screenState?: ScreenState,\n) => {\n replaceElementInputs(baseEle, screenState?.inputs);\n replaceElementInputs(baseEle, screenState?.form);\n};\n\nexport const setTOTPVariable = (rootEle: HTMLElement, image?: string) => {\n setImageVariable(rootEle, 'descope-totp-image', image);\n};\n\nexport const setNOTPVariable = (rootEle: HTMLElement, image?: string) => {\n setImageVariable(rootEle, 'descope-notp-image', image);\n};\n\nexport const setComponentsAutoDetectByGeo = (\n fragment: DocumentFragment,\n countryCodeIso2?: string, // e.g. 'US', 'IL', 'FR'\n) => {\n const config = {\n // phone\n 'default-code': 'autoDetect',\n // country-subdivision-city\n 'default-country': 'autoDetect',\n };\n Object.entries(config).forEach(([key, value]) => {\n Array.from(fragment.querySelectorAll(`[${key}=\"${value}\"]`)).forEach(\n (ele) => {\n ele.setAttribute(key, countryCodeIso2 || value);\n },\n );\n });\n};\n\nexport const setComponentsAutoDetectByLocale = (\n fragment: DocumentFragment,\n locale?: string, // e.g. 'en-US', 'fr-FR'\n) => {\n const config = {\n // country-subdivision-city\n lang: 'autoDetect',\n };\n\n let canonicalLocale = locale;\n if (locale) {\n try {\n const [canonical] = Intl.getCanonicalLocales(locale);\n if (canonical) {\n canonicalLocale = canonical;\n }\n } catch {\n // locale is not valid, keep original value\n }\n }\n\n Object.entries(config).forEach(([key, value]) => {\n Array.from(fragment.querySelectorAll(`[${key}=\"${value}\"]`)).forEach(\n (ele) => {\n ele.setAttribute(key, canonicalLocale || value);\n },\n );\n });\n};\n\nexport const disableWebauthnButtons = (fragment: DocumentFragment) => {\n const webauthnButtons = fragment.querySelectorAll(\n `descope-button[${ELEMENT_TYPE_ATTRIBUTE}=\"biometrics\"]`,\n );\n webauthnButtons.forEach((button) => button.setAttribute('disabled', 'true'));\n};\n\nexport const getDescopeUiComponentsList = (clone: DocumentFragment) => [\n ...Array.from(clone.querySelectorAll('*')).reduce<Set<string>>(\n (acc, el: HTMLElement) =>\n el.tagName.startsWith('DESCOPE-')\n ? acc.add(el.tagName.toLocaleLowerCase())\n : acc,\n new Set(),\n ),\n];\n"],"names":["ALLOWED_INPUT_CONFIG_ATTRS","replaceElementMessage","baseEle","eleType","message","querySelectorAll","ELEMENT_TYPE_ATTRIBUTE","forEach","ele","textContent","classList","replaceElementInputs","screenInputs","Object","entries","name","value","Array","from","DESCOPE_ATTRIBUTE_EXCLUDE_FIELD","inputEle","getByPath","obj","path","split","reduce","prev","next","applyTemplates","text","screenState","handleMarkdown","replace","_","match","escapeMarkdown","replaceHrefByDataType","dataType","provisionUrl","setAttribute","setCssVars","rootEle","nextPageTemplate","cssVars","logger","keys","componentName","querySelector","debug","componentClass","customElements","get","cssVarKey","componentCssVars","varName","_a","cssVarList","info","style","setProperty","setImageVariable","image","imageVarName","url","_b","updateTemplateFromScreenState","flowInputs","totp","notp","redirectUrl","inEle","shouldHandleMarkdown","localName","href","getAttribute","replaceElementTemplates","componentsConfig","componentsDynamicAttrs","rest","__rest","configMap","acc","componentSelector","componentDynamicAttrs","attributes","length","componentsSelector","comp","config","attr","JSON","stringify","e","error","setElementConfig","HAS_DYNAMIC_VALUES_ATTR_NAME","replaceTemplateDynamicAttrValues","formData","attrName","attrValue","includes","setFormConfigValues","updateScreenFromScreenState","inputs","form","setTOTPVariable","setNOTPVariable","setComponentsAutoDetectByGeo","fragment","countryCodeIso2","key","setComponentsAutoDetectByLocale","locale","canonicalLocale","canonical","Intl","getCanonicalLocales","lang","disableWebauthnButtons","button"],"mappings":"mRASA,MAAMA,EAA6B,CAAC,YAEvBC,EAAwB,CACnCC,EACAC,EACAC,EAAU,MAEMF,EAAQG,iBACtB,IAAIC,MAA2BH,OAEzBI,SAASC,IAEfA,EAAIC,YAAcL,EAClBI,EAAIE,UAAUN,EAAU,SAAW,OAAO,OAAO,GACjD,EAQEO,EAAuB,CAC3BT,EACAU,KAEAC,OAAOC,QAAQF,GAAgB,CAAE,GAAEL,SAAQ,EAAEQ,EAAMC,MAChCC,MAAMC,KACrBhB,EAAQG,iBACN,WAAWU,YAAeI,QAGrBZ,SAASa,IAEhBA,EAASJ,MAAQA,CAAK,GACtB,GACF,EASEK,EAAY,CAACC,EAA0BC,IAC3CA,EAAKC,MAAM,KAAKC,QAAO,CAACC,EAAMC,KAASD,aAAI,EAAJA,EAAOC,KAAS,IAAIL,GAQvDM,EAAiB,CACrBC,EACAC,EACAC,IAEAF,EAAKG,QAAQ,cAAc,CAACC,EAAGC,IAC7BH,EACII,EAAed,EAAUS,EAAaI,IACtCb,EAAUS,EAAaI,KAyCzBE,EAAwB,CAC5BlC,EACAmC,EACAC,KAEgBpC,EAAQG,iBACtB,IAAIC,MAA2B+B,OAEzB9B,SAASC,IAEfA,EAAI+B,aAAa,OAAQD,EAAa,GACtC,EAoBSE,EAAa,CACxBC,EACAC,EACAC,EACAC,KAMKD,GAIL9B,OAAOgC,KAAKF,GAASpC,SAASuC,IAC5B,IAAKJ,EAAiBK,cAAcD,GAMlC,YALAF,EAAOI,MACL,oCAAoCF,KACpC,8BAA8BA,wCAKlC,MAAMG,EAEUC,eAAeC,IAAIL,GAE9BG,EASLpC,OAAOgC,KAAKF,EAAQG,IAAgBvC,S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EAASgE,EAAW,EAO7BoC,EAA8B,CACzCpG,EACA4B,KAEAnB,EAAqBT,EAAS4B,aAAW,EAAXA,EAAayE,QAC3C5F,EAAqBT,EAAS4B,aAAW,EAAXA,EAAa0E,KAAK,EAGrCC,EAAkB,CAAChE,EAAsBoB,KACpDD,EAAiBnB,EAAS,qBAAsBoB,EAAM,EAG3C6C,EAAkB,CAACjE,EAAsBoB,KACpDD,EAAiBnB,EAAS,qBAAsBoB,EAAM,EAG3C8C,EAA+B,CAC1CC,EACAC,KAQAhG,OAAOC,QANQ,CAEb,eAAgB,aAEhB,kBAAmB,eAEEP,SAAQ,EAAEuG,EAAK9F,MACpCC,MAAMC,KAAK0F,EAASvG,iBAAiB,IAAIyG,MAAQ9F,QAAYT,SAC1DC,IACCA,EAAI+B,aAAauE,EAAKD,GAAmB7F,EAAM,GAElD,GACD,EAGS+F,EAAkC,CAC7CH,EACAI,KAOA,IAAIC,EAAkBD,EACtB,GAAIA,EACF,IACE,MAAOE,GAAaC,KAAKC,oBAAoBJ,GACzCE,IACFD,EAAkBC,EAErB,CAAC,MAAA3D,GAED,CAGH1C,OAAOC,QAjBQ,CAEbuG,KAAM,eAee9G,SAAQ,EAAEuG,EAAK9F,MACpCC,MAAMC,KAAK0F,EAASvG,iBAAiB,IAAIyG,MAAQ9F,QAAYT,SAC1DC,IACCA,EAAI+B,aAAauE,EAAKG,GAAmBjG,EAAM,GAElD,GACD,EAGSsG,EAA0BV,IACbA,EAASvG,iBAC/B,kBAAkBC,mBAEJC,SAASgH,GAAWA,EAAOhF,aAAa,WAAY,SAAQ"}
|
|
1
|
+
{"version":3,"file":"templates.js","sources":["../../../src/lib/helpers/templates.ts"],"sourcesContent":["import { escapeMarkdown } from '@descope/escape-markdown';\nimport {\n ELEMENT_TYPE_ATTRIBUTE,\n DESCOPE_ATTRIBUTE_EXCLUDE_FIELD,\n HAS_DYNAMIC_VALUES_ATTR_NAME,\n} from '../constants';\nimport { ComponentsConfig, CssVars, ScreenState } from '../types';\nimport { shouldHandleMarkdown } from './helpers';\n\nconst ALLOWED_INPUT_CONFIG_ATTRS = ['disabled'];\n\nexport const replaceElementMessage = (\n baseEle: HTMLElement,\n eleType: string,\n message = '',\n) => {\n const eleList = baseEle.querySelectorAll(\n `[${ELEMENT_TYPE_ATTRIBUTE}=\"${eleType}\"]`,\n );\n eleList.forEach((ele: HTMLElement) => {\n // eslint-disable-next-line no-param-reassign\n ele.textContent = message;\n ele.classList[message ? 'remove' : 'add']('hide');\n });\n};\n\n/**\n * Replace the 'value' attribute of screen inputs with screen state's inputs.\n * For example: if base element contains '<input name=\"key1\" ...>' and screen input is in form of { key1: 'val1' },\n * it will add 'val1' as the input value\n */\nconst replaceElementInputs = (\n baseEle: HTMLElement,\n screenInputs: Record<string, string>,\n) => {\n Object.entries(screenInputs || {}).forEach(([name, value]) => {\n const inputEls = Array.from(\n baseEle.querySelectorAll(\n `*[name=\"${name}\"]:not([${DESCOPE_ATTRIBUTE_EXCLUDE_FIELD}])`,\n ),\n ) as HTMLInputElement[];\n inputEls.forEach((inputEle) => {\n // eslint-disable-next-line no-param-reassign\n inputEle.value = value;\n });\n });\n};\n\n/**\n * Get object nested path.\n * Examples:\n * - getByPath({ { a { b: 'rob' } }, 'a.b') => 'hey rob'\n * - getByPath({}, 'a.b') => ''\n */\nconst getByPath = (obj: Record<string, any>, path: string) =>\n path.split('.').reduce((prev, next) => prev?.[next] || '', obj);\n\n/**\n * Apply template language on text, based on screen state.\n * Examples:\n * - 'hey {{a.b}}', { a { b: 'rob' }} => 'hey rob'\n * - 'hey {{not.exists}}', {} => 'hey '\n */\nconst applyTemplates = (\n text: string,\n screenState?: Record<string, any>,\n handleMarkdown?: boolean,\n): string =>\n text.replace(/{{(.+?)}}/g, (_, match) =>\n handleMarkdown\n ? escapeMarkdown(getByPath(screenState, match))\n : getByPath(screenState, match),\n );\n\n/**\n * Replace the templates of content of inner text/link elements with screen state data\n */\nconst replaceElementTemplates = (\n baseEle: DocumentFragment,\n screenState?: Record<string, any>,\n) => {\n const eleList = baseEle.querySelectorAll(\n 'descope-text,descope-link,descope-enriched-text,descope-code-snippet',\n );\n eleList.forEach((inEle: HTMLElement) => {\n const handleMarkdown = shouldHandleMarkdown(inEle.localName);\n // eslint-disable-next-line no-param-reassign\n inEle.textContent = applyTemplates(\n inEle.textContent,\n screenState,\n handleMarkdown,\n );\n const href = inEle.getAttribute('href');\n if (href) {\n inEle.setAttribute('href', applyTemplates(href, screenState));\n }\n });\n};\n\nconst replaceTemplateDynamicAttrValues = (\n baseEle: DocumentFragment,\n screenState?: Record<string, any>,\n) => {\n const eleList = baseEle.querySelectorAll(`[${HAS_DYNAMIC_VALUES_ATTR_NAME}]`);\n eleList.forEach((ele: HTMLElement) => {\n Array.from(ele.attributes).forEach((attr) => {\n // eslint-disable-next-line no-param-reassign\n attr.value = applyTemplates(attr.value, screenState);\n });\n });\n};\n\nconst replaceHrefByDataType = (\n baseEle: DocumentFragment,\n dataType: string,\n provisionUrl?: string,\n) => {\n const eleList = baseEle.querySelectorAll(\n `[${ELEMENT_TYPE_ATTRIBUTE}=\"${dataType}\"]`,\n );\n eleList.forEach((ele: HTMLLinkElement) => {\n // eslint-disable-next-line no-param-reassign\n ele.setAttribute('href', provisionUrl);\n });\n};\n\nconst setFormConfigValues = (\n baseEle: DocumentFragment,\n formData: Record<string, string>,\n) => {\n Object.entries(formData).forEach(([name, config]) => {\n const eles = baseEle.querySelectorAll(`[name=\"${name}\"]`);\n\n eles.forEach((ele) => {\n Object.entries(config).forEach(([attrName, attrValue]) => {\n if (ALLOWED_INPUT_CONFIG_ATTRS.includes(attrName)) {\n ele.setAttribute(attrName, attrValue);\n }\n });\n });\n });\n};\n\nexport const setCssVars = (\n rootEle: HTMLElement,\n nextPageTemplate: DocumentFragment,\n cssVars: CssVars,\n logger: {\n error: (message: string, description: string) => void;\n info: (message: string, description: string) => void;\n debug: (message: string, description: string) => void;\n },\n) => {\n if (!cssVars) {\n return;\n }\n\n Object.keys(cssVars).forEach((componentName) => {\n if (!nextPageTemplate.querySelector(componentName)) {\n logger.debug(\n `Skipping css vars for component \"${componentName}\"`,\n `Got css vars for component ${componentName} but Could not find it on next page`,\n );\n\n return;\n }\n const componentClass:\n | (CustomElementConstructor & { cssVarList: CssVars })\n | undefined = customElements.get(componentName) as any;\n\n if (!componentClass) {\n logger.debug(\n `Could not find component class for ${componentName}`,\n 'Check if the component is registered',\n );\n\n return;\n }\n\n Object.keys(cssVars[componentName]).forEach((cssVarKey) => {\n const componentCssVars = cssVars[componentName];\n const varName = componentClass?.cssVarList?.[cssVarKey];\n\n if (!varName) {\n logger.info(\n `Could not find css variable name for ${cssVarKey} in ${componentName}`,\n 'Check if the css variable is defined in the component',\n );\n return;\n }\n\n const value = componentCssVars[cssVarKey];\n\n rootEle.style.setProperty(varName, value);\n });\n });\n};\n\nconst setElementConfig = (\n baseEle: DocumentFragment,\n componentsConfig: ComponentsConfig,\n logger?: { error: (message: string, description: string) => void },\n) => {\n if (!componentsConfig) {\n return;\n }\n const { componentsDynamicAttrs, ...rest } = componentsConfig;\n\n const configMap = Object.keys(rest).reduce((acc, componentName) => {\n acc[`[name=${componentName}]`] = rest[componentName];\n return acc;\n }, {});\n\n if (componentsDynamicAttrs) {\n Object.keys(componentsDynamicAttrs).forEach((componentSelector) => {\n const componentDynamicAttrs = componentsDynamicAttrs[componentSelector];\n if (componentDynamicAttrs) {\n const { attributes } = componentDynamicAttrs;\n if (attributes && Object.keys(attributes).length) {\n configMap[componentSelector] = attributes;\n }\n }\n });\n }\n\n // collect components that needs configuration from DOM\n Object.keys(configMap).forEach((componentsSelector) => {\n baseEle.querySelectorAll(componentsSelector).forEach((comp) => {\n const config = configMap[componentsSelector];\n\n Object.keys(config).forEach((attr) => {\n let value = config[attr];\n\n if (typeof value !== 'string') {\n try {\n value = JSON.stringify(value);\n } catch (e) {\n logger.error(\n `Could not stringify value \"${value}\" for \"${attr}\"`,\n e.message,\n );\n value = '';\n }\n }\n\n comp.setAttribute(attr, value);\n });\n });\n });\n};\n\nconst setImageVariable = (\n rootEle: HTMLElement,\n name: string,\n image?: string,\n) => {\n const imageVarName = (\n customElements.get(name) as CustomElementConstructor & {\n cssVarList: Record<string, string>;\n }\n )?.cssVarList.url;\n\n if (image && imageVarName) {\n rootEle?.style?.setProperty(\n imageVarName,\n `url(data:image/jpg;base64,${image})`,\n );\n }\n};\n\n/**\n * Update a screen template based on the screen state\n * - Show/hide error messages\n * - Replace element templates ({{...}} syntax) with screen state object\n *\n * Note: applying `screenState.componentsState` (the server-applied baseline\n * hide/disable/read-only map) is owned by the `componentConditionsMixin`. The\n * host calls `this.applyComponentsState(...)` after this function returns and\n * before the fragment is mounted.\n */\nexport const updateTemplateFromScreenState = (\n baseEle: DocumentFragment,\n screenState?: ScreenState,\n flowInputs?: Record<string, string>,\n logger?: { error: (message: string, description: string) => void },\n) => {\n replaceHrefByDataType(baseEle, 'totp-link', screenState?.totp?.provisionUrl);\n replaceHrefByDataType(baseEle, 'notp-link', screenState?.notp?.redirectUrl);\n replaceElementTemplates(baseEle, screenState);\n setElementConfig(baseEle, screenState?.componentsConfig, logger);\n replaceTemplateDynamicAttrValues(baseEle, screenState);\n setFormConfigValues(baseEle, flowInputs);\n};\n\n/**\n * Update a screen based on a screen state\n * - Replace values of element inputs with screen state's inputs\n */\nexport const updateScreenFromScreenState = (\n baseEle: HTMLElement,\n screenState?: ScreenState,\n) => {\n replaceElementInputs(baseEle, screenState?.inputs);\n replaceElementInputs(baseEle, screenState?.form);\n};\n\nexport const setTOTPVariable = (rootEle: HTMLElement, image?: string) => {\n setImageVariable(rootEle, 'descope-totp-image', image);\n};\n\nexport const setNOTPVariable = (rootEle: HTMLElement, image?: string) => {\n setImageVariable(rootEle, 'descope-notp-image', image);\n};\n\nexport const setComponentsAutoDetectByGeo = (\n fragment: DocumentFragment,\n countryCodeIso2?: string, // e.g. 'US', 'IL', 'FR'\n) => {\n const config = {\n // phone\n 'default-code': 'autoDetect',\n // country-subdivision-city\n 'default-country': 'autoDetect',\n };\n Object.entries(config).forEach(([key, value]) => {\n Array.from(fragment.querySelectorAll(`[${key}=\"${value}\"]`)).forEach(\n (ele) => {\n ele.setAttribute(key, countryCodeIso2 || value);\n },\n );\n });\n};\n\nexport const setComponentsAutoDetectByLocale = (\n fragment: DocumentFragment,\n locale?: string, // e.g. 'en-US', 'fr-FR'\n) => {\n const config = {\n // country-subdivision-city\n lang: 'autoDetect',\n };\n\n let canonicalLocale = locale;\n if (locale) {\n try {\n const [canonical] = Intl.getCanonicalLocales(locale);\n if (canonical) {\n canonicalLocale = canonical;\n }\n } catch {\n // locale is not valid, keep original value\n }\n }\n\n Object.entries(config).forEach(([key, value]) => {\n Array.from(fragment.querySelectorAll(`[${key}=\"${value}\"]`)).forEach(\n (ele) => {\n ele.setAttribute(key, canonicalLocale || value);\n },\n );\n });\n};\n\nexport const disableWebauthnButtons = (fragment: DocumentFragment) => {\n const webauthnButtons = fragment.querySelectorAll(\n `descope-button[${ELEMENT_TYPE_ATTRIBUTE}=\"biometrics\"]`,\n );\n webauthnButtons.forEach((button) => button.setAttribute('disabled', 'true'));\n};\n\nexport const getDescopeUiComponentsList = (clone: DocumentFragment) => [\n ...Array.from(clone.querySelectorAll('*')).reduce<Set<string>>(\n (acc, el: HTMLElement) =>\n el.tagName.startsWith('DESCOPE-')\n ? acc.add(el.tagName.toLocaleLowerCase())\n : acc,\n new Set(),\n ),\n];\n"],"names":["ALLOWED_INPUT_CONFIG_ATTRS","replaceElementMessage","baseEle","eleType","message","querySelectorAll","ELEMENT_TYPE_ATTRIBUTE","forEach","ele","textContent","classList","replaceElementInputs","screenInputs","Object","entries","name","value","Array","from","DESCOPE_ATTRIBUTE_EXCLUDE_FIELD","inputEle","getByPath","obj","path","split","reduce","prev","next","applyTemplates","text","screenState","handleMarkdown","replace","_","match","escapeMarkdown","replaceHrefByDataType","dataType","provisionUrl","setAttribute","setCssVars","rootEle","nextPageTemplate","cssVars","logger","keys","componentName","querySelector","debug","componentClass","customElements","get","cssVarKey","componentCssVars","varName","_a","cssVarList","info","style","setProperty","setImageVariable","image","imageVarName","url","_b","updateTemplateFromScreenState","flowInputs","totp","notp","redirectUrl","inEle","shouldHandleMarkdown","localName","href","getAttribute","replaceElementTemplates","componentsConfig","componentsDynamicAttrs","rest","__rest","configMap","acc","componentSelector","componentDynamicAttrs","attributes","length","componentsSelector","comp","config","attr","JSON","stringify","e","error","setElementConfig","HAS_DYNAMIC_VALUES_ATTR_NAME","replaceTemplateDynamicAttrValues","formData","attrName","attrValue","includes","setFormConfigValues","updateScreenFromScreenState","inputs","form","setTOTPVariable","setNOTPVariable","setComponentsAutoDetectByGeo","fragment","countryCodeIso2","key","setComponentsAutoDetectByLocale","locale","canonicalLocale","canonical","Intl","getCanonicalLocales","lang","disableWebauthnButtons","button"],"mappings":"mRASA,MAAMA,EAA6B,CAAC,YAEvBC,EAAwB,CACnCC,EACAC,EACAC,EAAU,MAEMF,EAAQG,iBACtB,IAAIC,MAA2BH,OAEzBI,SAASC,IAEfA,EAAIC,YAAcL,EAClBI,EAAIE,UAAUN,EAAU,SAAW,OAAO,OAAO,GACjD,EAQEO,EAAuB,CAC3BT,EACAU,KAEAC,OAAOC,QAAQF,GAAgB,CAAA,GAAIL,SAAQ,EAAEQ,EAAMC,MAChCC,MAAMC,KACrBhB,EAAQG,iBACN,WAAWU,YAAeI,QAGrBZ,SAASa,IAEhBA,EAASJ,MAAQA,CAAK,GACtB,GACF,EASEK,EAAY,CAACC,EAA0BC,IAC3CA,EAAKC,MAAM,KAAKC,QAAO,CAACC,EAAMC,KAASD,aAAI,EAAJA,EAAOC,KAAS,IAAIL,GAQvDM,EAAiB,CACrBC,EACAC,EACAC,IAEAF,EAAKG,QAAQ,cAAc,CAACC,EAAGC,IAC7BH,EACII,EAAed,EAAUS,EAAaI,IACtCb,EAAUS,EAAaI,KAyCzBE,EAAwB,CAC5BlC,EACAmC,EACAC,KAEgBpC,EAAQG,iBACtB,IAAIC,MAA2B+B,OAE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AAkBC,mBAEJC,SAASgH,GAAWA,EAAOhF,aAAa,WAAY,SAAQ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"webauthn.js","sources":["../../../src/lib/helpers/webauthn.ts"],"sourcesContent":["/* eslint @typescript-eslint/no-use-before-define: 0 */\n\nimport { withMemCache, timeoutPromise, getChromiumVersion } from './helpers';\n\nconst CHROMIUM_VERSION_THAT_SUPPORTS_PASSKEYS = 108;\n\n// eslint-disable-next-line import/prefer-default-export\nexport const isConditionalLoginSupported = withMemCache(async () => {\n if (\n !window.PublicKeyCredential ||\n !(<any>PublicKeyCredential).isConditionalMediationAvailable ||\n !PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable\n ) {\n return false;\n }\n try {\n const isSupported = Promise.all([\n (<any>window.PublicKeyCredential)?.isConditionalMediationAvailable(),\n window.PublicKeyCredential?.isUserVerifyingPlatformAuthenticatorAvailable(),\n ]).then((arr) => arr.every((value) => !!value));\n\n // when using Dashlane Chrome extension, \"isConditionalMediationAvailable\" never resolved and the app hangs\n // if timeout exceeded, we are deciding if passkeys are supported based on the Chromium version\n const isChromiumSupported =\n getChromiumVersion() >= CHROMIUM_VERSION_THAT_SUPPORTS_PASSKEYS;\n\n return await timeoutPromise(100, isSupported, isChromiumSupported);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error('Conditional login check failed', err);\n return false;\n }\n});\n"],"names":["isConditionalLoginSupported","withMemCache","__awaiter","window","PublicKeyCredential","isConditionalMediationAvailable","isUserVerifyingPlatformAuthenticatorAvailable","isSupported","Promise","all","_a","_b","then","arr","every","value","isChromiumSupported","getChromiumVersion","timeoutPromise","err","console","error"],"mappings":"0HAIA,MAGaA,EAA8BC,GAAa,IAAWC,OAAA,OAAA,OAAA,GAAA,oBACjE,IACGC,OAAOC,sBACDA,oBAAqBC,kCAC3BD,oBAAoBE,8CAErB,OAAO,EAET,IACE,MAAMC,EAAcC,QAAQC,IAAI,CACG,QAAjCC,EAAMP,OAAOC,2BAAoB,IAAAM,OAAA,EAAAA,EAAEL,kCACT,QAA1BM,EAAAR,OAAOC,2BAAmB,IAAAO,OAAA,EAAAA,EAAEL,kDAC3BM,MAAMC,GAAQA,EAAIC,OAAOC,KAAYA,MAIlCC,EACJC,KApB0C,IAsB5C,aAAaC,EAAe,IAAKX,EAAaS,
|
|
1
|
+
{"version":3,"file":"webauthn.js","sources":["../../../src/lib/helpers/webauthn.ts"],"sourcesContent":["/* eslint @typescript-eslint/no-use-before-define: 0 */\n\nimport { withMemCache, timeoutPromise, getChromiumVersion } from './helpers';\n\nconst CHROMIUM_VERSION_THAT_SUPPORTS_PASSKEYS = 108;\n\n// eslint-disable-next-line import/prefer-default-export\nexport const isConditionalLoginSupported = withMemCache(async () => {\n if (\n !window.PublicKeyCredential ||\n !(<any>PublicKeyCredential).isConditionalMediationAvailable ||\n !PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable\n ) {\n return false;\n }\n try {\n const isSupported = Promise.all([\n (<any>window.PublicKeyCredential)?.isConditionalMediationAvailable(),\n window.PublicKeyCredential?.isUserVerifyingPlatformAuthenticatorAvailable(),\n ]).then((arr) => arr.every((value) => !!value));\n\n // when using Dashlane Chrome extension, \"isConditionalMediationAvailable\" never resolved and the app hangs\n // if timeout exceeded, we are deciding if passkeys are supported based on the Chromium version\n const isChromiumSupported =\n getChromiumVersion() >= CHROMIUM_VERSION_THAT_SUPPORTS_PASSKEYS;\n\n return await timeoutPromise(100, isSupported, isChromiumSupported);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error('Conditional login check failed', err);\n return false;\n }\n});\n"],"names":["isConditionalLoginSupported","withMemCache","__awaiter","window","PublicKeyCredential","isConditionalMediationAvailable","isUserVerifyingPlatformAuthenticatorAvailable","isSupported","Promise","all","_a","_b","then","arr","every","value","isChromiumSupported","getChromiumVersion","timeoutPromise","err","console","error"],"mappings":"0HAIA,MAGaA,EAA8BC,GAAa,IAAWC,OAAA,OAAA,OAAA,GAAA,oBACjE,IACGC,OAAOC,sBACDA,oBAAqBC,kCAC3BD,oBAAoBE,8CAErB,OAAO,EAET,IACE,MAAMC,EAAcC,QAAQC,IAAI,CACG,QAAjCC,EAAMP,OAAOC,2BAAoB,IAAAM,OAAA,EAAAA,EAAEL,kCACT,QAA1BM,EAAAR,OAAOC,2BAAmB,IAAAO,OAAA,EAAAA,EAAEL,kDAC3BM,MAAMC,GAAQA,EAAIC,OAAOC,KAAYA,MAIlCC,EACJC,KApB0C,IAsB5C,aAAaC,EAAe,IAAKX,EAAaS,EAChD,CAAE,MAAOG,GAGP,OADAC,QAAQC,MAAM,iCAAkCF,IACzC,CACT,CACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"componentConditionsMixin.js","sources":["../../../src/lib/mixins/componentConditionsMixin.ts"],"sourcesContent":["/* eslint-disable import/prefer-default-export, no-param-reassign */\nimport { compose, createSingletonMixin } from '@descope/sdk-helpers';\nimport { loggerMixin } from '@descope/sdk-mixins';\nimport {\n REALTIME_CONDITION_DEBOUNCE_MS,\n REALTIME_CONDITION_EVENTS,\n} from '../helpers/realtime-conditions/config';\nimport {\n collectReferencedFormKeys,\n collectTouchedComponentIds,\n evaluateAll,\n FormSnapshot,\n} from '../helpers/realtime-conditions/evaluator';\nimport {\n apply,\n COMPONENT_ACTIONS,\n escapeSelector,\n} from '../helpers/realtime-conditions/applier';\nimport { DESCOPE_ATTRIBUTE_EXCLUDE_FIELD } from '../constants';\nimport type { RealtimeComponentsCondition, ScreenState } from '../types';\n\nconst LOG_PREFIX = 'component-conditions:';\n\n// What the mixin needs from its host: a way to subscribe to loading state\n// so input handling can pause while the next request is in flight. Defined\n// as an interface (not imported) to avoid a circular dependency on BaseDescopeWc.\nexport interface PausableHost {\n nextRequestStatus?: {\n // subscribe returns a token; pass that token to unsubscribe — not the handler.\n subscribe: (cb: (v: { isLoading: boolean }) => void) => string;\n unsubscribe?: (token: string) => void;\n };\n}\n\nexport interface RealtimeRuntime {\n conditions: RealtimeComponentsCondition[];\n // IDs of components that any rule can change\n touchedIds: Set<string>;\n // latest form values on screen\n snapshot: FormSnapshot;\n // what's currently applied on screen for touched components.\n // Compared against on each re-evaluation to know what to change.\n applied: Record<string, string>;\n // What the server told us to apply for these components. Stays fixed for\n // the screen's lifetime so we can fall back to it when a real-time rule\n // stops matching. Without this, a server-set action could disappear when\n // a real-time rule briefly fires on the same component.\n serverBaseline: Record<string, string>;\n debounceTimer: ReturnType<typeof setTimeout> | null;\n // true while paused (during submit, to avoid stale updates)\n paused: boolean;\n unsubscribePauseListener: (() => void) | null;\n // the listener we attach to form events (kept so we can detach)\n inputHandler: (e: Event) => void;\n // the screen root we work against\n root: HTMLElement | null;\n}\n\n// Some inputs already have `name=\"form.x\"`, others use `name=\"x\"`. Always\n// return the `form.x` form so it lines up with what rules reference.\nfunction toFormKey(name: string): string {\n return name.startsWith('form.') ? name : `form.${name}`;\n}\n\n// Try the full `form.x` first (descope components), then `x` (plain inputs).\nfunction findInputForFormKey(\n root: ParentNode,\n formKey: string,\n): Element | null {\n const bare = formKey.startsWith('form.')\n ? formKey.slice('form.'.length)\n : formKey;\n return (\n root.querySelector(`[name=\"${escapeSelector(formKey)}\"]`) ||\n root.querySelector(`[name=\"${escapeSelector(bare)}\"]`)\n );\n}\n\n// Read the current value off a form input. Reads JS properties (not HTML\n// attributes) so we pick up both the component's default and any value\n// carried over from earlier screens.\n//\n// Native <input type=checkbox> needs special handling: `.value` is always\n// \"on\", only `.checked` reflects the real state. Descope boolean components\n// (descope-checkbox, descope-switch-toggle) expose `.checked` on their class.\nfunction readInputValue(el: Element): unknown {\n if (el instanceof HTMLInputElement) {\n return el.type === 'checkbox' ? el.checked : el.value;\n }\n if ('checked' in el) {\n return (el as unknown as { checked: boolean }).checked;\n }\n if ('value' in el) {\n return (el as unknown as { value: unknown }).value;\n }\n return undefined;\n}\n\nfunction shallowEqualStringMap(\n a: Record<string, string>,\n b: Record<string, string>,\n): boolean {\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n if (keysA.length !== keysB.length) return false;\n return keysA.every((k) => a[k] === b[k]);\n}\n\nfunction emptyRuntime(): RealtimeRuntime {\n return {\n conditions: [],\n touchedIds: new Set(),\n snapshot: {},\n applied: {},\n serverBaseline: {},\n debounceTimer: null,\n paused: false,\n unsubscribePauseListener: null,\n inputHandler: () => {},\n root: null,\n };\n}\n\n// For each touched component, pick the real-time action if a rule is firing\n// for it, otherwise fall back to the server's action. Components that no rule\n// touches are not in the result — those were already painted by\n// applyComponentsState.\nfunction effectiveActions(\n realtimeVerdict: Record<string, string>,\n serverBaseline: Record<string, string>,\n touchedIds: Set<string>,\n): Record<string, string> {\n const out: Record<string, string> = {};\n touchedIds.forEach((id) => {\n if (realtimeVerdict[id]) {\n out[id] = realtimeVerdict[id];\n } else if (serverBaseline[id]) {\n out[id] = serverBaseline[id];\n }\n });\n return out;\n}\n\nexport const componentConditionsMixin = createSingletonMixin(\n <T extends CustomElementConstructor>(superclass: T) => {\n // Pull in loggerMixin so `this.logger` is available no matter where\n // this mixin sits in the chain.\n const BaseClass = compose(loggerMixin)(superclass);\n\n return class ComponentConditionsMixin extends BaseClass {\n // One runtime per <descope-wc> element.\n #rtRuntime: RealtimeRuntime = emptyRuntime();\n\n /**\n * Apply the server's hide/disable/read-only actions to the DOM.\n * Logs unknown actions here (runs once per screen) but stays quiet on\n * the keystroke path to avoid log spam.\n */\n applyComponentsState(\n root: ParentNode,\n componentsState: Record<string, string> | undefined,\n ): void {\n if (!componentsState) return;\n Object.entries(componentsState).forEach(([id, action]) => {\n if (!(COMPONENT_ACTIONS as readonly string[]).includes(action)) {\n this.logger.error(\n `Unknown component action \"${action}\" for component with id \"${id}\"`,\n `Valid actions are ${COMPONENT_ACTIONS.map((a) => `\"${a}\"`).join(\n ', ',\n )}`,\n );\n }\n });\n apply(root, {}, componentsState);\n }\n\n /**\n * Set up real-time conditions for the current screen. Safe to call\n * twice — a second call rebuilds from screenState.\n *\n * Must run AFTER `updateScreenFromScreenState`, so the DOM reads below\n * see both server-shipped values and any component defaults from the\n * HTML.\n */\n initRealtimeConditions(\n rootElement: HTMLElement,\n screenState: ScreenState | undefined,\n ): void {\n this.#teardownRealtimeRuntime();\n\n const conditions = screenState?.realtimeComponentsConditions ?? [];\n if (!conditions.length) {\n this.logger.debug(\n `${LOG_PREFIX} no real-time rules to apply on this screen`,\n );\n return;\n }\n this.logger.info(\n `${LOG_PREFIX} found ${conditions.length} real-time rule(s) for this screen`,\n );\n\n // screenState.form uses \"phone\"; rules reference \"form.phone\".\n // Add the prefix on the way in.\n const initialSnapshot: FormSnapshot = {};\n Object.entries(screenState?.form ?? {}).forEach(([k, v]) => {\n initialSnapshot[`form.${k}`] = v;\n });\n\n // For every key the rules reference, read the current DOM value.\n // Component defaults (e.g. `checked=\"true\"` on a descope-checkbox)\n // live only in the HTML and don't make it into screenState.form, so\n // without this read the first evaluation would miss them.\n collectReferencedFormKeys(conditions).forEach((formKey) => {\n const el = findInputForFormKey(rootElement, formKey);\n if (!el) return;\n const v = readInputValue(el);\n if (v !== undefined) initialSnapshot[formKey] = v;\n });\n\n const touchedIds = collectTouchedComponentIds(conditions);\n\n // What to fall back to when a real-time rule stops matching for a\n // touched component — the actions set by server-only rules (rules\n // with no client-side conditions).\n const serverBaseline: Record<string, string> = {};\n // What's already painted on the DOM (touched components only), so\n // the first real-time evaluation can diff against the right state.\n const initialApplied: Record<string, string> = {};\n\n Object.entries(screenState?.componentsState ?? {}).forEach(\n ([id, action]) => {\n if (!touchedIds.has(id)) return;\n initialApplied[id] = action;\n },\n );\n\n Object.entries(screenState?.serverOnlyComponentsState ?? {}).forEach(\n ([id, action]) => {\n if (touchedIds.has(id)) {\n serverBaseline[id] = action;\n }\n },\n );\n\n const runtime: RealtimeRuntime = {\n conditions,\n touchedIds,\n snapshot: initialSnapshot,\n applied: initialApplied,\n serverBaseline,\n debounceTimer: null,\n paused: false,\n unsubscribePauseListener: null,\n inputHandler: () => {},\n root: rootElement,\n };\n\n // Re-run the rules now that we've read the real DOM values. The\n // server evaluated without seeing component defaults, so its\n // `componentsState` can disagree with what the user actually sees.\n // Apply the diff once before listening for input.\n const reconciled = effectiveActions(\n evaluateAll(conditions, initialSnapshot),\n serverBaseline,\n touchedIds,\n );\n if (!shallowEqualStringMap(initialApplied, reconciled)) {\n runtime.applied = apply(rootElement, initialApplied, reconciled);\n }\n\n runtime.inputHandler = (e: Event) =>\n this.#handleRealtimeInput(e as InputEvent);\n\n REALTIME_CONDITION_EVENTS.forEach((ev) => {\n rootElement.addEventListener(ev, runtime.inputHandler, true);\n });\n this.logger.debug(\n `${LOG_PREFIX} listening for \"${REALTIME_CONDITION_EVENTS.join(\n '\" and \"',\n )}\" events on form fields; ${\n Object.keys(initialApplied).length\n } component(s) start hidden / disabled / read-only by these rules`,\n );\n\n // Pause while a /next request is in flight. Without this, a debounced\n // evaluation could run between submit and the next screen render and\n // change components that are about to be replaced — causing flicker,\n // or hiding something the next screen needs visible.\n const pauseState = (this as unknown as PausableHost).nextRequestStatus;\n if (pauseState?.subscribe) {\n const handler = ({ isLoading }: { isLoading: boolean }) => {\n runtime.paused = isLoading;\n if (isLoading && runtime.debounceTimer) {\n clearTimeout(runtime.debounceTimer);\n runtime.debounceTimer = null;\n }\n };\n // subscribe returns a token; unsubscribe needs that token, not the\n // handler. Without storing it, handlers leak across screens and\n // keep old runtimes (and their DOM roots) alive.\n const token = pauseState.subscribe(handler);\n runtime.unsubscribePauseListener = () => {\n if (token !== undefined && token !== null) {\n pauseState.unsubscribe?.(token);\n }\n };\n }\n\n this.#rtRuntime = runtime;\n }\n\n #handleRealtimeInput(e: InputEvent): void {\n const runtime = this.#rtRuntime;\n if (!runtime.root || runtime.paused) return;\n\n const target = e.target as Element | null;\n if (!target) return;\n if (target.hasAttribute?.(DESCOPE_ATTRIBUTE_EXCLUDE_FIELD)) return;\n\n const name = target.getAttribute?.('name');\n if (!name) return;\n\n // Update the snapshot only — evaluation is debounced. Use readInputValue\n // so checkboxes read the same way as at mount; otherwise `target.value`\n // would be the string \"on\" for native checkboxes and break is-true rules.\n const key = toFormKey(name);\n runtime.snapshot[key] = readInputValue(target);\n\n if (runtime.debounceTimer) {\n clearTimeout(runtime.debounceTimer);\n }\n runtime.debounceTimer = setTimeout(() => {\n runtime.debounceTimer = null;\n this.#reEvaluateRealtime();\n }, REALTIME_CONDITION_DEBOUNCE_MS);\n }\n\n #reEvaluateRealtime(): void {\n const runtime = this.#rtRuntime;\n if (!runtime.root) return;\n\n let next: Record<string, string>;\n try {\n next = effectiveActions(\n evaluateAll(runtime.conditions, runtime.snapshot),\n runtime.serverBaseline,\n runtime.touchedIds,\n );\n } catch (e) {\n this.logger.error(\n `${LOG_PREFIX} failed to evaluate real-time rules — keeping the previous state`,\n (e as Error)?.message,\n );\n return;\n }\n\n const prevApplied = runtime.applied;\n if (shallowEqualStringMap(prevApplied, next)) return;\n\n this.logger.debug(\n `${LOG_PREFIX} form changed — updating components: was ${JSON.stringify(\n prevApplied,\n )}, now ${JSON.stringify(next)}`,\n );\n runtime.applied = apply(runtime.root, prevApplied, next);\n }\n\n // Clean up listeners and timers when the host leaves the DOM. Reaches\n // us only if BaseDescopeWc calls `super.disconnectedCallback?.()`;\n // otherwise teardown happens lazily on the next initRealtimeConditions.\n disconnectedCallback() {\n // disconnectedCallback isn't on HTMLElement in the lib types, but it\n // exists at runtime — forward into super in case the chain uses it.\n super.disconnectedCallback?.();\n this.#teardownRealtimeRuntime();\n }\n\n #teardownRealtimeRuntime(): void {\n const r = this.#rtRuntime;\n if (r.debounceTimer) {\n clearTimeout(r.debounceTimer);\n }\n if (r.unsubscribePauseListener) {\n r.unsubscribePauseListener();\n }\n if (r.root) {\n // Deliberately NOT undoing what we applied. `r.root` is the host's\n // content root, which is built once in the constructor and never\n // replaced. Only its children are. By the time we get here the caller\n // has already swapped in the next screen, so looking our component\n // ids up in `r.root` finds the NEW screen's elements and would strip\n // the state the server just painted on them. Nothing needs undoing\n // anyway, because the elements we touched went with the old screen.\n REALTIME_CONDITION_EVENTS.forEach((ev) => {\n r.root!.removeEventListener(ev, r.inputHandler, true);\n });\n }\n this.#rtRuntime = emptyRuntime();\n }\n };\n },\n);\n"],"names":["LOG_PREFIX","readInputValue","el","HTMLInputElement","type","checked","value","shallowEqualStringMap","a","b","keysA","Object","keys","keysB","length","every","k","emptyRuntime","conditions","touchedIds","Set","snapshot","applied","serverBaseline","debounceTimer","paused","unsubscribePauseListener","inputHandler","root","effectiveActions","realtimeVerdict","out","forEach","id","componentConditionsMixin","createSingletonMixin","superclass","BaseClass","compose","loggerMixin","_a","constructor","_ComponentConditionsMixin_rtRuntime","set","this","applyComponentsState","componentsState","entries","action","COMPONENT_ACTIONS","includes","logger","error","map","join","apply","initRealtimeConditions","rootElement","screenState","__classPrivateFieldGet","_ComponentConditionsMixin_instances","_ComponentConditionsMixin_teardownRealtimeRuntime","call","_b","realtimeComponentsConditions","debug","info","initialSnapshot","_c","form","v","collectReferencedFormKeys","formKey","bare","startsWith","slice","querySelector","escapeSelector","findInputForFormKey","undefined","collectTouchedComponentIds","initialApplied","_d","has","_e","serverOnlyComponentsState","runtime","reconciled","evaluateAll","e","REALTIME_CONDITION_EVENTS","ev","addEventListener","pauseState","nextRequestStatus","subscribe","handler","isLoading","clearTimeout","token","unsubscribe","__classPrivateFieldSet","disconnectedCallback","super","target","hasAttribute","DESCOPE_ATTRIBUTE_EXCLUDE_FIELD","name","getAttribute","key","toFormKey","setTimeout","_ComponentConditionsMixin_reEvaluateRealtime","REALTIME_CONDITION_DEBOUNCE_MS","next","message","prevApplied","JSON","stringify","r","removeEventListener"],"mappings":"6nBAqBA,MAAMA,EAAa,wBAgEnB,SAASC,EAAeC,GACtB,OAAIA,aAAcC,iBACG,aAAZD,EAAGE,KAAsBF,EAAGG,QAAUH,EAAGI,MAE9C,YAAaJ,EACPA,EAAuCG,QAE7C,UAAWH,EACLA,EAAqCI,WAD/C,CAIF,CAEA,SAASC,EACPC,EACAC,GAEA,MAAMC,EAAQ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nD,CAuQoBG,CAAUH,GACtBrB,EAAQjE,SAASwF,GAAO5G,EAAeuG,GAEnClB,EAAQ9D,eACV0E,aAAaZ,EAAQ9D,eAEvB8D,EAAQ9D,cAAgBuF,YAAW,KACjCzB,EAAQ9D,cAAgB,KACxBmC,EAAAf,KAAIgB,EAAA,IAAAoD,GAAJlD,KAAAlB,KAA0B,GACzBqE,EACJ,eAGC,MAAM3B,EAAU3B,EAAAf,YAChB,IAAK0C,EAAQ1D,KAAM,OAEnB,IAAIsF,EACJ,IACEA,EAAOrF,EACL2D,EAAYF,EAAQpE,WAAYoE,EAAQjE,UACxCiE,EAAQ/D,eACR+D,EAAQnE,WAEX,CAAC,MAAOsE,GAKP,YAJA7C,KAAKO,OAAOC,MACV,GAAGpD,oEACFyF,aAAC,EAADA,EAAa0B,QAGjB,CAED,MAAMC,EAAc9B,EAAQhE,QACxBf,EAAsB6G,EAAaF,KAEvCtE,KAAKO,OAAOc,MACV,GAAGjE,6CAAsDqH,KAAKC,UAC5DF,WACQC,KAAKC,UAAUJ,MAE3B5B,EAAQhE,QAAUiC,EAAM+B,EAAQ1D,KAAMwF,EAAaF,GACpD,eAaC,MAAMK,EAAI5D,EAAAf,YACN2E,EAAE/F,eACJ0E,aAAaqB,EAAE/F,eAEb+F,EAAE7F,0BACJ6F,EAAE7F,2BAEA6F,EAAE3F,MAQJ8D,EAA0B1D,SAAS2D,IACjC4B,EAAE3F,KAAM4F,oBAAoB7B,EAAI4B,EAAE5F,cAAc,EAAK,IAGzD0E,EAAAzD,KAAIF,EAAczB,QACnB,EACDuB,CAAA"}
|
|
1
|
+
{"version":3,"file":"componentConditionsMixin.js","sources":["../../../src/lib/mixins/componentConditionsMixin.ts"],"sourcesContent":["/* eslint-disable import/prefer-default-export, no-param-reassign */\nimport { compose, createSingletonMixin } from '@descope/sdk-helpers';\nimport { loggerMixin } from '@descope/sdk-mixins';\nimport {\n REALTIME_CONDITION_DEBOUNCE_MS,\n REALTIME_CONDITION_EVENTS,\n} from '../helpers/realtime-conditions/config';\nimport {\n collectReferencedFormKeys,\n collectTouchedComponentIds,\n evaluateAll,\n FormSnapshot,\n} from '../helpers/realtime-conditions/evaluator';\nimport {\n apply,\n COMPONENT_ACTIONS,\n escapeSelector,\n} from '../helpers/realtime-conditions/applier';\nimport { DESCOPE_ATTRIBUTE_EXCLUDE_FIELD } from '../constants';\nimport type { RealtimeComponentsCondition, ScreenState } from '../types';\n\nconst LOG_PREFIX = 'component-conditions:';\n\n// What the mixin needs from its host: a way to subscribe to loading state\n// so input handling can pause while the next request is in flight. Defined\n// as an interface (not imported) to avoid a circular dependency on BaseDescopeWc.\nexport interface PausableHost {\n nextRequestStatus?: {\n // subscribe returns a token; pass that token to unsubscribe — not the handler.\n subscribe: (cb: (v: { isLoading: boolean }) => void) => string;\n unsubscribe?: (token: string) => void;\n };\n}\n\nexport interface RealtimeRuntime {\n conditions: RealtimeComponentsCondition[];\n // IDs of components that any rule can change\n touchedIds: Set<string>;\n // latest form values on screen\n snapshot: FormSnapshot;\n // what's currently applied on screen for touched components.\n // Compared against on each re-evaluation to know what to change.\n applied: Record<string, string>;\n // What the server told us to apply for these components. Stays fixed for\n // the screen's lifetime so we can fall back to it when a real-time rule\n // stops matching. Without this, a server-set action could disappear when\n // a real-time rule briefly fires on the same component.\n serverBaseline: Record<string, string>;\n debounceTimer: ReturnType<typeof setTimeout> | null;\n // true while paused (during submit, to avoid stale updates)\n paused: boolean;\n unsubscribePauseListener: (() => void) | null;\n // the listener we attach to form events (kept so we can detach)\n inputHandler: (e: Event) => void;\n // the screen root we work against\n root: HTMLElement | null;\n}\n\n// Some inputs already have `name=\"form.x\"`, others use `name=\"x\"`. Always\n// return the `form.x` form so it lines up with what rules reference.\nfunction toFormKey(name: string): string {\n return name.startsWith('form.') ? name : `form.${name}`;\n}\n\n// Try the full `form.x` first (descope components), then `x` (plain inputs).\nfunction findInputForFormKey(\n root: ParentNode,\n formKey: string,\n): Element | null {\n const bare = formKey.startsWith('form.')\n ? formKey.slice('form.'.length)\n : formKey;\n return (\n root.querySelector(`[name=\"${escapeSelector(formKey)}\"]`) ||\n root.querySelector(`[name=\"${escapeSelector(bare)}\"]`)\n );\n}\n\n// Read the current value off a form input. Reads JS properties (not HTML\n// attributes) so we pick up both the component's default and any value\n// carried over from earlier screens.\n//\n// Native <input type=checkbox> needs special handling: `.value` is always\n// \"on\", only `.checked` reflects the real state. Descope boolean components\n// (descope-checkbox, descope-switch-toggle) expose `.checked` on their class.\nfunction readInputValue(el: Element): unknown {\n if (el instanceof HTMLInputElement) {\n return el.type === 'checkbox' ? el.checked : el.value;\n }\n if ('checked' in el) {\n return (el as unknown as { checked: boolean }).checked;\n }\n if ('value' in el) {\n return (el as unknown as { value: unknown }).value;\n }\n return undefined;\n}\n\nfunction shallowEqualStringMap(\n a: Record<string, string>,\n b: Record<string, string>,\n): boolean {\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n if (keysA.length !== keysB.length) return false;\n return keysA.every((k) => a[k] === b[k]);\n}\n\nfunction emptyRuntime(): RealtimeRuntime {\n return {\n conditions: [],\n touchedIds: new Set(),\n snapshot: {},\n applied: {},\n serverBaseline: {},\n debounceTimer: null,\n paused: false,\n unsubscribePauseListener: null,\n inputHandler: () => {},\n root: null,\n };\n}\n\n// For each touched component, pick the real-time action if a rule is firing\n// for it, otherwise fall back to the server's action. Components that no rule\n// touches are not in the result — those were already painted by\n// applyComponentsState.\nfunction effectiveActions(\n realtimeVerdict: Record<string, string>,\n serverBaseline: Record<string, string>,\n touchedIds: Set<string>,\n): Record<string, string> {\n const out: Record<string, string> = {};\n touchedIds.forEach((id) => {\n if (realtimeVerdict[id]) {\n out[id] = realtimeVerdict[id];\n } else if (serverBaseline[id]) {\n out[id] = serverBaseline[id];\n }\n });\n return out;\n}\n\nexport const componentConditionsMixin = createSingletonMixin(\n <T extends CustomElementConstructor>(superclass: T) => {\n // Pull in loggerMixin so `this.logger` is available no matter where\n // this mixin sits in the chain.\n const BaseClass = compose(loggerMixin)(superclass);\n\n return class ComponentConditionsMixin extends BaseClass {\n // One runtime per <descope-wc> element.\n #rtRuntime: RealtimeRuntime = emptyRuntime();\n\n /**\n * Apply the server's hide/disable/read-only actions to the DOM.\n * Logs unknown actions here (runs once per screen) but stays quiet on\n * the keystroke path to avoid log spam.\n */\n applyComponentsState(\n root: ParentNode,\n componentsState: Record<string, string> | undefined,\n ): void {\n if (!componentsState) return;\n Object.entries(componentsState).forEach(([id, action]) => {\n if (!(COMPONENT_ACTIONS as readonly string[]).includes(action)) {\n this.logger.error(\n `Unknown component action \"${action}\" for component with id \"${id}\"`,\n `Valid actions are ${COMPONENT_ACTIONS.map((a) => `\"${a}\"`).join(\n ', ',\n )}`,\n );\n }\n });\n apply(root, {}, componentsState);\n }\n\n /**\n * Set up real-time conditions for the current screen. Safe to call\n * twice — a second call rebuilds from screenState.\n *\n * Must run AFTER `updateScreenFromScreenState`, so the DOM reads below\n * see both server-shipped values and any component defaults from the\n * HTML.\n */\n initRealtimeConditions(\n rootElement: HTMLElement,\n screenState: ScreenState | undefined,\n ): void {\n this.#teardownRealtimeRuntime();\n\n const conditions = screenState?.realtimeComponentsConditions ?? [];\n if (!conditions.length) {\n this.logger.debug(\n `${LOG_PREFIX} no real-time rules to apply on this screen`,\n );\n return;\n }\n this.logger.info(\n `${LOG_PREFIX} found ${conditions.length} real-time rule(s) for this screen`,\n );\n\n // screenState.form uses \"phone\"; rules reference \"form.phone\".\n // Add the prefix on the way in.\n const initialSnapshot: FormSnapshot = {};\n Object.entries(screenState?.form ?? {}).forEach(([k, v]) => {\n initialSnapshot[`form.${k}`] = v;\n });\n\n // For every key the rules reference, read the current DOM value.\n // Component defaults (e.g. `checked=\"true\"` on a descope-checkbox)\n // live only in the HTML and don't make it into screenState.form, so\n // without this read the first evaluation would miss them.\n collectReferencedFormKeys(conditions).forEach((formKey) => {\n const el = findInputForFormKey(rootElement, formKey);\n if (!el) return;\n const v = readInputValue(el);\n if (v !== undefined) initialSnapshot[formKey] = v;\n });\n\n const touchedIds = collectTouchedComponentIds(conditions);\n\n // What to fall back to when a real-time rule stops matching for a\n // touched component — the actions set by server-only rules (rules\n // with no client-side conditions).\n const serverBaseline: Record<string, string> = {};\n // What's already painted on the DOM (touched components only), so\n // the first real-time evaluation can diff against the right state.\n const initialApplied: Record<string, string> = {};\n\n Object.entries(screenState?.componentsState ?? {}).forEach(\n ([id, action]) => {\n if (!touchedIds.has(id)) return;\n initialApplied[id] = action;\n },\n );\n\n Object.entries(screenState?.serverOnlyComponentsState ?? {}).forEach(\n ([id, action]) => {\n if (touchedIds.has(id)) {\n serverBaseline[id] = action;\n }\n },\n );\n\n const runtime: RealtimeRuntime = {\n conditions,\n touchedIds,\n snapshot: initialSnapshot,\n applied: initialApplied,\n serverBaseline,\n debounceTimer: null,\n paused: false,\n unsubscribePauseListener: null,\n inputHandler: () => {},\n root: rootElement,\n };\n\n // Re-run the rules now that we've read the real DOM values. The\n // server evaluated without seeing component defaults, so its\n // `componentsState` can disagree with what the user actually sees.\n // Apply the diff once before listening for input.\n const reconciled = effectiveActions(\n evaluateAll(conditions, initialSnapshot),\n serverBaseline,\n touchedIds,\n );\n if (!shallowEqualStringMap(initialApplied, reconciled)) {\n runtime.applied = apply(rootElement, initialApplied, reconciled);\n }\n\n runtime.inputHandler = (e: Event) =>\n this.#handleRealtimeInput(e as InputEvent);\n\n REALTIME_CONDITION_EVENTS.forEach((ev) => {\n rootElement.addEventListener(ev, runtime.inputHandler, true);\n });\n this.logger.debug(\n `${LOG_PREFIX} listening for \"${REALTIME_CONDITION_EVENTS.join(\n '\" and \"',\n )}\" events on form fields; ${\n Object.keys(initialApplied).length\n } component(s) start hidden / disabled / read-only by these rules`,\n );\n\n // Pause while a /next request is in flight. Without this, a debounced\n // evaluation could run between submit and the next screen render and\n // change components that are about to be replaced — causing flicker,\n // or hiding something the next screen needs visible.\n const pauseState = (this as unknown as PausableHost).nextRequestStatus;\n if (pauseState?.subscribe) {\n const handler = ({ isLoading }: { isLoading: boolean }) => {\n runtime.paused = isLoading;\n if (isLoading && runtime.debounceTimer) {\n clearTimeout(runtime.debounceTimer);\n runtime.debounceTimer = null;\n }\n };\n // subscribe returns a token; unsubscribe needs that token, not the\n // handler. Without storing it, handlers leak across screens and\n // keep old runtimes (and their DOM roots) alive.\n const token = pauseState.subscribe(handler);\n runtime.unsubscribePauseListener = () => {\n if (token !== undefined && token !== null) {\n pauseState.unsubscribe?.(token);\n }\n };\n }\n\n this.#rtRuntime = runtime;\n }\n\n #handleRealtimeInput(e: InputEvent): void {\n const runtime = this.#rtRuntime;\n if (!runtime.root || runtime.paused) return;\n\n const target = e.target as Element | null;\n if (!target) return;\n if (target.hasAttribute?.(DESCOPE_ATTRIBUTE_EXCLUDE_FIELD)) return;\n\n const name = target.getAttribute?.('name');\n if (!name) return;\n\n // Update the snapshot only — evaluation is debounced. Use readInputValue\n // so checkboxes read the same way as at mount; otherwise `target.value`\n // would be the string \"on\" for native checkboxes and break is-true rules.\n const key = toFormKey(name);\n runtime.snapshot[key] = readInputValue(target);\n\n if (runtime.debounceTimer) {\n clearTimeout(runtime.debounceTimer);\n }\n runtime.debounceTimer = setTimeout(() => {\n runtime.debounceTimer = null;\n this.#reEvaluateRealtime();\n }, REALTIME_CONDITION_DEBOUNCE_MS);\n }\n\n #reEvaluateRealtime(): void {\n const runtime = this.#rtRuntime;\n if (!runtime.root) return;\n\n let next: Record<string, string>;\n try {\n next = effectiveActions(\n evaluateAll(runtime.conditions, runtime.snapshot),\n runtime.serverBaseline,\n runtime.touchedIds,\n );\n } catch (e) {\n this.logger.error(\n `${LOG_PREFIX} failed to evaluate real-time rules — keeping the previous state`,\n (e as Error)?.message,\n );\n return;\n }\n\n const prevApplied = runtime.applied;\n if (shallowEqualStringMap(prevApplied, next)) return;\n\n this.logger.debug(\n `${LOG_PREFIX} form changed — updating components: was ${JSON.stringify(\n prevApplied,\n )}, now ${JSON.stringify(next)}`,\n );\n runtime.applied = apply(runtime.root, prevApplied, next);\n }\n\n // Clean up listeners and timers when the host leaves the DOM. Reaches\n // us only if BaseDescopeWc calls `super.disconnectedCallback?.()`;\n // otherwise teardown happens lazily on the next initRealtimeConditions.\n disconnectedCallback() {\n // disconnectedCallback isn't on HTMLElement in the lib types, but it\n // exists at runtime — forward into super in case the chain uses it.\n super.disconnectedCallback?.();\n this.#teardownRealtimeRuntime();\n }\n\n #teardownRealtimeRuntime(): void {\n const r = this.#rtRuntime;\n if (r.debounceTimer) {\n clearTimeout(r.debounceTimer);\n }\n if (r.unsubscribePauseListener) {\n r.unsubscribePauseListener();\n }\n if (r.root) {\n // Deliberately NOT undoing what we applied. `r.root` is the host's\n // content root, which is built once in the constructor and never\n // replaced. Only its children are. By the time we get here the caller\n // has already swapped in the next screen, so looking our component\n // ids up in `r.root` finds the NEW screen's elements and would strip\n // the state the server just painted on them. Nothing needs undoing\n // anyway, because the elements we touched went with the old screen.\n REALTIME_CONDITION_EVENTS.forEach((ev) => {\n r.root!.removeEventListener(ev, r.inputHandler, true);\n });\n }\n this.#rtRuntime = emptyRuntime();\n }\n };\n },\n);\n"],"names":["LOG_PREFIX","readInputValue","el","HTMLInputElement","type","checked","value","shallowEqualStringMap","a","b","keysA","Object","keys","keysB","length","every","k","emptyRuntime","conditions","touchedIds","Set","snapshot","applied","serverBaseline","debounceTimer","paused","unsubscribePauseListener","inputHandler","root","effectiveActions","realtimeVerdict","out","forEach","id","componentConditionsMixin","createSingletonMixin","superclass","BaseClass","compose","loggerMixin","_a","constructor","_ComponentConditionsMixin_rtRuntime","set","this","applyComponentsState","componentsState","entries","action","COMPONENT_ACTIONS","includes","logger","error","map","join","apply","initRealtimeConditions","rootElement","screenState","__classPrivateFieldGet","_ComponentConditionsMixin_instances","_ComponentConditionsMixin_teardownRealtimeRuntime","call","_b","realtimeComponentsConditions","debug","info","initialSnapshot","_c","form","v","collectReferencedFormKeys","formKey","bare","startsWith","slice","querySelector","escapeSelector","findInputForFormKey","undefined","collectTouchedComponentIds","initialApplied","_d","has","_e","serverOnlyComponentsState","runtime","reconciled","evaluateAll","e","REALTIME_CONDITION_EVENTS","ev","addEventListener","pauseState","nextRequestStatus","subscribe","handler","isLoading","clearTimeout","token","unsubscribe","__classPrivateFieldSet","disconnectedCallback","super","target","hasAttribute","DESCOPE_ATTRIBUTE_EXCLUDE_FIELD","name","getAttribute","key","toFormKey","setTimeout","_ComponentConditionsMixin_reEvaluateRealtime","REALTIME_CONDITION_DEBOUNCE_MS","next","message","prevApplied","JSON","stringify","r","removeEventListener"],"mappings":"6nBAqBA,MAAMA,EAAa,wBAgEnB,SAASC,EAAeC,GACtB,OAAIA,aAAcC,iBACG,aAAZD,EAAGE,KAAsBF,EAAGG,QAAUH,EAAGI,MAE9C,YAAaJ,EACPA,EAAuCG,QAE7C,UAAWH,EACLA,EAAqCI,WAD/C,CAIF,CAEA,SAASC,EACPC,EACAC,GAEA,MAAMC,EAAQC,OAAOC,KAAKJ,GACpBK,EAAQF,OAAOC,KAAKH,GAC1B,OAAIC,EAAMI,SAAWD,EAAMC,QACpBJ,EAAMK,OAAOC,GAAMR,EAAEQ,KAAOP,EAAEO,IACvC,CAEA,SAASC,IACP,MAAO,CACLC,WAAY,GACZC,WAAY,IAAIC,IAChBC,SAAU,CAAA,EACVC,QAAS,CAAA,EACTC,eAAgB,CAAA,EAChBC,cAAe,KACfC,QAAQ,EACRC,yBAA0B,KAC1BC,aAAc,OACdC,KAAM,KAEV,CAMA,SAASC,EACPC,EACAP,EACAJ,GAEA,MAAMY,EAA8B,CAAA,EAQpC,OAPAZ,EAAWa,SAASC,IACdH,EAAgBG,GAClBF,EAAIE,GAAMH,EAAgBG,GACjBV,EAAeU,KACxBF,EAAIE,GAAMV,EAAeU,GAC3B,IAEKF,CACT,OAEaG,EAA2BC,GACDC,oBAGnC,MAAMC,EAAYC,EAAQC,EAARD,CAAqBF,GAEvC,OAAAI,EAAO,cAAuCH,EAAvC,WAAAI,mCAELC,EAAAC,IAAAC,KAA8B3B,IAwPhC,CAjPE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B,EAAQhE,QAAUiC,EAAM+B,EAAQ1D,KAAMwF,EAAaF,GACrD,eAaE,MAAMK,EAAI5D,EAAAf,YACN2E,EAAE/F,eACJ0E,aAAaqB,EAAE/F,eAEb+F,EAAE7F,0BACJ6F,EAAE7F,2BAEA6F,EAAE3F,MAQJ8D,EAA0B1D,SAAS2D,IACjC4B,EAAE3F,KAAM4F,oBAAoB7B,EAAI4B,EAAE5F,cAAc,EAAK,IAGzD0E,EAAAzD,KAAIF,EAAczB,QACpB,EACAuB,CAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"duplicateFlowWarningMixin.js","sources":["../../../src/lib/mixins/duplicateFlowWarningMixin.ts"],"sourcesContent":["/* eslint-disable import/prefer-default-export */\nimport { compose, createSingletonMixin } from '@descope/sdk-helpers';\nimport { loggerMixin } from '@descope/sdk-mixins';\n\nconst DESCOPE_WC_TAG = 'descope-wc';\nconst PROJECT_ID_ATTR = 'project-id';\nconst FLOW_ID_ATTR = 'flow-id';\n\n/**\n * All `<descope-wc>` elements in `el`'s document that run the same project-id\n * and flow-id as `el` (including `el` itself), in document order. Empty when\n * `el` is missing either attribute.\n */\nexport const getSameFlowInstances = (el: Element): Element[] => {\n const projectId = el.getAttribute(PROJECT_ID_ATTR);\n const flowId = el.getAttribute(FLOW_ID_ATTR);\n if (!projectId || !flowId) return [];\n return Array.from(el.ownerDocument.querySelectorAll(DESCOPE_WC_TAG)).filter(\n (other) =>\n other.getAttribute(PROJECT_ID_ATTR) === projectId &&\n other.getAttribute(FLOW_ID_ATTR) === flowId,\n );\n};\n\n/**\n * True when `el` is a same-flow duplicate that is NOT the first such element in\n * document order. Reporting only from the non-first element means exactly one\n * element per same-flow group reports `true`, so a single warning is emitted\n * regardless of how many duplicates exist. Note: light-DOM only — duplicates\n * nested inside another component's shadow root are intentionally not detected.\n */\nexport const isDuplicateSameFlowInstance = (el: Element): boolean => {\n const sameFlow = getSameFlowInstances(el);\n return sameFlow.length > 1 && sameFlow[0] !== el;\n};\n\n/**\n * Logs a one-time dev warning when more than one `<descope-wc>` on the page runs\n * the same project-id + flow-id. Rendering the same flow more than once is not\n * supported (it causes the post-login screen to flicker, among other issues).\n * Warning only — no behavior change. Hooks `connectedCallback` (not `init`) and\n * pulls in only `loggerMixin`, to avoid participating in the flow `init()` chain.\n */\nexport const duplicateFlowWarningMixin = createSingletonMixin(\n <T extends CustomElementConstructor>(superclass: T) => {\n const BaseClass = compose(loggerMixin)(superclass);\n\n return class DuplicateFlowWarningMixinClass extends BaseClass {\n // The project|flow key this element has already warned for, so we warn at\n // most once per identity. connectedCallback can fire multiple times for\n // the same element (e.g. formMountMixin re-parents it into a <form>), so a\n // plain per-call warning would fire repeatedly.\n #warnedForKey?: string;\n\n #scheduleDuplicateFlowCheck() {\n // Defer so sibling instances mounted in the same tick are attached to\n // the DOM before we query it.\n queueMicrotask(() => {\n if (!this.isConnected) return;\n const projectId = this.getAttribute(PROJECT_ID_ATTR);\n const flowId = this.getAttribute(FLOW_ID_ATTR);\n const key = `${projectId}|${flowId}`;\n // Bail before the DOM query when we've already warned for this\n // identity — connectedCallback can fire several times per element.\n if (\n this.#warnedForKey === key ||\n !isDuplicateSameFlowInstance(this)\n ) {\n return;\n }\n this.#warnedForKey = key;\n this.logger.warn(\n 'Multiple Descope flow components detected on the same page',\n `The same flow (\"${flowId}\") and project (\"${projectId}\") are running more than once on this page. This is not supported and may cause the flow to behave unexpectedly.`,\n );\n });\n }\n\n connectedCallback() {\n super.connectedCallback?.();\n this.#scheduleDuplicateFlowCheck();\n }\n\n // Re-check when the flow identity changes at runtime. BaseDescopeWc\n // forwards `super.attributeChangedCallback?.()`; the `#warnedForKey`\n // de-dupe keeps this to one warning even if it also fires on mount.\n attributeChangedCallback(\n attrName: string,\n oldValue: string,\n newValue: string,\n ) {\n super.attributeChangedCallback?.(attrName, oldValue, newValue);\n if (\n oldValue !== newValue &&\n (attrName === PROJECT_ID_ATTR || attrName === FLOW_ID_ATTR)\n ) {\n this.#scheduleDuplicateFlowCheck();\n }\n }\n };\n },\n);\n"],"names":["PROJECT_ID_ATTR","FLOW_ID_ATTR","getSameFlowInstances","el","projectId","getAttribute","flowId","Array","from","ownerDocument","querySelectorAll","filter","other","isDuplicateSameFlowInstance","sameFlow","length","duplicateFlowWarningMixin","createSingletonMixin","superclass","BaseClass","compose","loggerMixin","_a","constructor","_DuplicateFlowWarningMixinClass_warnedForKey","set","this","connectedCallback","_b","super","call","__classPrivateFieldGet","_DuplicateFlowWarningMixinClass_instances","_DuplicateFlowWarningMixinClass_scheduleDuplicateFlowCheck","attributeChangedCallback","attrName","oldValue","newValue","queueMicrotask","isConnected","key","__classPrivateFieldSet","logger","warn"],"mappings":"sMAIA,MACMA,EAAkB,aAClBC,EAAe,UAORC,EAAwBC,IACnC,MAAMC,EAAYD,EAAGE,aAAaL,GAC5BM,EAASH,EAAGE,aAAaJ,GAC/B,OAAKG,GAAcE,EACZC,MAAMC,KAAKL,EAAGM,cAAcC,iBAbd,eAagDC,QAClEC,GACCA,EAAMP,aAAaL,KAAqBI,GACxCQ,EAAMP,aAAaJ,KAAkBK,IAJP,EAKjC,EAUUO,EAA+BV,IAC1C,MAAMW,EAAWZ,EAAqBC,GACtC,OAAOW,EAASC,OAAS,GAAKD,EAAS,KAAOX,CAAE,EAUrCa,EAA4BC,GACFC,gBACnC,MAAMC,EAAYC,EAAQC,EAARD,CAAqBF,GAEvC,
|
|
1
|
+
{"version":3,"file":"duplicateFlowWarningMixin.js","sources":["../../../src/lib/mixins/duplicateFlowWarningMixin.ts"],"sourcesContent":["/* eslint-disable import/prefer-default-export */\nimport { compose, createSingletonMixin } from '@descope/sdk-helpers';\nimport { loggerMixin } from '@descope/sdk-mixins';\n\nconst DESCOPE_WC_TAG = 'descope-wc';\nconst PROJECT_ID_ATTR = 'project-id';\nconst FLOW_ID_ATTR = 'flow-id';\n\n/**\n * All `<descope-wc>` elements in `el`'s document that run the same project-id\n * and flow-id as `el` (including `el` itself), in document order. Empty when\n * `el` is missing either attribute.\n */\nexport const getSameFlowInstances = (el: Element): Element[] => {\n const projectId = el.getAttribute(PROJECT_ID_ATTR);\n const flowId = el.getAttribute(FLOW_ID_ATTR);\n if (!projectId || !flowId) return [];\n return Array.from(el.ownerDocument.querySelectorAll(DESCOPE_WC_TAG)).filter(\n (other) =>\n other.getAttribute(PROJECT_ID_ATTR) === projectId &&\n other.getAttribute(FLOW_ID_ATTR) === flowId,\n );\n};\n\n/**\n * True when `el` is a same-flow duplicate that is NOT the first such element in\n * document order. Reporting only from the non-first element means exactly one\n * element per same-flow group reports `true`, so a single warning is emitted\n * regardless of how many duplicates exist. Note: light-DOM only — duplicates\n * nested inside another component's shadow root are intentionally not detected.\n */\nexport const isDuplicateSameFlowInstance = (el: Element): boolean => {\n const sameFlow = getSameFlowInstances(el);\n return sameFlow.length > 1 && sameFlow[0] !== el;\n};\n\n/**\n * Logs a one-time dev warning when more than one `<descope-wc>` on the page runs\n * the same project-id + flow-id. Rendering the same flow more than once is not\n * supported (it causes the post-login screen to flicker, among other issues).\n * Warning only — no behavior change. Hooks `connectedCallback` (not `init`) and\n * pulls in only `loggerMixin`, to avoid participating in the flow `init()` chain.\n */\nexport const duplicateFlowWarningMixin = createSingletonMixin(\n <T extends CustomElementConstructor>(superclass: T) => {\n const BaseClass = compose(loggerMixin)(superclass);\n\n return class DuplicateFlowWarningMixinClass extends BaseClass {\n // The project|flow key this element has already warned for, so we warn at\n // most once per identity. connectedCallback can fire multiple times for\n // the same element (e.g. formMountMixin re-parents it into a <form>), so a\n // plain per-call warning would fire repeatedly.\n #warnedForKey?: string;\n\n #scheduleDuplicateFlowCheck() {\n // Defer so sibling instances mounted in the same tick are attached to\n // the DOM before we query it.\n queueMicrotask(() => {\n if (!this.isConnected) return;\n const projectId = this.getAttribute(PROJECT_ID_ATTR);\n const flowId = this.getAttribute(FLOW_ID_ATTR);\n const key = `${projectId}|${flowId}`;\n // Bail before the DOM query when we've already warned for this\n // identity — connectedCallback can fire several times per element.\n if (\n this.#warnedForKey === key ||\n !isDuplicateSameFlowInstance(this)\n ) {\n return;\n }\n this.#warnedForKey = key;\n this.logger.warn(\n 'Multiple Descope flow components detected on the same page',\n `The same flow (\"${flowId}\") and project (\"${projectId}\") are running more than once on this page. This is not supported and may cause the flow to behave unexpectedly.`,\n );\n });\n }\n\n connectedCallback() {\n super.connectedCallback?.();\n this.#scheduleDuplicateFlowCheck();\n }\n\n // Re-check when the flow identity changes at runtime. BaseDescopeWc\n // forwards `super.attributeChangedCallback?.()`; the `#warnedForKey`\n // de-dupe keeps this to one warning even if it also fires on mount.\n attributeChangedCallback(\n attrName: string,\n oldValue: string,\n newValue: string,\n ) {\n super.attributeChangedCallback?.(attrName, oldValue, newValue);\n if (\n oldValue !== newValue &&\n (attrName === PROJECT_ID_ATTR || attrName === FLOW_ID_ATTR)\n ) {\n this.#scheduleDuplicateFlowCheck();\n }\n }\n };\n },\n);\n"],"names":["PROJECT_ID_ATTR","FLOW_ID_ATTR","getSameFlowInstances","el","projectId","getAttribute","flowId","Array","from","ownerDocument","querySelectorAll","filter","other","isDuplicateSameFlowInstance","sameFlow","length","duplicateFlowWarningMixin","createSingletonMixin","superclass","BaseClass","compose","loggerMixin","_a","constructor","_DuplicateFlowWarningMixinClass_warnedForKey","set","this","connectedCallback","_b","super","call","__classPrivateFieldGet","_DuplicateFlowWarningMixinClass_instances","_DuplicateFlowWarningMixinClass_scheduleDuplicateFlowCheck","attributeChangedCallback","attrName","oldValue","newValue","queueMicrotask","isConnected","key","__classPrivateFieldSet","logger","warn"],"mappings":"sMAIA,MACMA,EAAkB,aAClBC,EAAe,UAORC,EAAwBC,IACnC,MAAMC,EAAYD,EAAGE,aAAaL,GAC5BM,EAASH,EAAGE,aAAaJ,GAC/B,OAAKG,GAAcE,EACZC,MAAMC,KAAKL,EAAGM,cAAcC,iBAbd,eAagDC,QAClEC,GACCA,EAAMP,aAAaL,KAAqBI,GACxCQ,EAAMP,aAAaJ,KAAkBK,IAJP,EAKjC,EAUUO,EAA+BV,IAC1C,MAAMW,EAAWZ,EAAqBC,GACtC,OAAOW,EAASC,OAAS,GAAKD,EAAS,KAAOX,CAAE,EAUrCa,EAA4BC,GACFC,gBACnC,MAAMC,EAAYC,EAAQC,EAARD,CAAqBF,GAEvC,OAAAI,EAAO,cAA6CH,EAA7C,WAAAI,mCAKLC,EAAAC,IAAAC,UAAA,EA+CF,CArBE,iBAAAC,SACyB,QAAvBC,EAAAC,MAAMF,yBAAiB,IAAAC,GAAAA,EAAAE,KAAAJ,MACvBK,EAAAL,KAAIM,EAAA,IAAAC,GAA4BH,KAAhCJ,KACF,CAKA,wBAAAQ,CACEC,EACAC,EACAC,SAE8B,QAA9BT,EAAAC,MAAMK,gCAAwB,IAAAN,GAAAA,EAAAE,KAAAJ,KAAGS,EAAUC,EAAUC,GAEnDD,IAAaC,GACZF,IAAanC,GAAmBmC,IAAalC,GAE9C8B,EAAAL,KAAIM,EAAA,IAAAC,GAA4BH,KAAhCJ,KAEJ,4CAzCEY,gBAAe,KACb,IAAKZ,KAAKa,YAAa,OACvB,MAAMnC,EAAYsB,KAAKrB,aAAaL,GAC9BM,EAASoB,KAAKrB,aAAaJ,GAC3BuC,EAAM,GAAGpC,KAAaE,IAI1ByB,EAAAL,KAAIF,EAAA,OAAmBgB,GACtB3B,EAA4Ba,QAI/Be,EAAAf,KAAIF,EAAiBgB,EAAG,KACxBd,KAAKgB,OAAOC,KACV,6DACA,mBAAmBrC,qBAA0BF,qHAC9C,GAEL,EAuBAkB,CAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"formMountMixin.js","sources":["../../../src/lib/mixins/formMountMixin.ts"],"sourcesContent":["/* eslint-disable import/prefer-default-export */\nimport { createSingletonMixin } from '@descope/sdk-helpers';\nimport { isChromium } from '../helpers';\n\nexport const formMountMixin = createSingletonMixin(\n <T extends CustomElementConstructor>(superclass: T) =>\n class FormMountMixin extends superclass {\n #shouldMountInFormEle() {\n const wc = this.shadowRoot.host;\n return !wc.closest('form') && isChromium();\n }\n\n // we want to make sure the web-component is wrapped with on outer form element\n // this is needed in order to support webauthn conditional UI (which currently supported only in Chrome when input is inside a web-component)\n // for more info see here: https://github.com/descope/etc/issues/733\n #handleOuterForm() {\n const wc = this.shadowRoot.host;\n const form = document.createElement('form');\n form.style.width = '100%';\n form.style.height = '100%';\n wc.parentElement.appendChild(form);\n form.appendChild(wc);\n }\n\n connectedCallback() {\n if (this.#shouldMountInFormEle()) {\n this.#handleOuterForm();\n }\n super.connectedCallback?.();\n }\n },\n);\n"],"names":["formMountMixin","createSingletonMixin","superclass","_FormMountMixin_instances","_FormMountMixin_shouldMountInFormEle","_FormMountMixin_handleOuterForm","_a","constructor","connectedCallback","__classPrivateFieldGet","this","call","_b","super","shadowRoot","host","closest","isChromium","wc","form","document","createElement","style","width","height","parentElement","appendChild"],"mappings":"+TAIO,MAAMA,EAAiBC,GACSC,IAAiB,IAAAC,EAAAC,EAAAC,EAAAC,EAAA,OAAAA,EACpD,cAA6BJ,EAA7B,WAAAK,
|
|
1
|
+
{"version":3,"file":"formMountMixin.js","sources":["../../../src/lib/mixins/formMountMixin.ts"],"sourcesContent":["/* eslint-disable import/prefer-default-export */\nimport { createSingletonMixin } from '@descope/sdk-helpers';\nimport { isChromium } from '../helpers';\n\nexport const formMountMixin = createSingletonMixin(\n <T extends CustomElementConstructor>(superclass: T) =>\n class FormMountMixin extends superclass {\n #shouldMountInFormEle() {\n const wc = this.shadowRoot.host;\n return !wc.closest('form') && isChromium();\n }\n\n // we want to make sure the web-component is wrapped with on outer form element\n // this is needed in order to support webauthn conditional UI (which currently supported only in Chrome when input is inside a web-component)\n // for more info see here: https://github.com/descope/etc/issues/733\n #handleOuterForm() {\n const wc = this.shadowRoot.host;\n const form = document.createElement('form');\n form.style.width = '100%';\n form.style.height = '100%';\n wc.parentElement.appendChild(form);\n form.appendChild(wc);\n }\n\n connectedCallback() {\n if (this.#shouldMountInFormEle()) {\n this.#handleOuterForm();\n }\n super.connectedCallback?.();\n }\n },\n);\n"],"names":["formMountMixin","createSingletonMixin","superclass","_FormMountMixin_instances","_FormMountMixin_shouldMountInFormEle","_FormMountMixin_handleOuterForm","_a","constructor","connectedCallback","__classPrivateFieldGet","this","call","_b","super","shadowRoot","host","closest","isChromium","wc","form","document","createElement","style","width","height","parentElement","appendChild"],"mappings":"+TAIO,MAAMA,EAAiBC,GACSC,IAAiB,IAAAC,EAAAC,EAAAC,EAAAC,EAAA,OAAAA,EACpD,cAA6BJ,EAA7B,WAAAK,kCAwBA,CANE,iBAAAC,SACMC,EAAAC,KAAIP,EAAA,IAAAC,QAAJM,OACFD,EAAAC,KAAIP,EAAA,IAAAE,GAAiBM,KAArBD,MAEqB,QAAvBE,EAAAC,MAAML,yBAAiB,IAAAI,GAAAA,EAAAD,KAAAD,KACzB,8BApBE,OADWA,KAAKI,WAAWC,KAChBC,QAAQ,SAAWC,GAChC,eAME,MAAMC,EAAKR,KAAKI,WAAWC,KACrBI,EAAOC,SAASC,cAAc,QACpCF,EAAKG,MAAMC,MAAQ,OACnBJ,EAAKG,MAAME,OAAS,OACpBN,EAAGO,cAAcC,YAAYP,GAC7BA,EAAKO,YAAYR,EACnB,EAQDZ,CAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"passwordManagerMixin.js","sources":["../../../src/lib/mixins/passwordManagerMixin.ts"],"sourcesContent":["/* eslint-disable import/prefer-default-export */\nimport { compose, createSingletonMixin } from '@descope/sdk-helpers';\nimport { loggerMixin } from '@descope/sdk-mixins';\nimport {\n DESCOPE_ATTRIBUTE_EXCLUDE_FIELD,\n DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY,\n} from '../constants';\nimport { getFirstNonEmptyValue } from '../helpers';\nimport type { ScreenStateUser } from '../types';\n\nconst LOGIN_ID_FIELDS = ['externalId', 'email', 'phone'];\nconst PASSWORD_FIELDS = ['newPassword', 'password'];\n\nconst USERNAME_ANCHOR_ATTRIBUTE = 'data-username-anchor';\n\n// What the mixin needs from its host. Defined as an interface (not imported)\n// to avoid a circular dependency on DescopeWc. Exported so declaration emit\n// can name it from BaseDescopeWc's composed base class.\nexport interface PasswordManagerHost {\n contentRootElement?: HTMLElement;\n flowState?: { current?: { executionId?: string } };\n sdk?: { getLastUserLoginId?: () => string };\n}\n\n// the last identifier the user submitted on a previous screen in this flow\n// (e.g. the email entered before a magic link was sent), used when neither\n// the flow state nor a previous authentication provides one.\n// kept in sessionStorage (tab scoped, cleared when the tab closes) so it\n// survives page reloads during the flow, and scoped to the flow execution so\n// a stale identifier is never carried into another flow (or another user)\n// running in the same tab\nconst getLastSubmittedLoginId = (executionId: string): string => {\n // a missing execution id must never match anything, otherwise two flows\n // without one would share the stored identifier\n if (!executionId) {\n return '';\n }\n try {\n const raw = window.sessionStorage?.getItem(\n DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY,\n );\n if (!raw) {\n return '';\n }\n const stored = JSON.parse(raw);\n return stored.executionId === executionId ? stored.loginId || '' : '';\n } catch (e) {\n return '';\n }\n};\n\nconst setLastSubmittedLoginId = (loginId: string, executionId: string) => {\n if (!loginId || !executionId) {\n return;\n }\n try {\n window.sessionStorage?.setItem(\n DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY,\n JSON.stringify({ executionId, loginId }),\n );\n } catch (e) {\n // sessionStorage unavailable, losing reload persistence is acceptable\n }\n};\n\nconst clearUsernameAnchorIfExists = () => {\n document\n .querySelectorAll(`[${USERNAME_ANCHOR_ATTRIBUTE}=\"true\"]`)\n .forEach((ele) => ele.remove());\n};\n\nconst findPasswordComponent = (contentRootEle: Element) =>\n contentRootEle.querySelector('descope-new-password') ||\n contentRootEle.querySelector('descope-password');\n\n// an identifier is already on screen when there is an autocomplete=\"username\"\n// input, or a component collecting one of the login id fields (e.g.\n// descope-email-field renders its input inside a closed shadow root, so only\n// its name attribute is visible from here)\nconst hasLoginIdField = (roots: Element[]) => {\n const selector = [\n 'input[autocomplete=\"username\"]',\n ...LOGIN_ID_FIELDS.map((field) => `[name=\"${field}\"]`),\n ].join(', ');\n return roots.some((root) => root.querySelector(selector));\n};\n\nconst createUsernameAnchor = (loginId: string) => {\n const input = document.createElement('input');\n input.setAttribute('autocomplete', 'username');\n input.setAttribute('name', 'username');\n input.setAttribute('type', 'email');\n input.setAttribute('readonly', 'true');\n input.setAttribute('tabindex', '-1');\n input.setAttribute('aria-hidden', 'true');\n // never collect the anchor's value into the submitted form data\n input.setAttribute(DESCOPE_ATTRIBUTE_EXCLUDE_FIELD, 'true');\n // cleaned up by clearUsernameAnchorIfExists between screens\n input.setAttribute(USERNAME_ANCHOR_ATTRIBUTE, 'true');\n // some password managers read the markup value rather than the property\n input.setAttribute('value', loginId);\n input.value = loginId;\n // real input hidden via CSSOM: managers ignore type=\"hidden\", and strict\n // CSP style-src blocks style attributes\n Object.assign(input.style, {\n position: 'absolute',\n opacity: '0',\n pointerEvents: 'none',\n height: '0',\n border: '0',\n });\n return input;\n};\n\n// Anchors a hidden autocomplete=\"username\" input on password screens that\n// have no identifier input, so password managers can associate the credential\n// with a user (descope/etc#16712). Appended to the host light DOM — password\n// manager save heuristics (verified on WebKit) do not scan shadow trees\nconst injectUsernameAnchorIfNeeded = (\n hostEle: HTMLElement,\n contentRootEle: Element,\n user: ScreenStateUser | undefined,\n logger: { debug: (...args: string[]) => void },\n) => {\n const loginId = user?.email || user?.loginIds?.[0];\n\n if (!findPasswordComponent(contentRootEle)) {\n logger.debug('Username anchor: no password component on screen');\n return;\n }\n if (!loginId) {\n logger.debug('Username anchor: no user identifier available');\n return;\n }\n if (hasLoginIdField([hostEle, contentRootEle])) {\n logger.debug('Username anchor: screen already has an identifier field');\n return;\n }\n\n logger.debug('Username anchor: injecting hidden username input');\n hostEle.appendChild(createUsernameAnchor(loginId));\n};\n\n/**\n * Password manager integrations: keeps track of the current screen's user\n * identifier, anchors a hidden username input on password screens that have\n * no identifier input, and stores submitted credentials via the Credential\n * Management API.\n */\nexport const passwordManagerMixin = createSingletonMixin(\n <T extends CustomElementConstructor>(superclass: T) => {\n const BaseClass = compose(loggerMixin)(superclass);\n\n return class PasswordManagerMixinClass extends BaseClass {\n // the authenticated user of the current screen (if any), used as a\n // fallback identifier for password manager integrations on screens that\n // have no identifier input (e.g. step-up password change)\n #screenUser?: ScreenStateUser;\n\n get #host() {\n return this as unknown as PasswordManagerHost;\n }\n\n get #executionId() {\n return this.#host.flowState?.current?.executionId || '';\n }\n\n // called on every screen render. flow state does not always carry the\n // user (e.g. after magic link auth), so fall back to the login id\n // submitted earlier in this flow, then to the last authenticated user\n updateScreenUser(stateUser?: ScreenStateUser) {\n this.#screenUser = {\n email: stateUser?.email,\n loginIds: stateUser?.loginIds?.length\n ? stateUser.loginIds\n : [\n getLastSubmittedLoginId(this.#executionId) ||\n this.#host.sdk?.getLastUserLoginId?.(),\n ].filter(Boolean),\n };\n }\n\n updateUsernameAnchor() {\n // clear the previous screen's anchor, so each screen gets an anchor\n // only if it needs one\n clearUsernameAnchorIfExists();\n\n injectUsernameAnchorIfNeeded(\n this,\n this.#host.contentRootElement,\n this.#screenUser,\n this.logger,\n );\n }\n\n // called after a successful next(): on flows that render their first\n // screen before the flow starts, the execution id only exists on the\n // response, so prefer it over the current flow state\n captureLastSubmittedLoginId(formData = {}, responseExecutionId?: string) {\n const loginId = getFirstNonEmptyValue(formData, LOGIN_ID_FIELDS);\n if (loginId) {\n setLastSubmittedLoginId(\n loginId,\n responseExecutionId || this.#executionId,\n );\n }\n }\n\n // handle storing passwords in password managers\n storeCredentials(formData = {}) {\n const id =\n getFirstNonEmptyValue(formData, LOGIN_ID_FIELDS) ||\n this.#screenUser?.email ||\n this.#screenUser?.loginIds?.[0];\n const password = getFirstNonEmptyValue(formData, PASSWORD_FIELDS);\n\n // PasswordCredential not supported in Firefox\n if (id && password) {\n try {\n if (!globalThis.PasswordCredential) {\n return;\n }\n const cred = new globalThis.PasswordCredential({ id, password });\n\n navigator?.credentials?.store?.(cred)?.catch((e) => {\n this.logger.debug('Could not store credentials', e?.message);\n });\n } catch (e) {\n this.logger.warn('Could not store credentials', e.message);\n }\n }\n }\n };\n },\n);\n"],"names":["LOGIN_ID_FIELDS","PASSWORD_FIELDS","USERNAME_ANCHOR_ATTRIBUTE","getLastSubmittedLoginId","executionId","raw","_a","window","sessionStorage","getItem","DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY","stored","JSON","parse","loginId","e","injectUsernameAnchorIfNeeded","hostEle","contentRootEle","user","logger","email","loginIds","querySelector","findPasswordComponent","roots","selector","map","field","join","some","root","hasLoginIdField","debug","appendChild","input","document","createElement","setAttribute","DESCOPE_ATTRIBUTE_EXCLUDE_FIELD","value","Object","assign","style","position","opacity","pointerEvents","height","border","createUsernameAnchor","passwordManagerMixin","createSingletonMixin","superclass","BaseClass","compose","loggerMixin","constructor","_PasswordManagerMixinClass_screenUser","set","this","updateScreenUser","stateUser","__classPrivateFieldSet","_b","length","__classPrivateFieldGet","_PasswordManagerMixinClass_instances","_PasswordManagerMixinClass_executionId_get","_d","_c","_PasswordManagerMixinClass_host_get","sdk","getLastUserLoginId","call","filter","Boolean","updateUsernameAnchor","querySelectorAll","forEach","ele","remove","contentRootElement","captureLastSubmittedLoginId","formData","responseExecutionId","getFirstNonEmptyValue","setItem","stringify","setLastSubmittedLoginId","storeCredentials","id","password","globalThis","PasswordCredential","cred","_g","_f","navigator","credentials","_e","store","catch","message","warn","flowState","current"],"mappings":"ieAUA,MAAMA,EAAkB,CAAC,aAAc,QAAS,SAC1CC,EAAkB,CAAC,cAAe,YAElCC,EAA4B,uBAkB5BC,EAA2BC,UAG/B,IAAKA,EACH,MAAO,GAET,IACE,MAAMC,EAA2B,QAArBC,EAAAC,OAAOC,sBAAc,IAAAF,OAAA,EAAAA,EAAEG,QACjCC,GAEF,IAAKL,EACH,MAAO,GAET,MAAMM,EAASC,KAAKC,MAAMR,GAC1B,OAAOM,EAAOP,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mBACd,OAEF,MAAMC,EAAO,IAAIF,WAAWC,mBAAmB,CAAEH,KAAIC,aAEd,QAAvCI,EAAgC,QAAhCC,EAAsB,UAAb,OAATC,gBAAA,IAAAA,eAAA,EAAAA,UAAWC,mBAAW,IAAAC,OAAA,EAAAA,EAAEC,aAAQ,IAAAJ,OAAA,EAAAA,EAAAvB,KAAA0B,EAAAL,UAAO,IAAAC,GAAAA,EAAAM,OAAOtF,IAC5C4C,KAAKvC,OAAOa,MAAM,8BAA+BlB,aAAA,EAAAA,EAAGuF,QAAQ,GAE/D,CAAC,MAAOvF,GACP4C,KAAKvC,OAAOmF,KAAK,8BAA+BxF,EAAEuF,QACnD,CAEJ,4CAvEC,OAAO3C,IACR,uBAGC,OAAoC,QAA7BU,EAAoB,QAApBN,EAAAE,EAAAN,KAAUO,EAAA,IAAAI,GAACkC,iBAAS,IAAAzC,OAAA,EAAAA,EAAE0C,eAAO,IAAApC,OAAA,EAAAA,EAAEjE,cAAe,EACtD,EAmEDE,CAAA"}
|
|
1
|
+
{"version":3,"file":"passwordManagerMixin.js","sources":["../../../src/lib/mixins/passwordManagerMixin.ts"],"sourcesContent":["/* eslint-disable import/prefer-default-export */\nimport { compose, createSingletonMixin } from '@descope/sdk-helpers';\nimport { loggerMixin } from '@descope/sdk-mixins';\nimport {\n DESCOPE_ATTRIBUTE_EXCLUDE_FIELD,\n DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY,\n} from '../constants';\nimport { getFirstNonEmptyValue } from '../helpers';\nimport type { ScreenStateUser } from '../types';\n\nconst LOGIN_ID_FIELDS = ['externalId', 'email', 'phone'];\nconst PASSWORD_FIELDS = ['newPassword', 'password'];\n\nconst USERNAME_ANCHOR_ATTRIBUTE = 'data-username-anchor';\n\n// What the mixin needs from its host. Defined as an interface (not imported)\n// to avoid a circular dependency on DescopeWc. Exported so declaration emit\n// can name it from BaseDescopeWc's composed base class.\nexport interface PasswordManagerHost {\n contentRootElement?: HTMLElement;\n flowState?: { current?: { executionId?: string } };\n sdk?: { getLastUserLoginId?: () => string };\n}\n\n// the last identifier the user submitted on a previous screen in this flow\n// (e.g. the email entered before a magic link was sent), used when neither\n// the flow state nor a previous authentication provides one.\n// kept in sessionStorage (tab scoped, cleared when the tab closes) so it\n// survives page reloads during the flow, and scoped to the flow execution so\n// a stale identifier is never carried into another flow (or another user)\n// running in the same tab\nconst getLastSubmittedLoginId = (executionId: string): string => {\n // a missing execution id must never match anything, otherwise two flows\n // without one would share the stored identifier\n if (!executionId) {\n return '';\n }\n try {\n const raw = window.sessionStorage?.getItem(\n DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY,\n );\n if (!raw) {\n return '';\n }\n const stored = JSON.parse(raw);\n return stored.executionId === executionId ? stored.loginId || '' : '';\n } catch (e) {\n return '';\n }\n};\n\nconst setLastSubmittedLoginId = (loginId: string, executionId: string) => {\n if (!loginId || !executionId) {\n return;\n }\n try {\n window.sessionStorage?.setItem(\n DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY,\n JSON.stringify({ executionId, loginId }),\n );\n } catch (e) {\n // sessionStorage unavailable, losing reload persistence is acceptable\n }\n};\n\nconst clearUsernameAnchorIfExists = () => {\n document\n .querySelectorAll(`[${USERNAME_ANCHOR_ATTRIBUTE}=\"true\"]`)\n .forEach((ele) => ele.remove());\n};\n\nconst findPasswordComponent = (contentRootEle: Element) =>\n contentRootEle.querySelector('descope-new-password') ||\n contentRootEle.querySelector('descope-password');\n\n// an identifier is already on screen when there is an autocomplete=\"username\"\n// input, or a component collecting one of the login id fields (e.g.\n// descope-email-field renders its input inside a closed shadow root, so only\n// its name attribute is visible from here)\nconst hasLoginIdField = (roots: Element[]) => {\n const selector = [\n 'input[autocomplete=\"username\"]',\n ...LOGIN_ID_FIELDS.map((field) => `[name=\"${field}\"]`),\n ].join(', ');\n return roots.some((root) => root.querySelector(selector));\n};\n\nconst createUsernameAnchor = (loginId: string) => {\n const input = document.createElement('input');\n input.setAttribute('autocomplete', 'username');\n input.setAttribute('name', 'username');\n input.setAttribute('type', 'email');\n input.setAttribute('readonly', 'true');\n input.setAttribute('tabindex', '-1');\n input.setAttribute('aria-hidden', 'true');\n // never collect the anchor's value into the submitted form data\n input.setAttribute(DESCOPE_ATTRIBUTE_EXCLUDE_FIELD, 'true');\n // cleaned up by clearUsernameAnchorIfExists between screens\n input.setAttribute(USERNAME_ANCHOR_ATTRIBUTE, 'true');\n // some password managers read the markup value rather than the property\n input.setAttribute('value', loginId);\n input.value = loginId;\n // real input hidden via CSSOM: managers ignore type=\"hidden\", and strict\n // CSP style-src blocks style attributes\n Object.assign(input.style, {\n position: 'absolute',\n opacity: '0',\n pointerEvents: 'none',\n height: '0',\n border: '0',\n });\n return input;\n};\n\n// Anchors a hidden autocomplete=\"username\" input on password screens that\n// have no identifier input, so password managers can associate the credential\n// with a user (descope/etc#16712). Appended to the host light DOM — password\n// manager save heuristics (verified on WebKit) do not scan shadow trees\nconst injectUsernameAnchorIfNeeded = (\n hostEle: HTMLElement,\n contentRootEle: Element,\n user: ScreenStateUser | undefined,\n logger: { debug: (...args: string[]) => void },\n) => {\n const loginId = user?.email || user?.loginIds?.[0];\n\n if (!findPasswordComponent(contentRootEle)) {\n logger.debug('Username anchor: no password component on screen');\n return;\n }\n if (!loginId) {\n logger.debug('Username anchor: no user identifier available');\n return;\n }\n if (hasLoginIdField([hostEle, contentRootEle])) {\n logger.debug('Username anchor: screen already has an identifier field');\n return;\n }\n\n logger.debug('Username anchor: injecting hidden username input');\n hostEle.appendChild(createUsernameAnchor(loginId));\n};\n\n/**\n * Password manager integrations: keeps track of the current screen's user\n * identifier, anchors a hidden username input on password screens that have\n * no identifier input, and stores submitted credentials via the Credential\n * Management API.\n */\nexport const passwordManagerMixin = createSingletonMixin(\n <T extends CustomElementConstructor>(superclass: T) => {\n const BaseClass = compose(loggerMixin)(superclass);\n\n return class PasswordManagerMixinClass extends BaseClass {\n // the authenticated user of the current screen (if any), used as a\n // fallback identifier for password manager integrations on screens that\n // have no identifier input (e.g. step-up password change)\n #screenUser?: ScreenStateUser;\n\n get #host() {\n return this as unknown as PasswordManagerHost;\n }\n\n get #executionId() {\n return this.#host.flowState?.current?.executionId || '';\n }\n\n // called on every screen render. flow state does not always carry the\n // user (e.g. after magic link auth), so fall back to the login id\n // submitted earlier in this flow, then to the last authenticated user\n updateScreenUser(stateUser?: ScreenStateUser) {\n this.#screenUser = {\n email: stateUser?.email,\n loginIds: stateUser?.loginIds?.length\n ? stateUser.loginIds\n : [\n getLastSubmittedLoginId(this.#executionId) ||\n this.#host.sdk?.getLastUserLoginId?.(),\n ].filter(Boolean),\n };\n }\n\n updateUsernameAnchor() {\n // clear the previous screen's anchor, so each screen gets an anchor\n // only if it needs one\n clearUsernameAnchorIfExists();\n\n injectUsernameAnchorIfNeeded(\n this,\n this.#host.contentRootElement,\n this.#screenUser,\n this.logger,\n );\n }\n\n // called after a successful next(): on flows that render their first\n // screen before the flow starts, the execution id only exists on the\n // response, so prefer it over the current flow state\n captureLastSubmittedLoginId(formData = {}, responseExecutionId?: string) {\n const loginId = getFirstNonEmptyValue(formData, LOGIN_ID_FIELDS);\n if (loginId) {\n setLastSubmittedLoginId(\n loginId,\n responseExecutionId || this.#executionId,\n );\n }\n }\n\n // handle storing passwords in password managers\n storeCredentials(formData = {}) {\n const id =\n getFirstNonEmptyValue(formData, LOGIN_ID_FIELDS) ||\n this.#screenUser?.email ||\n this.#screenUser?.loginIds?.[0];\n const password = getFirstNonEmptyValue(formData, PASSWORD_FIELDS);\n\n // PasswordCredential not supported in Firefox\n if (id && password) {\n try {\n if (!globalThis.PasswordCredential) {\n return;\n }\n const cred = new globalThis.PasswordCredential({ id, password });\n\n navigator?.credentials?.store?.(cred)?.catch((e) => {\n this.logger.debug('Could not store credentials', e?.message);\n });\n } catch (e) {\n this.logger.warn('Could not store credentials', e.message);\n }\n }\n }\n };\n },\n);\n"],"names":["LOGIN_ID_FIELDS","PASSWORD_FIELDS","USERNAME_ANCHOR_ATTRIBUTE","getLastSubmittedLoginId","executionId","raw","_a","window","sessionStorage","getItem","DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY","stored","JSON","parse","loginId","e","injectUsernameAnchorIfNeeded","hostEle","contentRootEle","user","logger","email","loginIds","querySelector","findPasswordComponent","roots","selector","map","field","join","some","root","hasLoginIdField","debug","appendChild","input","document","createElement","setAttribute","DESCOPE_ATTRIBUTE_EXCLUDE_FIELD","value","Object","assign","style","position","opacity","pointerEvents","height","border","createUsernameAnchor","passwordManagerMixin","createSingletonMixin","superclass","BaseClass","compose","loggerMixin","constructor","_PasswordManagerMixinClass_screenUser","set","this","updateScreenUser","stateUser","__classPrivateFieldSet","_b","length","__classPrivateFieldGet","_PasswordManagerMixinClass_instances","_PasswordManagerMixinClass_executionId_get","_d","_c","_PasswordManagerMixinClass_host_get","sdk","getLastUserLoginId","call","filter","Boolean","updateUsernameAnchor","querySelectorAll","forEach","ele","remove","contentRootElement","captureLastSubmittedLoginId","formData","responseExecutionId","getFirstNonEmptyValue","setItem","stringify","setLastSubmittedLoginId","storeCredentials","id","password","globalThis","PasswordCredential","cred","_g","_f","navigator","credentials","_e","store","catch","message","warn","flowState","current"],"mappings":"ieAUA,MAAMA,EAAkB,CAAC,aAAc,QAAS,SAC1CC,EAAkB,CAAC,cAAe,YAElCC,EAA4B,uBAkB5BC,EAA2BC,UAG/B,IAAKA,EACH,MAAO,GAET,IACE,MAAMC,EAA2B,QAArBC,EAAAC,OAAOC,sBAAc,IAAAF,OAAA,EAAAA,EAAEG,QACjCC,GAEF,IAAKL,EACH,MAAO,GAET,MAAMM,EAASC,KAAKC,MAAMR,GAC1B,OAAOM,EAAOP,cAAgBA,GAAcO,EAAOG,SAAgB,EACrE,CAAE,MAAOC,GACP,MAAO,EACT,GAsEIC,EAA+B,CACnCC,EACAC,EACAC,EACAC,WAEA,MAAMN,GAAUK,aAAI,EAAJA,EAAME,SAAuB,UAAdF,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