@descope/web-component 3.33.0 → 3.34.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +64 -13
- package/dist/cjs/constants/content.js +1 -0
- package/dist/cjs/constants/content.js.map +1 -0
- package/dist/cjs/constants/customScreens.js +2 -0
- package/dist/cjs/constants/customScreens.js.map +1 -0
- package/dist/cjs/constants/general.js +1 -0
- package/dist/cjs/constants/general.js.map +1 -0
- package/dist/cjs/constants/index.js +1 -0
- package/dist/cjs/constants/index.js.map +1 -0
- package/dist/cjs/constants/uiComponents.js +1 -0
- package/dist/cjs/constants/uiComponents.js.map +1 -0
- package/dist/cjs/debugger-wc.js +1 -0
- package/dist/cjs/debugger-wc.js.map +1 -0
- package/dist/cjs/descope-wc/BaseDescopeWc.js +2 -1
- package/dist/cjs/descope-wc/BaseDescopeWc.js.map +1 -0
- package/dist/cjs/descope-wc/DescopeWc.js +2 -1
- package/dist/cjs/descope-wc/DescopeWc.js.map +1 -0
- package/dist/cjs/descope-wc/index.js +1 -0
- package/dist/cjs/descope-wc/index.js.map +1 -0
- package/dist/cjs/descope-wc/initTemplate.js +2 -1
- package/dist/cjs/descope-wc/initTemplate.js.map +1 -0
- package/dist/cjs/descope-wc/sdkScripts/fingerprint.js +1 -0
- package/dist/cjs/descope-wc/sdkScripts/fingerprint.js.map +1 -0
- package/dist/cjs/descope-wc/sdkScripts/fingerprintDescope.js +1 -0
- package/dist/cjs/descope-wc/sdkScripts/fingerprintDescope.js.map +1 -0
- package/dist/cjs/descope-wc/sdkScripts/forter.js +1 -0
- package/dist/cjs/descope-wc/sdkScripts/forter.js.map +1 -0
- package/dist/cjs/descope-wc/sdkScripts/index.js +1 -0
- package/dist/cjs/descope-wc/sdkScripts/index.js.map +1 -0
- package/dist/cjs/helpers/abTestingKey.js +1 -0
- package/dist/cjs/helpers/abTestingKey.js.map +1 -0
- package/dist/cjs/helpers/conditions.js +2 -1
- package/dist/cjs/helpers/conditions.js.map +1 -0
- package/dist/cjs/helpers/flowInputs.js +1 -0
- package/dist/cjs/helpers/flowInputs.js.map +1 -0
- package/dist/cjs/helpers/helpers.js +2 -1
- package/dist/cjs/helpers/helpers.js.map +1 -0
- package/dist/cjs/helpers/lastAuth.js +1 -0
- package/dist/cjs/helpers/lastAuth.js.map +1 -0
- package/dist/cjs/helpers/positionHelpers.js +1 -0
- package/dist/cjs/helpers/positionHelpers.js.map +1 -0
- package/dist/cjs/helpers/state.js +2 -1
- package/dist/cjs/helpers/state.js.map +1 -0
- package/dist/cjs/helpers/templates.js +1 -0
- package/dist/cjs/helpers/templates.js.map +1 -0
- package/dist/cjs/helpers/webauthn.js +1 -0
- package/dist/cjs/helpers/webauthn.js.map +1 -0
- package/dist/cjs/mixins/formMountMixin.js +1 -0
- package/dist/cjs/mixins/formMountMixin.js.map +1 -0
- package/dist/cjs/types.js +1 -0
- package/dist/cjs/types.js.map +1 -0
- package/dist/esm/constants/content.js +1 -0
- package/dist/esm/constants/content.js.map +1 -0
- package/dist/esm/constants/customScreens.js +2 -0
- package/dist/esm/constants/customScreens.js.map +1 -0
- package/dist/esm/constants/general.js +1 -0
- package/dist/esm/constants/general.js.map +1 -0
- package/dist/esm/constants/index.js +1 -0
- package/dist/esm/constants/index.js.map +1 -0
- package/dist/esm/constants/uiComponents.js +1 -0
- package/dist/esm/constants/uiComponents.js.map +1 -0
- package/dist/esm/debugger-wc.js +1 -0
- package/dist/esm/debugger-wc.js.map +1 -0
- package/dist/esm/descope-wc/BaseDescopeWc.js +2 -1
- package/dist/esm/descope-wc/BaseDescopeWc.js.map +1 -0
- package/dist/esm/descope-wc/DescopeWc.js +2 -1
- package/dist/esm/descope-wc/DescopeWc.js.map +1 -0
- package/dist/esm/descope-wc/index.js +1 -0
- package/dist/esm/descope-wc/index.js.map +1 -0
- package/dist/esm/descope-wc/initTemplate.js +2 -1
- package/dist/esm/descope-wc/initTemplate.js.map +1 -0
- package/dist/esm/descope-wc/sdkScripts/fingerprint.js +1 -0
- package/dist/esm/descope-wc/sdkScripts/fingerprint.js.map +1 -0
- package/dist/esm/descope-wc/sdkScripts/fingerprintDescope.js +1 -0
- package/dist/esm/descope-wc/sdkScripts/fingerprintDescope.js.map +1 -0
- package/dist/esm/descope-wc/sdkScripts/forter.js +1 -0
- package/dist/esm/descope-wc/sdkScripts/forter.js.map +1 -0
- package/dist/esm/descope-wc/sdkScripts/index.js +1 -0
- package/dist/esm/descope-wc/sdkScripts/index.js.map +1 -0
- package/dist/esm/helpers/abTestingKey.js +1 -0
- package/dist/esm/helpers/abTestingKey.js.map +1 -0
- package/dist/esm/helpers/conditions.js +2 -1
- package/dist/esm/helpers/conditions.js.map +1 -0
- package/dist/esm/helpers/flowInputs.js +1 -0
- package/dist/esm/helpers/flowInputs.js.map +1 -0
- package/dist/esm/helpers/helpers.js +2 -1
- package/dist/esm/helpers/helpers.js.map +1 -0
- package/dist/esm/helpers/lastAuth.js +1 -0
- package/dist/esm/helpers/lastAuth.js.map +1 -0
- package/dist/esm/helpers/positionHelpers.js +1 -0
- package/dist/esm/helpers/positionHelpers.js.map +1 -0
- package/dist/esm/helpers/state.js +2 -1
- package/dist/esm/helpers/state.js.map +1 -0
- package/dist/esm/helpers/templates.js +1 -0
- package/dist/esm/helpers/templates.js.map +1 -0
- package/dist/esm/helpers/webauthn.js +1 -0
- package/dist/esm/helpers/webauthn.js.map +1 -0
- package/dist/esm/mixins/formMountMixin.js +1 -0
- package/dist/esm/mixins/formMountMixin.js.map +1 -0
- package/dist/esm/types.js +1 -0
- package/dist/esm/types.js.map +1 -0
- package/dist/index.d.ts +78 -46
- package/dist/index.js +2 -2
- package/package.json +4 -4
package/README.md
CHANGED
|
@@ -71,22 +71,22 @@ NOTE: This package is a part of a monorepo. so if you make changes in a dependen
|
|
|
71
71
|
|
|
72
72
|
## Optional Attributes
|
|
73
73
|
|
|
74
|
-
| Attribute
|
|
75
|
-
|
|
|
76
|
-
| base-url
|
|
77
|
-
| theme
|
|
78
|
-
| debug
|
|
79
|
-
| preview
|
|
80
|
-
| auto-focus
|
|
74
|
+
| Attribute | Available options | Default value |
|
|
75
|
+
| ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- |
|
|
76
|
+
| base-url | Custom Descope base URL | **""** |
|
|
77
|
+
| theme | **"light"** - Light theme</br>**"dark"** - Dark theme</br>**"os"** - Auto select a theme based on the OS theme settings | **"light"** |
|
|
78
|
+
| debug | **"true"** - Enable debugger</br>**"false"** - Disable debugger | **"false"** |
|
|
79
|
+
| preview | **"true"** - Run flow in a preview mode</br>**"false"** - Do run flow in a preview mode | **"false"** |
|
|
80
|
+
| auto-focus | **"true"** - Automatically focus on the first input of each screen</br>**"false"** - Do not automatically focus on screen's inputs</br>**"skipFirstScreen"** - Automatically focus on the first input of each screen, except first screen | **"true"** |
|
|
81
81
|
|
|
82
|
-
| validate-on-blur
|
|
82
|
+
| validate-on-blur | **"true"** - Triggers the input validation upon blur in addition to the validation on submit</br>**"false"** - Do not triggers validation upon blur</br> | **"false"** |
|
|
83
83
|
|
|
84
|
-
| restart-on-error
|
|
84
|
+
| restart-on-error | **"true"** - In case of flow version mismatch, will restart the flow if the components version was not changed</br>**"false"** - Do not restart the flow automatically</br> | **"false"** |
|
|
85
85
|
|
|
86
|
-
| storage-prefix
|
|
87
|
-
| store-last-authenticated-user
|
|
88
|
-
| keep-last-authenticated-user-after-logout | **"true"** - Do not clear the last authenticated user details from the browser storage after logout</br>**"false"** - Clear the last authenticated user details from the browser storage after logout
|
|
89
|
-
| style-id
|
|
86
|
+
| storage-prefix | **String** - A prefix to add to the key of the local storage when persisting tokens | **""** |
|
|
87
|
+
| store-last-authenticated-user | **"true"** - Stores last-authenticated user details in local storage when flow is completed</br>**"false"** - Do not store last-auth user details. Disabling this flag may cause last-authenticated user features to not function properly | **"true"** |
|
|
88
|
+
| keep-last-authenticated-user-after-logout | **"true"** - Do not clear the last authenticated user details from the browser storage after logout</br>**"false"** - Clear the last authenticated user details from the browser storage after logout | **"false"** |
|
|
89
|
+
| style-id | **"String"** - Set a specific style to load rather then the default style | **""** |
|
|
90
90
|
|
|
91
91
|
## Optional Properties
|
|
92
92
|
|
|
@@ -131,6 +131,57 @@ const descopeWcEle = document.getElementsByTagName('descope-wc')[0];
|
|
|
131
131
|
descopeWcEle.logger = logger;
|
|
132
132
|
```
|
|
133
133
|
|
|
134
|
+
### `onScreenUpdate`
|
|
135
|
+
|
|
136
|
+
A function that is called whenever there is a new screen state and after every next call. It receives the following parameters:
|
|
137
|
+
|
|
138
|
+
- `screenName`: The name of the screen that is about to be rendered
|
|
139
|
+
- `context`: An object containing the upcoming screen state
|
|
140
|
+
- `next`: A function that, when called, continues the flow execution
|
|
141
|
+
- `ref`: A reference to the descope-wc node
|
|
142
|
+
|
|
143
|
+
The function can be sync or async, and should return a boolean indicating whether a custom screen should be rendered:
|
|
144
|
+
|
|
145
|
+
- `true`: Render a custom screen
|
|
146
|
+
- `false`: Render the default flow screen
|
|
147
|
+
|
|
148
|
+
This function allows rendering custom screens instead of the default flow screens.
|
|
149
|
+
It can be useful for highly customized UIs or specific logic not covered by the default screens
|
|
150
|
+
|
|
151
|
+
To render a custom screen, its elements should be appended as children of the `descope-wc` component
|
|
152
|
+
|
|
153
|
+
Usage example:
|
|
154
|
+
|
|
155
|
+
```javascript
|
|
156
|
+
function onScreenUpdate(screenName, context, next, ref) {
|
|
157
|
+
if (screenName === 'My Custom Screen') {
|
|
158
|
+
ref.innerHTML = `
|
|
159
|
+
<form>
|
|
160
|
+
<input type="text" name="email" placeholder="Email" />
|
|
161
|
+
<button type="submit">Submit</button>
|
|
162
|
+
</form>
|
|
163
|
+
`;
|
|
164
|
+
|
|
165
|
+
ref.closest('form').addEventListener('submit', (e) => {
|
|
166
|
+
e.preventDefault();
|
|
167
|
+
const formData = new FormData(e.target);
|
|
168
|
+
const data = Object.fromEntries(formData.entries());
|
|
169
|
+
|
|
170
|
+
// replace with the button interaction id
|
|
171
|
+
next('interactionId', data);
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
return true;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
return false;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const descopeWcEle = document.querySelector('descope-wc');
|
|
181
|
+
|
|
182
|
+
descopeWcEle.onScreenUpdate = onScreenUpdate;
|
|
183
|
+
```
|
|
184
|
+
|
|
134
185
|
## Events
|
|
135
186
|
|
|
136
187
|
### `error` - Fired when an error occurs. The event detail contains the error object.
|
|
@@ -1 +1,2 @@
|
|
|
1
1
|
"use strict";const e=require("./general.js").IS_LOCAL_STORAGE&&localStorage.getItem("base.content.url")||"";exports.ASSETS_FOLDER="v2-beta",exports.BASE_CONTENT_URL="https://static.descope.com/pages",exports.CONFIG_FILENAME="config.json",exports.OVERRIDE_CONTENT_URL=e,exports.PREV_VER_ASSETS_FOLDER="v2-alpha";
|
|
2
|
+
//# sourceMappingURL=content.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"content.js","sources":["../../../src/lib/constants/content.ts"],"sourcesContent":["import { IS_LOCAL_STORAGE } from './general';\n\nconst BASE_CONTENT_URL_KEY = 'base.content.url';\n\n// eslint-disable-next-line import/prefer-default-export\nexport const OVERRIDE_CONTENT_URL =\n (IS_LOCAL_STORAGE && localStorage.getItem(BASE_CONTENT_URL_KEY)) || '';\nexport const BASE_CONTENT_URL = 'https://static.descope.com/pages';\n\nexport const ASSETS_FOLDER = 'v2-beta';\nexport const PREV_VER_ASSETS_FOLDER = 'v2-alpha';\n\nexport const CONFIG_FILENAME = 'config.json';\n"],"names":["OVERRIDE_CONTENT_URL","IS_LOCAL_STORAGE","localStorage","getItem"],"mappings":"aAEA,MAGaA,0BACVC,kBAAoBC,aAAaC,QAJP,qBAIyC,yBAGzC,mCAFG,2DAKD,4EAFO"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"customScreens.js","sources":["../../../src/lib/constants/customScreens.ts"],"sourcesContent":["export const EXCLUDED_STATE_KEYS = [\n 'cssVars',\n 'componentsConfig',\n 'inputs',\n 'errorText',\n 'errorType',\n 'clientScripts',\n];\n"],"names":[],"mappings":"yCAAmC,CACjC,UACA,mBACA,SACA,YACA,YACA"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"general.js","sources":["../../../src/lib/constants/general.ts"],"sourcesContent":["/* eslint-disable import/prefer-default-export */\nexport const IS_LOCAL_STORAGE = typeof localStorage !== 'undefined';\n\nexport const FETCH_EXCEPTION_ERROR_CODE = 'J151000';\nexport const FETCH_ERROR_RESPONSE_ERROR_CODE = 'J151001';\n"],"names":["IS_LOCAL_STORAGE","localStorage"],"mappings":"mBACaA,EAA2C,oBAAjBC,qDAGQ,6CADL"}
|
|
@@ -1 +1,2 @@
|
|
|
1
1
|
"use strict";var _=require("./content.js"),E=require("./uiComponents.js");exports.ASSETS_FOLDER=_.ASSETS_FOLDER,exports.BASE_CONTENT_URL=_.BASE_CONTENT_URL,exports.CONFIG_FILENAME=_.CONFIG_FILENAME,exports.OVERRIDE_CONTENT_URL=_.OVERRIDE_CONTENT_URL,exports.PREV_VER_ASSETS_FOLDER=_.PREV_VER_ASSETS_FOLDER,exports.UI_COMPONENTS_URL_KEY=E.UI_COMPONENTS_URL_KEY,exports.APPLICATION_SCOPES_PARAM_NAME="application_scopes",exports.CUSTOM_INTERACTIONS={submit:"submit",polling:"polling"},exports.DESCOPE_ATTRIBUTE_EXCLUDE_FIELD="data-exclude-field",exports.DESCOPE_ATTRIBUTE_EXCLUDE_NEXT_BUTTON="data-exclude-next",exports.DESCOPE_ATTRIBUTE_PREFIX="data-descope-",exports.DESCOPE_IDP_INITIATED_PARAM_NAME="descope_idp_initiated",exports.DESCOPE_LAST_AUTH_LOCAL_STORAGE_KEY="dls_last_auth",exports.ELEMENTS_TO_IGNORE_ENTER_KEY_ON=["descope-multi-select-combo-box","descope-text-area"],exports.ELEMENT_TYPE_ATTRIBUTE="data-type",exports.HAS_DYNAMIC_VALUES_ATTR_NAME="data-has-dynamic-attr-values",exports.OIDC_ERROR_REDIRECT_URI_PARAM_NAME="oidc_error_redirect_uri",exports.OIDC_IDP_STATE_ID_PARAM_NAME="state_id",exports.OIDC_LOGIN_HINT_PARAM_NAME="oidc_login_hint",exports.OIDC_PROMPT_PARAM_NAME="oidc_prompt",exports.RESPONSE_ACTIONS={redirect:"redirect",poll:"poll",webauthnCreate:"webauthnCreate",webauthnGet:"webauthnGet",nativeBridge:"nativeBridge",loadForm:"loadForm"},exports.SAML_IDP_STATE_ID_PARAM_NAME="saml_idp_state_id",exports.SAML_IDP_USERNAME_PARAM_NAME="saml_idp_username",exports.SDK_SCRIPT_RESULTS_KEY="sdkScriptsResults",exports.SSO_APP_ID_PARAM_NAME="sso_app_id",exports.THIRD_PARTY_APP_ID_PARAM_NAME="third_party_app_id",exports.THIRD_PARTY_APP_STATE_ID_PARAM_NAME="third_party_app_state_id",exports.URL_CODE_PARAM_NAME="code",exports.URL_ERR_PARAM_NAME="err",exports.URL_REDIRECT_AUTH_BACKUP_CALLBACK_PARAM_NAME="ra-backup-callback",exports.URL_REDIRECT_AUTH_CALLBACK_PARAM_NAME="ra-callback",exports.URL_REDIRECT_AUTH_CHALLENGE_PARAM_NAME="ra-challenge",exports.URL_REDIRECT_AUTH_INITIATOR_PARAM_NAME="ra-initiator",exports.URL_RUN_IDS_PARAM_NAME="descope-login-flow",exports.URL_TOKEN_PARAM_NAME="t";
|
|
2
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../../../src/lib/constants/index.ts"],"sourcesContent":["export * from './general';\nexport * from './content';\nexport * from './uiComponents';\n\nexport const URL_RUN_IDS_PARAM_NAME = 'descope-login-flow';\nexport const URL_TOKEN_PARAM_NAME = 't';\nexport const URL_CODE_PARAM_NAME = 'code';\nexport const URL_ERR_PARAM_NAME = 'err';\nexport const URL_REDIRECT_AUTH_CHALLENGE_PARAM_NAME = 'ra-challenge';\nexport const URL_REDIRECT_AUTH_CALLBACK_PARAM_NAME = 'ra-callback';\nexport const URL_REDIRECT_AUTH_BACKUP_CALLBACK_PARAM_NAME =\n 'ra-backup-callback';\nexport const URL_REDIRECT_AUTH_INITIATOR_PARAM_NAME = 'ra-initiator';\nexport const DESCOPE_ATTRIBUTE_PREFIX = 'data-descope-';\nexport const DESCOPE_ATTRIBUTE_EXCLUDE_FIELD = 'data-exclude-field';\nexport const DESCOPE_ATTRIBUTE_EXCLUDE_NEXT_BUTTON = 'data-exclude-next';\nexport const DESCOPE_LAST_AUTH_LOCAL_STORAGE_KEY = 'dls_last_auth';\n\n// SSO query params\nexport const OIDC_IDP_STATE_ID_PARAM_NAME = 'state_id';\nexport const SAML_IDP_STATE_ID_PARAM_NAME = 'saml_idp_state_id';\nexport const SAML_IDP_USERNAME_PARAM_NAME = 'saml_idp_username';\nexport const DESCOPE_IDP_INITIATED_PARAM_NAME = 'descope_idp_initiated';\nexport const SSO_APP_ID_PARAM_NAME = 'sso_app_id';\nexport const THIRD_PARTY_APP_ID_PARAM_NAME = 'third_party_app_id';\nexport const THIRD_PARTY_APP_STATE_ID_PARAM_NAME = 'third_party_app_state_id';\nexport const OIDC_LOGIN_HINT_PARAM_NAME = 'oidc_login_hint';\nexport const OIDC_PROMPT_PARAM_NAME = 'oidc_prompt';\nexport const OIDC_ERROR_REDIRECT_URI_PARAM_NAME = 'oidc_error_redirect_uri';\nexport const APPLICATION_SCOPES_PARAM_NAME = 'application_scopes';\n\nexport const ELEMENT_TYPE_ATTRIBUTE = 'data-type';\n\nexport const SDK_SCRIPT_RESULTS_KEY = 'sdkScriptsResults';\n\nexport const RESPONSE_ACTIONS = {\n redirect: 'redirect',\n poll: 'poll',\n webauthnCreate: 'webauthnCreate',\n webauthnGet: 'webauthnGet',\n nativeBridge: 'nativeBridge',\n loadForm: 'loadForm',\n};\n\nexport const CUSTOM_INTERACTIONS = {\n submit: 'submit',\n polling: 'polling',\n};\n\nexport const HAS_DYNAMIC_VALUES_ATTR_NAME = 'data-has-dynamic-attr-values';\n\nexport const ELEMENTS_TO_IGNORE_ENTER_KEY_ON = [\n 'descope-multi-select-combo-box',\n 'descope-text-area',\n];\n"],"names":["submit","polling","redirect","poll","webauthnCreate","webauthnGet","nativeBridge","loadForm"],"mappings":"8YA6B6C,iDAeV,CACjCA,OAAQ,SACRC,QAAS,mDAhCoC,mEACM,qDAFb,yDASQ,oEANG,wDAmCJ,CAC7C,iCACA,oDAtBoC,iDAkBM,0EArBM,+DATN,8CAOF,iDACJ,uCAQN,CAC9BC,SAAU,WACVC,KAAM,OACNC,eAAgB,iBAChBC,YAAa,cACbC,aAAc,eACdC,SAAU,iDArBgC,yDACA,mDAYN,kDAVD,mDACQ,iEACM,uDAnBhB,kCACD,2DAIhC,mEAFmD,6DADC,8DAIA,8CARhB,kDACF"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"uiComponents.js","sources":["../../../src/lib/constants/uiComponents.ts"],"sourcesContent":["import { IS_LOCAL_STORAGE } from './general';\n\nexport const UI_COMPONENTS_URL_KEY = 'base.ui.components.url';\n\nexport const UI_COMPONENTS_URL =\n (IS_LOCAL_STORAGE && localStorage.getItem(UI_COMPONENTS_URL_KEY)) ||\n 'https://descopecdn.com/npm/@descope/web-components-ui@<version>/dist/umd/index.js';\n\nexport const UI_COMPONENTS_FALLBACK_URL =\n (IS_LOCAL_STORAGE && localStorage.getItem(UI_COMPONENTS_URL_KEY)) ||\n 'https://static.descope.com/npm/@descope/web-components-ui@<version>/dist/umd/index.js';\n\nexport const UI_COMPONENTS_URL_VERSION_PLACEHOLDER = '<version>';\n"],"names":["UI_COMPONENTS_URL_KEY","IS_LOCAL_STORAGE","localStorage","getItem"],"mappings":"2CAEO,MAAMA,EAAwB,yBAGlCC,oBAAoBC,aAAaC,QAAQH,GAIzCC,oBAAoBC,aAAaC,QAAQH"}
|
package/dist/cjs/debugger-wc.js
CHANGED
|
@@ -1 +1,2 @@
|
|
|
1
1
|
"use strict";var e=require("tslib");require("./constants/content.js"),require("./constants/uiComponents.js"),require("./types.js");var s=require("./helpers/state.js");require("@descope/escape-markdown"),require("./helpers/webauthn.js");var t,n,i,l,a,r,o,d,c,p,h=require("./helpers/positionHelpers.js");const g=document.createElement("template");g.innerHTML=`\n<style>\n .debugger {\n width: 300px;\n height: 200px;\n background-color: #FAFAFA;\n position: fixed;\n font-family: "Helvetica Neue", sans-serif;\n box-shadow: rgba(0, 0, 0, 0.1) 0px 5px 10px;\n border-radius: 8px;\n overflow: hidden;\n border: 1px solid lightgrey;\n pointer-events: initial;\n display: flex;\n flex-direction: column;\n min-width: 200px;\n max-width: 600px;\n max-height: calc(100% - 64px);\n min-height: 200px;\n resize: both;\n }\n\n .header {\n padding: 8px 16px;\n display: flex;\n align-items: center;\n background-color: #EEEEEE;\n cursor: move;\n border-bottom: 1px solid #e0e0e0;\n }\n\n .content {\n font-size: 14px;\n flex-grow: 1;\n overflow: auto;\n }\n\n .msg {\n border-bottom: 1px solid lightgrey;\n padding: 8px 16px;\n display: flex;\n gap: 5px;\n background-color: #FAFAFA;\n }\n\n .msg.collapsible {\n cursor: pointer;\n }\n\n .empty-state {\n padding: 8px 16px;\n background-color: #FAFAFA;\n }\n\n\n .msg.collapsible:not(.collapsed) {\n background-color: #F5F5F5;\n }\n\n .msg_title {\n padding-bottom: 5px;\n display: flex;\n gap: 8px;\n font-weight: 500;\n }\n\n .msg svg {\n padding: 1px;\n flex-shrink: 0;\n margin-top: -2px;\n }\n\n .msg_content {\n overflow: hidden;\n flex-grow: 1;\n margin-right:5px;\n }\n\n .msg_desc {\n color: #646464;\n cursor: initial;\n word-wrap: break-word;\n }\n\n .msg.collapsed .msg_desc {\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n }\n\n .msg.collapsible.collapsed .chevron {\n transform: rotate(-45deg) translateX(-2px);\n }\n\n .msg.collapsible .chevron {\n content: "";\n width:6px;\n height:6px;\n border-bottom: 2px solid grey;\n border-right: 2px solid grey;\n transform: rotate(45deg) translateX(-1px);\n margin: 5px;\n flex-shrink:0;\n }\n</style>\n\n<div style="top:32px; left:${window.innerWidth-300-32}px;" class="debugger">\n <div class="header">\n <span>Debugger messages</span>\n </div>\n <div class="content">\n <div class="empty-state">\n No errors detected 👀\n </div>\n </div>\n</div>\n`;class v extends HTMLElement{constructor(){super(),t.add(this),n.set(this,new s({messages:[]})),i.set(this,void 0),l.set(this,void 0),a.set(this,void 0),r.set(this,{resize:e.__classPrivateFieldGet(this,t,"m",p).bind(this)}),this.attachShadow({mode:"open"}),this.shadowRoot.appendChild(g.content.cloneNode(!0)),e.__classPrivateFieldSet(this,i,this.shadowRoot.querySelector(".debugger"),"f"),e.__classPrivateFieldSet(this,l,e.__classPrivateFieldGet(this,i,"f").querySelector(".content"),"f"),e.__classPrivateFieldSet(this,a,e.__classPrivateFieldGet(this,i,"f").querySelector(".header"),"f")}updateData(s){e.__classPrivateFieldGet(this,n,"f").update((e=>({messages:e.messages.concat(s)})))}connectedCallback(){h.dragElement(e.__classPrivateFieldGet(this,i,"f"),e.__classPrivateFieldGet(this,a,"f"),{top:"all",bottom:100,left:100,right:100}),window.addEventListener("resize",e.__classPrivateFieldGet(this,r,"f").resize),h.addOnResize(e.__classPrivateFieldGet(this,i,"f")),e.__classPrivateFieldGet(this,i,"f").onresize=e.__classPrivateFieldGet(this,t,"m",c).bind(this),e.__classPrivateFieldGet(this,n,"f").subscribe(e.__classPrivateFieldGet(this,t,"m",o).bind(this))}disconnectedCallback(){e.__classPrivateFieldGet(this,n,"f").unsubscribeAll(),window.removeEventListener("resize",e.__classPrivateFieldGet(this,r,"f").resize)}}n=new WeakMap,i=new WeakMap,l=new WeakMap,a=new WeakMap,r=new WeakMap,t=new WeakSet,o=function(s){e.__classPrivateFieldGet(this,t,"m",d).call(this,s),e.__classPrivateFieldGet(this,t,"m",c).call(this)},d=function(s){e.__classPrivateFieldGet(this,l,"f").innerHTML=s.messages.map((e=>`\n <div class="msg">\n <svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">\n<path d="M5.99984 13.167L8.99984 10.167L11.9998 13.167L13.1665 12.0003L10.1665 9.00033L13.1665 6.00033L11.9998 4.83366L8.99984 7.83366L5.99984 4.83366L4.83317 6.00033L7.83317 9.00033L4.83317 12.0003L5.99984 13.167ZM8.99984 17.3337C7.84706 17.3337 6.76373 17.1148 5.74984 16.677C4.73595 16.2398 3.854 15.6462 3.104 14.8962C2.354 14.1462 1.76039 13.2642 1.32317 12.2503C0.885393 11.2364 0.666504 10.1531 0.666504 9.00033C0.666504 7.84755 0.885393 6.76421 1.32317 5.75033C1.76039 4.73644 2.354 3.85449 3.104 3.10449C3.854 2.35449 4.73595 1.7606 5.74984 1.32283C6.76373 0.885603 7.84706 0.666992 8.99984 0.666992C10.1526 0.666992 11.2359 0.885603 12.2498 1.32283C13.2637 1.7606 14.1457 2.35449 14.8957 3.10449C15.6457 3.85449 16.2393 4.73644 16.6765 5.75033C17.1143 6.76421 17.3332 7.84755 17.3332 9.00033C17.3332 10.1531 17.1143 11.2364 16.6765 12.2503C16.2393 13.2642 15.6457 14.1462 14.8957 14.8962C14.1457 15.6462 13.2637 16.2398 12.2498 16.677C11.2359 17.1148 10.1526 17.3337 8.99984 17.3337ZM8.99984 15.667C10.8609 15.667 12.4373 15.0212 13.729 13.7295C15.0207 12.4378 15.6665 10.8614 15.6665 9.00033C15.6665 7.13921 15.0207 5.56283 13.729 4.27116C12.4373 2.97949 10.8609 2.33366 8.99984 2.33366C7.13873 2.33366 5.56234 2.97949 4.27067 4.27116C2.979 5.56283 2.33317 7.13921 2.33317 9.00033C2.33317 10.8614 2.979 12.4378 4.27067 13.7295C5.56234 15.0212 7.13873 15.667 8.99984 15.667Z" fill="#ED404A"/>\n</svg>\n\n <div class="msg_content">\n <div class="msg_title">\n ${e.title}\n </div>\n <div class="msg_desc">\n ${e.description}\n </div>\n </div>\n <div class="chevron"></div>\n </div>\n `)).join("")},c=function(){e.__classPrivateFieldGet(this,l,"f").querySelectorAll(".msg").forEach((e=>{const s=e.querySelector(".msg_desc"),t=s.scrollWidth>s.clientWidth,n=s.clientHeight>20;t||n?(e.classList.add("collapsible"),e.onclick=s=>{s.target.classList.contains("msg_desc")||e.classList.toggle("collapsed")}):(e.classList.remove("collapsible"),e.onclick=null)}))},p=function(){const[s,t]=h.limitCoordinateToScreenBoundaries(e.__classPrivateFieldGet(this,i,"f"),Number.parseInt(e.__classPrivateFieldGet(this,i,"f").style.left,10),Number.parseInt(e.__classPrivateFieldGet(this,i,"f").style.top,10),{top:"all",bottom:100,left:100,right:100});e.__classPrivateFieldGet(this,i,"f").style.top=`${t}px`,e.__classPrivateFieldGet(this,i,"f").style.left=`${s}px`},customElements.get("descope-debugger")||customElements.define("descope-debugger",v),module.exports=v;
|
|
2
|
+
//# sourceMappingURL=debugger-wc.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"debugger-wc.js","sources":["../../src/lib/debugger-wc.ts"],"sourcesContent":["/* eslint-disable no-param-reassign */\nimport {\n addOnResize,\n dragElement,\n limitCoordinateToScreenBoundaries,\n State,\n} from './helpers';\nimport { DebuggerMessage } from './types';\n\nconst INITIAL_POS_THRESHOLD = 32;\nconst INITIAL_WIDTH = 300;\nconst INITIAL_HEIGHT = 200;\nconst MIN_SIZE = 200;\n\nconst template = document.createElement('template');\ntemplate.innerHTML = `\n<style>\n .debugger {\n width: ${INITIAL_WIDTH}px;\n height: ${INITIAL_HEIGHT}px;\n background-color: #FAFAFA;\n position: fixed;\n font-family: \"Helvetica Neue\", sans-serif;\n box-shadow: rgba(0, 0, 0, 0.1) 0px 5px 10px;\n border-radius: 8px;\n overflow: hidden;\n border: 1px solid lightgrey;\n pointer-events: initial;\n display: flex;\n flex-direction: column;\n min-width: ${MIN_SIZE}px;\n max-width: 600px;\n max-height: calc(100% - ${INITIAL_POS_THRESHOLD * 2}px);\n min-height: ${MIN_SIZE}px;\n resize: both;\n }\n\n .header {\n padding: 8px 16px;\n display: flex;\n align-items: center;\n background-color: #EEEEEE;\n cursor: move;\n border-bottom: 1px solid #e0e0e0;\n }\n\n .content {\n font-size: 14px;\n flex-grow: 1;\n overflow: auto;\n }\n\n .msg {\n border-bottom: 1px solid lightgrey;\n padding: 8px 16px;\n display: flex;\n gap: 5px;\n background-color: #FAFAFA;\n }\n\n .msg.collapsible {\n cursor: pointer;\n }\n\n .empty-state {\n padding: 8px 16px;\n background-color: #FAFAFA;\n }\n\n\n .msg.collapsible:not(.collapsed) {\n background-color: #F5F5F5;\n }\n\n .msg_title {\n padding-bottom: 5px;\n display: flex;\n gap: 8px;\n font-weight: 500;\n }\n\n .msg svg {\n padding: 1px;\n flex-shrink: 0;\n margin-top: -2px;\n }\n\n .msg_content {\n overflow: hidden;\n flex-grow: 1;\n margin-right:5px;\n }\n\n .msg_desc {\n color: #646464;\n cursor: initial;\n word-wrap: break-word;\n }\n\n .msg.collapsed .msg_desc {\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n }\n\n .msg.collapsible.collapsed .chevron {\n transform: rotate(-45deg) translateX(-2px);\n }\n\n .msg.collapsible .chevron {\n content: \"\";\n width:6px;\n height:6px;\n border-bottom: 2px solid grey;\n border-right: 2px solid grey;\n transform: rotate(45deg) translateX(-1px);\n margin: 5px;\n flex-shrink:0;\n }\n</style>\n\n<div style=\"top:${INITIAL_POS_THRESHOLD}px; left:${\n window.innerWidth - INITIAL_WIDTH - INITIAL_POS_THRESHOLD\n}px;\" class=\"debugger\">\n <div class=\"header\">\n <span>Debugger messages</span>\n </div>\n <div class=\"content\">\n <div class=\"empty-state\">\n No errors detected 👀\n </div>\n </div>\n</div>\n`;\n\nconst icon = `<svg width=\"18\" height=\"18\" viewBox=\"0 0 18 18\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n<path d=\"M5.99984 13.167L8.99984 10.167L11.9998 13.167L13.1665 12.0003L10.1665 9.00033L13.1665 6.00033L11.9998 4.83366L8.99984 7.83366L5.99984 4.83366L4.83317 6.00033L7.83317 9.00033L4.83317 12.0003L5.99984 13.167ZM8.99984 17.3337C7.84706 17.3337 6.76373 17.1148 5.74984 16.677C4.73595 16.2398 3.854 15.6462 3.104 14.8962C2.354 14.1462 1.76039 13.2642 1.32317 12.2503C0.885393 11.2364 0.666504 10.1531 0.666504 9.00033C0.666504 7.84755 0.885393 6.76421 1.32317 5.75033C1.76039 4.73644 2.354 3.85449 3.104 3.10449C3.854 2.35449 4.73595 1.7606 5.74984 1.32283C6.76373 0.885603 7.84706 0.666992 8.99984 0.666992C10.1526 0.666992 11.2359 0.885603 12.2498 1.32283C13.2637 1.7606 14.1457 2.35449 14.8957 3.10449C15.6457 3.85449 16.2393 4.73644 16.6765 5.75033C17.1143 6.76421 17.3332 7.84755 17.3332 9.00033C17.3332 10.1531 17.1143 11.2364 16.6765 12.2503C16.2393 13.2642 15.6457 14.1462 14.8957 14.8962C14.1457 15.6462 13.2637 16.2398 12.2498 16.677C11.2359 17.1148 10.1526 17.3337 8.99984 17.3337ZM8.99984 15.667C10.8609 15.667 12.4373 15.0212 13.729 13.7295C15.0207 12.4378 15.6665 10.8614 15.6665 9.00033C15.6665 7.13921 15.0207 5.56283 13.729 4.27116C12.4373 2.97949 10.8609 2.33366 8.99984 2.33366C7.13873 2.33366 5.56234 2.97949 4.27067 4.27116C2.979 5.56283 2.33317 7.13921 2.33317 9.00033C2.33317 10.8614 2.979 12.4378 4.27067 13.7295C5.56234 15.0212 7.13873 15.667 8.99984 15.667Z\" fill=\"#ED404A\"/>\n</svg>\n`;\n\ntype MessagesState = { messages: DebuggerMessage[] };\n\nclass Debugger extends HTMLElement {\n #messagesState = new State<MessagesState>({ messages: [] });\n\n #rootEle: HTMLDivElement;\n\n #contentEle: HTMLDivElement;\n\n #headerEle: HTMLDivElement;\n\n #eventsCbRefs = {\n resize: this.#onWindowResize.bind(this),\n };\n\n constructor() {\n super();\n\n this.attachShadow({ mode: 'open' });\n this.shadowRoot.appendChild(template.content.cloneNode(true));\n\n this.#rootEle = this.shadowRoot.querySelector<HTMLDivElement>('.debugger');\n this.#contentEle = this.#rootEle.querySelector<HTMLDivElement>('.content');\n this.#headerEle = this.#rootEle.querySelector<HTMLDivElement>('.header');\n }\n\n updateData(data: DebuggerMessage | DebuggerMessage[]) {\n this.#messagesState.update((state) => ({\n messages: state.messages.concat(data),\n }));\n }\n\n #onNewMessages(data: MessagesState) {\n this.#renderMessages(data);\n this.#setCollapsibleMessages();\n }\n\n #renderMessages(data: MessagesState) {\n this.#contentEle.innerHTML = data.messages\n .map(\n (message) => `\n <div class=\"msg\">\n ${icon}\n <div class=\"msg_content\">\n <div class=\"msg_title\">\n ${message.title}\n </div>\n <div class=\"msg_desc\">\n ${message.description}\n </div>\n </div>\n <div class=\"chevron\"></div>\n </div>\n `,\n )\n .join('');\n }\n\n #setCollapsibleMessages() {\n this.#contentEle.querySelectorAll('.msg').forEach((ele: HTMLElement) => {\n const descEle = ele.querySelector('.msg_desc');\n const lineHeight = 20;\n const isScroll = descEle.scrollWidth > descEle.clientWidth;\n const isMultiLine = descEle.clientHeight > lineHeight;\n const isCollapsible = isScroll || isMultiLine;\n\n if (isCollapsible) {\n ele.classList.add('collapsible');\n ele.onclick = (e: MouseEvent) => {\n // message description should not toggle collapse\n if (!(e.target as HTMLElement).classList.contains('msg_desc')) {\n ele.classList.toggle('collapsed');\n }\n };\n } else {\n ele.classList.remove('collapsible');\n ele.onclick = null;\n }\n });\n }\n\n #onWindowResize() {\n // when window is resizing we want to make sure debugger is still visible\n const [left, top] = limitCoordinateToScreenBoundaries(\n this.#rootEle,\n Number.parseInt(this.#rootEle.style.left, 10),\n Number.parseInt(this.#rootEle.style.top, 10),\n { top: 'all', bottom: 100, left: 100, right: 100 },\n );\n this.#rootEle.style.top = `${top}px`;\n this.#rootEle.style.left = `${left}px`;\n }\n\n connectedCallback() {\n dragElement(this.#rootEle, this.#headerEle, {\n top: 'all',\n bottom: 100,\n left: 100,\n right: 100,\n });\n\n window.addEventListener('resize', this.#eventsCbRefs.resize);\n\n addOnResize(this.#rootEle);\n this.#rootEle.onresize = this.#setCollapsibleMessages.bind(this);\n\n this.#messagesState.subscribe(this.#onNewMessages.bind(this));\n }\n\n disconnectedCallback() {\n this.#messagesState.unsubscribeAll();\n window.removeEventListener('resize', this.#eventsCbRefs.resize);\n }\n}\n\nif (!customElements.get('descope-debugger')) {\n customElements.define('descope-debugger', Debugger);\n}\nexport default Debugger;\n"],"names":["template","document","createElement","innerHTML","window","innerWidth","Debugger","HTMLElement","constructor","super","_Debugger_messagesState","set","this","State","messages","_Debugger_rootEle","_Debugger_contentEle","_Debugger_headerEle","_Debugger_eventsCbRefs","resize","__classPrivateFieldGet","_Debugger_instances","_Debugger_onWindowResize","bind","attachShadow","mode","shadowRoot","appendChild","content","cloneNode","__classPrivateFieldSet","querySelector","updateData","data","update","state","concat","connectedCallback","dragElement","top","bottom","left","right","addEventListener","addOnResize","onresize","_Debugger_setCollapsibleMessages","subscribe","_Debugger_onNewMessages","disconnectedCallback","unsubscribeAll","removeEventListener","_Debugger_renderMessages","call","map","message","title","description","join","querySelectorAll","forEach","ele","descEle","isScroll","scrollWidth","clientWidth","isMultiLine","clientHeight","classList","add","onclick","e","target","contains","toggle","remove","limitCoordinateToScreenBoundaries","Number","parseInt","style","customElements","get","define"],"mappings":"8SASA,MAKMA,EAAWC,SAASC,cAAc,YACxCF,EAASG,UAAY,s9DA2GnBC,OAAOC,WAhHa,IADQ,sNAqI9B,MAAMC,UAAiBC,YAarB,WAAAC,GACEC,oBAbFC,EAAiBC,IAAAC,KAAA,IAAIC,EAAqB,CAAEC,SAAU,MAEtDC,EAAyBJ,IAAAC,UAAA,GAEzBI,EAA4BL,IAAAC,UAAA,GAE5BK,EAA2BN,IAAAC,UAAA,GAE3BM,EAAgBP,IAAAC,KAAA,CACdO,OAAQC,EAAAA,uBAAAR,KAAIS,EAAA,I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KAAAzC,KACF,aAEgBqB,GACdb,EAAAA,uBAAAR,KAAgBI,EAAA,KAACb,UAAY8B,EAAKnB,SAC/BwC,KACEC,GAAY,qlDAKTA,EAAQC,oEAGRD,EAAQE,iGAObC,KAAK,GACV,EAACZ,EAAA,WAGC1B,yBAAAR,KAAII,EAAA,KAAa2C,iBAAiB,QAAQC,SAASC,IACjD,MAAMC,EAAUD,EAAI9B,cAAc,aAE5BgC,EAAWD,EAAQE,YAAcF,EAAQG,YACzCC,EAAcJ,EAAQK,aAFT,GAGGJ,GAAYG,GAGhCL,EAAIO,UAAUC,IAAI,eAClBR,EAAIS,QAAWC,IAEPA,EAAEC,OAAuBJ,UAAUK,SAAS,aAChDZ,EAAIO,UAAUM,OAAO,YACtB,IAGHb,EAAIO,UAAUO,OAAO,eACrBd,EAAIS,QAAU,KACf,GAEL,EAAChD,EAAA,WAIC,MAAOmB,EAAMF,GAAOqC,EAAAA,kCAClBxD,EAAAA,uBAAAR,KAAaG,EAAA,KACb8D,OAAOC,SAAS1D,EAAAA,uBAAAR,KAAaG,EAAA,KAACgE,MAAMtC,KAAM,IAC1CoC,OAAOC,SAAS1D,EAAAA,uBAAAR,KAAIG,EAAA,KAAUgE,MAAMxC,IAAK,IACzC,CAAEA,IAAK,MAAOC,OAAQ,IAAKC,KAAM,IAAKC,MAAO,MAE/CtB,yBAAAR,KAAaG,EAAA,KAACgE,MAAMxC,IAAM,GAAGA,MAC7BnB,yBAAAR,KAAaG,EAAA,KAACgE,MAAMtC,KAAO,GAAGA,KAChC,EAwBGuC,eAAeC,IAAI,qBACtBD,eAAeE,OAAO,mBAAoB5E"}
|
|
@@ -1 +1,2 @@
|
|
|
1
|
-
"use strict";var t=require("tslib"),e=require("@descope/sdk-helpers"),i=require("@descope/sdk-mixins/static-resources-mixin"),s=require("@descope/sdk-mixins/theme-mixin"),r=require("@descope/web-js-sdk"),o=require("../constants/index.js"),n=require("../helpers/helpers.js"),a=require("../helpers/state.js");require("@descope/escape-markdown"),require("../helpers/webauthn.js");var l,u,d,c,h,g,f,v,p,_,b,m,w,C,F,A,P,x,k,E,I,y=require("../helpers/flowInputs.js"),G=require("../mixins/formMountMixin.js"),j=require("./initTemplate.js"),L=require("../constants/content.js"),S=require("../constants/general.js");function U(t){return Object.freeze({__proto__:null,default:t})}const M=e.compose(s.themeMixin,i.staticResourcesMixin,G.formMountMixin)(HTMLElement);class q extends M{static get observedAttributes(){return["project-id","flow-id","base-url","tenant","locale","debug","storage-prefix","preview","redirect-url","auto-focus","store-last-authenticated-user","keep-last-authenticated-user-after-logout","validate-on-blur","style-id"]}constructor(e){super(),l.add(this),d.set(this,!1),this.flowStatus="initial",this.loggerWrapper={error:(e,i="")=>{this.logger.error(e,i,new Error),t.__classPrivateFieldGet(this,l,"m",E).call(this,e,i)},warn:(t,e="")=>{this.logger.warn(t,e)},info:(t,e="",i={})=>{this.logger.info(t,e,i)},debug:(t,e="")=>{this.logger.debug(t,e)}},c.set(this,new a),h.set(this,new a),g.set(this,{}),this.getComponentsContext=()=>t.__classPrivateFieldGet(this,g,"f"),this.nextRequestStatus=new a({isLoading:!1}),f.set(this,void 0),v.set(this,{popstate:t.__classPrivateFieldGet(this,l,"m",m).bind(this),componentsContext:t.__classPrivateFieldGet(this,l,"m",P).bind(this)}),p.set(this,void 0),this.getConfig=()=>t.__awaiter(this,void 0,void 0,(function*(){return(yield this.config)||{isMissingConfig:!0}})),t.__classPrivateFieldSet(this,p,e,"f"),t.__classPrivateFieldGet(this,l,"m",_).call(this)}get flowId(){return this.getAttribute("flow-id")}get client(){try{return JSON.parse(this.getAttribute("client"))||{}}catch(t){return{}}}get tenantId(){return this.getAttribute("tenant")||void 0}get redirectUrl(){return this.getAttribute("redirect-url")||void 0}get debug(){return"true"===this.getAttribute("debug")}get locale(){return this.getAttribute("locale")||void 0}get autoFocus(){var t;const e=null!==(t=this.getAttribute("auto-focus"))&&void 0!==t?t:"true";return"skipFirstScreen"===e?e:"true"===e}get validateOnBlur(){return"true"===this.getAttribute("validate-on-blur")}get storeLastAuthenticatedUser(){var t;return"true"===(null!==(t=this.getAttribute("store-last-authenticated-user"))&&void 0!==t?t:"true")}get keepLastAuthenticatedUserAfterLogout(){return"true"===this.getAttribute("keep-last-authenticated-user-after-logout")}get storagePrefix(){return this.getAttribute("storage-prefix")||""}get preview(){return!!this.getAttribute("preview")}get formConfig(){return y.transformFlowInputFormData(this.form)}get form(){return this.getAttribute("form")}get formConfigValues(){return y.extractNestedAttribute(this.formConfig,"value")}get isRestartOnError(){return"true"===this.getAttribute("restart-on-error")}getExecutionContext(){return t.__awaiter(this,void 0,void 0,(function*(){const t=yield this.getConfig();return"executionContext"in t?t.executionContext:void 0}))}getProjectConfig(){return t.__awaiter(this,void 0,void 0,(function*(){const t=yield this.getConfig();return"projectConfig"in t?t.projectConfig:void 0}))}getFlowConfig(){return t.__awaiter(this,void 0,void 0,(function*(){var t,e;const i=yield this.getProjectConfig(),s=(null===(t=null==i?void 0:i.flows)||void 0===t?void 0:t[this.flowId])||{};return null!==(e=s.version)&&void 0!==e||(s.version=0),s}))}getTargetLocales(){return t.__awaiter(this,void 0,void 0,(function*(){const t=yield this.getFlowConfig();return((null==t?void 0:t.targetLocales)||[]).map((t=>t.toLowerCase()))}))}getComponentsVersion(){return t.__awaiter(this,void 0,void 0,(function*(){var t;const e=yield this.getConfig(),i="projectConfig"in e?null===(t=e.projectConfig)||void 0===t?void 0:t.componentsVersion:{};return i||(this.logger.error("Did not get components version, using latest version"),"latest")}))}init(){const e=Object.create(null,{init:{get:()=>super.init}});return t.__awaiter(this,void 0,void 0,(function*(){var i;if(this.flowStatus="loading",["ready","error","success"].forEach((t=>this.addEventListener(t,(()=>{this.flowStatus=t})))),yield null===(i=e.init)||void 0===i?void 0:i.call(this),t.__classPrivateFieldGet(this,h,"f").subscribe(t.__classPrivateFieldGet(this,l,"m",k).bind(this)),t.__classPrivateFieldGet(this,h,"f").update({isDebug:this.debug}),t.__classPrivateFieldGet(this,l,"m",b).call(this),yield t.__classPrivateFieldGet(this,l,"m",F).call(this))return void this.loggerWrapper.error("This SDK version does not support your flows version","Make sure to upgrade your flows to the latest version or use an older SDK version");const s=yield this.getConfig();if("isMissingConfig"in s&&s.isMissingConfig)return void this.loggerWrapper.error("Cannot get config file","Make sure that your projectId & flowId are correct");t.__classPrivateFieldGet(this,l,"m",I).call(this);const{executionId:r,stepId:o,token:a,code:u,exchangeError:g,redirectAuthCallbackUrl:f,redirectAuthBackupCallbackUri:p,redirectAuthCodeChallenge:_,redirectAuthInitiator:m,ssoQueryParams:w}=n.handleUrlParams(this.flowId,this.loggerWrapper);window.addEventListener("popstate",t.__classPrivateFieldGet(this,v,"f").popstate),window.addEventListener("components-context",t.__classPrivateFieldGet(this,v,"f").componentsContext),t.__classPrivateFieldGet(this,c,"f").subscribe(t.__classPrivateFieldGet(this,l,"m",C).bind(this)),t.__classPrivateFieldGet(this,c,"f").update(Object.assign({projectId:this.projectId,flowId:this.flowId,baseUrl:this.baseUrl,tenant:this.tenantId,redirectUrl:this.redirectUrl,locale:this.locale,stepId:o,executionId:r,token:a,code:u,exchangeError:g,redirectAuthCallbackUrl:f,redirectAuthBackupCallbackUri:p,redirectAuthCodeChallenge:_,redirectAuthInitiator:m},w)),t.__classPrivateFieldSet(this,d,!0,"f")}))}disconnectedCallback(){t.__classPrivateFieldGet(this,c,"f").unsubscribeAll(),t.__classPrivateFieldGet(this,h,"f").unsubscribeAll(),t.__classPrivateFieldGet(this,l,"m",x).call(this),window.removeEventListener("popstate",t.__classPrivateFieldGet(this,v,"f").popstate),window.removeEventListener("components-context",t.__classPrivateFieldGet(this,v,"f").componentsContext)}attributeChangedCallback(e,i,s){if(this.shadowRoot.isConnected&&t.__classPrivateFieldGet(this,d,"f")&&i!==s&&u.observedAttributes.includes(e)){t.__classPrivateFieldGet(this,l,"m",b).call(this);const r=null===i;t.__classPrivateFieldGet(this,c,"f").update((({stepId:t,executionId:i})=>{let o=t,a=i;return r||(a=null,o=null,n.clearRunIdsFromUrl()),{[n.camelCase(e)]:s,stepId:o,executionId:a}})),t.__classPrivateFieldGet(this,h,"f").update({isDebug:this.debug})}}}u=q,d=new WeakMap,c=new WeakMap,h=new WeakMap,g=new WeakMap,f=new WeakMap,v=new WeakMap,p=new WeakMap,l=new WeakSet,_=function(){this.shadowRoot.appendChild(j.content.cloneNode(!0)),this.rootElement=this.shadowRoot.querySelector("#root")},b=function(){const t=["base-url","tenant","locale","debug","redirect-url","auto-focus","store-last-authenticated-user","keep-last-authenticated-user-after-logout","preview","storage-prefix","form","client","validate-on-blur","style-id"];u.observedAttributes.forEach((e=>{if(!t.includes(e)&&!this[n.camelCase(e)])throw Error(`${e} cannot be empty`)}))},m=function(){const{stepId:e,executionId:i}=n.getRunIdsFromUrl(this.flowId);t.__classPrivateFieldGet(this,c,"f").update({stepId:e,executionId:i})},w=function(e,i){this.sdk=r(Object.assign(Object.assign({persistTokens:!0,preview:this.preview,storagePrefix:this.storagePrefix,storeLastAuthenticatedUser:this.storeLastAuthenticatedUser,keepLastAuthenticatedUserAfterLogout:this.keepLastAuthenticatedUserAfterLogout},u.sdkConfigOverrides),{projectId:e,baseUrl:i})),["start","next"].forEach((e=>{const i=this.sdk.flow[e];this.sdk.flow[e]=(...e)=>t.__awaiter(this,void 0,void 0,(function*(){this.nextRequestStatus.update({isLoading:!0});try{return yield i(...e)}catch(t){return{error:{errorCode:S.FETCH_EXCEPTION_ERROR_CODE,errorDescription:t.toString()}}}finally{this.nextRequestStatus.update({isLoading:!1})}}))}))},C=function(e,i,s){return t.__awaiter(this,void 0,void 0,(function*(){const{projectId:i,baseUrl:r}=e;if(s("projectId")||s("baseUrl")){if(!i)return;t.__classPrivateFieldGet(this,l,"m",w).call(this,i,r)}t.__classPrivateFieldGet(this,p,"f").call(this,e)}))},F=function(){return t.__awaiter(this,void 0,void 0,(function*(){const e=yield this.getConfig();return"isMissingConfig"in e&&e.isMissingConfig&&(yield t.__classPrivateFieldGet(this,l,"m",A).call(this))}))},A=function(){return t.__awaiter(this,void 0,void 0,(function*(){const t=n.getContentUrl({projectId:this.projectId,filename:L.CONFIG_FILENAME,assetsFolder:L.PREV_VER_ASSETS_FOLDER,baseUrl:this.baseStaticUrl});try{return yield n.fetchContent(t,"json"),!0}catch(t){return!1}}))},P=function(e){t.__classPrivateFieldSet(this,g,Object.assign(Object.assign({},t.__classPrivateFieldGet(this,g,"f")),e.detail),"f")},x=function(){var e;null===(e=t.__classPrivateFieldGet(this,f,"f"))||void 0===e||e.remove(),t.__classPrivateFieldSet(this,f,null,"f")},k=function(e){return t.__awaiter(this,arguments,void 0,(function*({isDebug:e}){e?(t.__classPrivateFieldSet(this,f,document.createElement("descope-debugger"),"f"),Object.assign(t.__classPrivateFieldGet(this,f,"f").style,{position:"fixed",top:"0",right:"0",height:"100vh",width:"100vw",pointerEvents:"none",zIndex:99999}),yield Promise.resolve().then((function(){return U(require("../debugger-wc.js"))})),document.body.appendChild(t.__classPrivateFieldGet(this,f,"f"))):t.__classPrivateFieldGet(this,l,"m",x).call(this)}))},E=function(e,i){var s;e&&this.debug&&(null===(s=t.__classPrivateFieldGet(this,f,"f"))||void 0===s||s.updateData({title:e,description:i}))},I=function(){this.rootElement.onkeydown=t=>{var e,i,s;const r=!!(null===(e=this.shadowRoot.activeElement)||void 0===e?void 0:e.getAttribute("href")),n=o.ELEMENTS_TO_IGNORE_ENTER_KEY_ON.includes(null!==(s=null===(i=this.shadowRoot.activeElement)||void 0===i?void 0:i.localName)&&void 0!==s?s:"");if("Enter"!==t.key||r||n)return;t.preventDefault();const a=this.rootElement.querySelectorAll("descope-button");if(1===a.length&&"false"!==a[0].getAttribute("auto-submit"))return void a[0].click();const l=Array.from(a).filter((t=>"true"===t.getAttribute("auto-submit")));if(1===l.length)return void l[0].click();const u=Array.from(a).filter((t=>"button"===t.getAttribute("data-type")));if(1===u.length)"false"!==u[0].getAttribute("auto-submit")&&u[0].click();else if(0===u.length){const t=Array.from(a).filter((t=>"sso"===t.getAttribute("data-type")));1===t.length&&"false"!==t[0].getAttribute("auto-submit")&&t[0].click()}}},q.sdkConfigOverrides={baseHeaders:{"x-descope-sdk-name":"web-component","x-descope-sdk-version":"3.33.0"}},module.exports=q;
|
|
1
|
+
"use strict";var t=require("tslib"),e=require("@descope/sdk-helpers"),i=require("@descope/sdk-mixins/static-resources-mixin"),s=require("@descope/sdk-mixins/theme-mixin"),r=require("@descope/web-js-sdk"),o=require("../constants/index.js"),n=require("../helpers/helpers.js"),a=require("../helpers/state.js");require("@descope/escape-markdown"),require("../helpers/webauthn.js");var l,d,u,c,h,g,f,v,p,_,b,m,w,C,F,A,P,x,k,E,I,G=require("../helpers/flowInputs.js"),y=require("../mixins/formMountMixin.js"),j=require("./initTemplate.js"),L=require("../constants/content.js"),U=require("../constants/general.js");function M(t){return Object.freeze({__proto__:null,default:t})}const S=e.compose(s.themeMixin,i.staticResourcesMixin,y.formMountMixin)(HTMLElement);class O extends S{static get observedAttributes(){return["project-id","flow-id","base-url","tenant","locale","debug","storage-prefix","preview","redirect-url","auto-focus","store-last-authenticated-user","keep-last-authenticated-user-after-logout","validate-on-blur","style-id"]}constructor(e){super(),l.add(this),u.set(this,!1),this.flowStatus="initial",this.loggerWrapper={error:(e,i="")=>{this.logger.error(e,i,new Error),t.__classPrivateFieldGet(this,l,"m",E).call(this,e,i)},warn:(t,e="")=>{this.logger.warn(t,e)},info:(t,e="",i={})=>{this.logger.info(t,e,i)},debug:(t,e="")=>{this.logger.debug(t,e)}},c.set(this,new a),h.set(this,new a),g.set(this,{}),this.getComponentsContext=()=>t.__classPrivateFieldGet(this,g,"f"),this.nextRequestStatus=new a({isLoading:!1}),f.set(this,void 0),v.set(this,{popstate:t.__classPrivateFieldGet(this,l,"m",m).bind(this),componentsContext:t.__classPrivateFieldGet(this,l,"m",P).bind(this)}),p.set(this,void 0),this.getConfig=()=>t.__awaiter(this,void 0,void 0,(function*(){return(yield this.config)||{isMissingConfig:!0}})),t.__classPrivateFieldSet(this,p,e,"f"),t.__classPrivateFieldGet(this,l,"m",_).call(this)}get flowId(){return this.getAttribute("flow-id")}get client(){try{return JSON.parse(this.getAttribute("client"))||{}}catch(t){return{}}}get tenantId(){return this.getAttribute("tenant")||void 0}get redirectUrl(){return this.getAttribute("redirect-url")||void 0}get debug(){return"true"===this.getAttribute("debug")}get locale(){return this.getAttribute("locale")||void 0}get autoFocus(){var t;const e=null!==(t=this.getAttribute("auto-focus"))&&void 0!==t?t:"true";return"skipFirstScreen"===e?e:"true"===e}get validateOnBlur(){return"true"===this.getAttribute("validate-on-blur")}get storeLastAuthenticatedUser(){var t;return"true"===(null!==(t=this.getAttribute("store-last-authenticated-user"))&&void 0!==t?t:"true")}get keepLastAuthenticatedUserAfterLogout(){return"true"===this.getAttribute("keep-last-authenticated-user-after-logout")}get storagePrefix(){return this.getAttribute("storage-prefix")||""}get preview(){return!!this.getAttribute("preview")}get formConfig(){return G.transformFlowInputFormData(this.form)}get form(){return this.getAttribute("form")}get formConfigValues(){return G.extractNestedAttribute(this.formConfig,"value")}get isRestartOnError(){return"true"===this.getAttribute("restart-on-error")}getExecutionContext(){return t.__awaiter(this,void 0,void 0,(function*(){const t=yield this.getConfig();return"executionContext"in t?t.executionContext:void 0}))}getProjectConfig(){return t.__awaiter(this,void 0,void 0,(function*(){const t=yield this.getConfig();return"projectConfig"in t?t.projectConfig:void 0}))}getFlowConfig(){return t.__awaiter(this,void 0,void 0,(function*(){var t,e;const i=yield this.getProjectConfig(),s=(null===(t=null==i?void 0:i.flows)||void 0===t?void 0:t[this.flowId])||{};return null!==(e=s.version)&&void 0!==e||(s.version=0),s}))}getTargetLocales(){return t.__awaiter(this,void 0,void 0,(function*(){const t=yield this.getFlowConfig();return((null==t?void 0:t.targetLocales)||[]).map((t=>t.toLowerCase()))}))}getComponentsVersion(){return t.__awaiter(this,void 0,void 0,(function*(){var t;const e=yield this.getConfig(),i="projectConfig"in e?null===(t=e.projectConfig)||void 0===t?void 0:t.componentsVersion:{};return i||(this.logger.error("Did not get components version, using latest version"),"latest")}))}init(){const e=Object.create(null,{init:{get:()=>super.init}});return t.__awaiter(this,void 0,void 0,(function*(){var i;if(this.flowStatus="loading",["ready","error","success"].forEach((t=>this.addEventListener(t,(()=>{this.flowStatus=t})))),yield null===(i=e.init)||void 0===i?void 0:i.call(this),t.__classPrivateFieldGet(this,h,"f").subscribe(t.__classPrivateFieldGet(this,l,"m",k).bind(this)),t.__classPrivateFieldGet(this,h,"f").update({isDebug:this.debug}),t.__classPrivateFieldGet(this,l,"m",b).call(this),yield t.__classPrivateFieldGet(this,l,"m",F).call(this))return void this.loggerWrapper.error("This SDK version does not support your flows version","Make sure to upgrade your flows to the latest version or use an older SDK version");const s=yield this.getConfig();if("isMissingConfig"in s&&s.isMissingConfig)return void this.loggerWrapper.error("Cannot get config file","Make sure that your projectId & flowId are correct");t.__classPrivateFieldGet(this,l,"m",I).call(this);const{executionId:r,stepId:o,token:a,code:d,exchangeError:g,redirectAuthCallbackUrl:f,redirectAuthBackupCallbackUri:p,redirectAuthCodeChallenge:_,redirectAuthInitiator:m,ssoQueryParams:w}=n.handleUrlParams(this.flowId,this.loggerWrapper);window.addEventListener("popstate",t.__classPrivateFieldGet(this,v,"f").popstate),window.addEventListener("components-context",t.__classPrivateFieldGet(this,v,"f").componentsContext),t.__classPrivateFieldGet(this,c,"f").subscribe(t.__classPrivateFieldGet(this,l,"m",C).bind(this)),t.__classPrivateFieldGet(this,c,"f").update(Object.assign({projectId:this.projectId,flowId:this.flowId,baseUrl:this.baseUrl,tenant:this.tenantId,redirectUrl:this.redirectUrl,locale:this.locale,stepId:o,executionId:r,token:a,code:d,exchangeError:g,redirectAuthCallbackUrl:f,redirectAuthBackupCallbackUri:p,redirectAuthCodeChallenge:_,redirectAuthInitiator:m},w)),t.__classPrivateFieldSet(this,u,!0,"f")}))}disconnectedCallback(){t.__classPrivateFieldGet(this,c,"f").unsubscribeAll(),t.__classPrivateFieldGet(this,h,"f").unsubscribeAll(),t.__classPrivateFieldGet(this,l,"m",x).call(this),window.removeEventListener("popstate",t.__classPrivateFieldGet(this,v,"f").popstate),window.removeEventListener("components-context",t.__classPrivateFieldGet(this,v,"f").componentsContext)}attributeChangedCallback(e,i,s){if(this.shadowRoot.isConnected&&t.__classPrivateFieldGet(this,u,"f")&&i!==s&&d.observedAttributes.includes(e)){t.__classPrivateFieldGet(this,l,"m",b).call(this);const r=null===i;t.__classPrivateFieldGet(this,c,"f").update((({stepId:t,executionId:i})=>{let o=t,a=i;return r||(a=null,o=null,n.clearRunIdsFromUrl()),{[n.camelCase(e)]:s,stepId:o,executionId:a}})),t.__classPrivateFieldGet(this,h,"f").update({isDebug:this.debug})}}}d=O,u=new WeakMap,c=new WeakMap,h=new WeakMap,g=new WeakMap,f=new WeakMap,v=new WeakMap,p=new WeakMap,l=new WeakSet,_=function(){this.shadowRoot.appendChild(j.content.cloneNode(!0)),this.slotElement=document.createElement("slot"),this.slotElement.classList.add("hidden"),this.rootElement.appendChild(this.slotElement)},b=function(){const t=["base-url","tenant","locale","debug","redirect-url","auto-focus","store-last-authenticated-user","keep-last-authenticated-user-after-logout","preview","storage-prefix","form","client","validate-on-blur","style-id"];d.observedAttributes.forEach((e=>{if(!t.includes(e)&&!this[n.camelCase(e)])throw Error(`${e} cannot be empty`)}))},m=function(){const{stepId:e,executionId:i}=n.getRunIdsFromUrl(this.flowId);t.__classPrivateFieldGet(this,c,"f").update({stepId:e,executionId:i})},w=function(e,i){this.sdk=r(Object.assign(Object.assign({persistTokens:!0,preview:this.preview,storagePrefix:this.storagePrefix,storeLastAuthenticatedUser:this.storeLastAuthenticatedUser,keepLastAuthenticatedUserAfterLogout:this.keepLastAuthenticatedUserAfterLogout},d.sdkConfigOverrides),{projectId:e,baseUrl:i})),["start","next"].forEach((e=>{const i=this.sdk.flow[e];this.sdk.flow[e]=(...e)=>t.__awaiter(this,void 0,void 0,(function*(){this.nextRequestStatus.update({isLoading:!0});try{return yield i(...e)}catch(t){return{error:{errorCode:U.FETCH_EXCEPTION_ERROR_CODE,errorDescription:t.toString()}}}finally{this.nextRequestStatus.update({isLoading:!1})}}))}))},C=function(e,i,s){return t.__awaiter(this,void 0,void 0,(function*(){const{projectId:i,baseUrl:r}=e;if(s("projectId")||s("baseUrl")){if(!i)return;t.__classPrivateFieldGet(this,l,"m",w).call(this,i,r)}t.__classPrivateFieldGet(this,p,"f").call(this,e)}))},F=function(){return t.__awaiter(this,void 0,void 0,(function*(){const e=yield this.getConfig();return"isMissingConfig"in e&&e.isMissingConfig&&(yield t.__classPrivateFieldGet(this,l,"m",A).call(this))}))},A=function(){return t.__awaiter(this,void 0,void 0,(function*(){const t=n.getContentUrl({projectId:this.projectId,filename:L.CONFIG_FILENAME,assetsFolder:L.PREV_VER_ASSETS_FOLDER,baseUrl:this.baseStaticUrl});try{return yield n.fetchContent(t,"json"),!0}catch(t){return!1}}))},P=function(e){t.__classPrivateFieldSet(this,g,Object.assign(Object.assign({},t.__classPrivateFieldGet(this,g,"f")),e.detail),"f")},x=function(){var e;null===(e=t.__classPrivateFieldGet(this,f,"f"))||void 0===e||e.remove(),t.__classPrivateFieldSet(this,f,null,"f")},k=function(e){return t.__awaiter(this,arguments,void 0,(function*({isDebug:e}){e?(t.__classPrivateFieldSet(this,f,document.createElement("descope-debugger"),"f"),Object.assign(t.__classPrivateFieldGet(this,f,"f").style,{position:"fixed",top:"0",right:"0",height:"100vh",width:"100vw",pointerEvents:"none",zIndex:99999}),yield Promise.resolve().then((function(){return M(require("../debugger-wc.js"))})),document.body.appendChild(t.__classPrivateFieldGet(this,f,"f"))):t.__classPrivateFieldGet(this,l,"m",x).call(this)}))},E=function(e,i){var s;e&&this.debug&&(null===(s=t.__classPrivateFieldGet(this,f,"f"))||void 0===s||s.updateData({title:e,description:i}))},I=function(){this.rootElement.onkeydown=t=>{var e,i,s;const r=!!(null===(e=this.shadowRoot.activeElement)||void 0===e?void 0:e.getAttribute("href")),n=o.ELEMENTS_TO_IGNORE_ENTER_KEY_ON.includes(null!==(s=null===(i=this.shadowRoot.activeElement)||void 0===i?void 0:i.localName)&&void 0!==s?s:"");if("Enter"!==t.key||r||n)return;t.preventDefault();const a=this.rootElement.querySelectorAll("descope-button");if(1===a.length&&"false"!==a[0].getAttribute("auto-submit"))return void a[0].click();const l=Array.from(a).filter((t=>"true"===t.getAttribute("auto-submit")));if(1===l.length)return void l[0].click();const d=Array.from(a).filter((t=>"button"===t.getAttribute("data-type")));if(1===d.length)"false"!==d[0].getAttribute("auto-submit")&&d[0].click();else if(0===d.length){const t=Array.from(a).filter((t=>"sso"===t.getAttribute("data-type")));1===t.length&&"false"!==t[0].getAttribute("auto-submit")&&t[0].click()}}},O.sdkConfigOverrides={baseHeaders:{"x-descope-sdk-name":"web-component","x-descope-sdk-version":"3.34.0"}},module.exports=O;
|
|
2
|
+
//# sourceMappingURL=BaseDescopeWc.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"BaseDescopeWc.js","sources":["../../../src/lib/descope-wc/BaseDescopeWc.ts"],"sourcesContent":["import { compose } from '@descope/sdk-helpers';\n// eslint-disable-next-line import/no-duplicates\nimport { staticResourcesMixin } from '@descope/sdk-mixins/static-resources-mixin';\n// eslint-disable-next-line import/no-duplicates\nimport { themeMixin } from '@descope/sdk-mixins/theme-mixin';\nimport createSdk from '@descope/web-js-sdk';\nimport {\n CONFIG_FILENAME,\n ELEMENTS_TO_IGNORE_ENTER_KEY_ON,\n FETCH_EXCEPTION_ERROR_CODE,\n PREV_VER_ASSETS_FOLDER,\n} from '../constants';\nimport {\n camelCase,\n clearRunIdsFromUrl,\n fetchContent,\n getContentUrl,\n getRunIdsFromUrl,\n handleUrlParams,\n State,\n} from '../helpers';\nimport {\n extractNestedAttribute,\n transformFlowInputFormData,\n} from '../helpers/flowInputs';\nimport { IsChanged } from '../helpers/state';\nimport { formMountMixin } from '../mixins';\nimport {\n AutoFocusOptions,\n DebuggerMessage,\n DebugState,\n DescopeUI,\n FlowConfig,\n FlowState,\n FlowStateUpdateFn,\n FlowStatus,\n ProjectConfiguration,\n SdkConfig,\n} from '../types';\nimport initTemplate from './initTemplate';\n\n// this is replaced in build time\ndeclare const BUILD_VERSION: string;\n\nconst BaseClass = compose(\n themeMixin,\n staticResourcesMixin,\n formMountMixin,\n)(HTMLElement);\n\n// this base class is responsible for WC initialization\nclass BaseDescopeWc extends BaseClass {\n static get observedAttributes() {\n return [\n 'project-id',\n 'flow-id',\n 'base-url',\n 'tenant',\n 'locale',\n 'debug',\n 'storage-prefix',\n 'preview',\n 'redirect-url',\n 'auto-focus',\n 'store-last-authenticated-user',\n 'keep-last-authenticated-user-after-logout',\n 'validate-on-blur',\n 'style-id',\n ];\n }\n\n // this is a way for extending the sdk config from outside\n static sdkConfigOverrides: Partial<SdkConfig> = {\n baseHeaders: {\n 'x-descope-sdk-name': 'web-component',\n 'x-descope-sdk-version': BUILD_VERSION,\n },\n };\n\n #init = false;\n\n flowStatus: FlowStatus = 'initial';\n\n loggerWrapper = {\n error: (message: string, description = '') => {\n this.logger.error(message, description, new Error());\n this.#updateDebuggerMessages(message, description);\n },\n warn: (message: string, description = '') => {\n this.logger.warn(message, description);\n },\n info: (message: string, description = '', state: any = {}) => {\n this.logger.info(message, description, state);\n },\n debug: (message: string, description = '') => {\n this.logger.debug(message, description);\n },\n };\n\n #flowState = new State<FlowState>();\n\n #debugState = new State<DebugState>();\n\n #componentsContext = {};\n\n getComponentsContext = () => this.#componentsContext;\n\n nextRequestStatus = new State<{ isLoading: boolean }>({ isLoading: false });\n\n rootElement: HTMLDivElement;\n\n contentRootElement: HTMLDivElement;\n\n slotElement: HTMLSlotElement;\n\n #debuggerEle: HTMLElement & {\n updateData: (data: DebuggerMessage | DebuggerMessage[]) => void;\n };\n\n #eventsCbRefs = {\n popstate: this.#syncStateIdFromUrl.bind(this),\n componentsContext: this.#handleComponentsContext.bind(this),\n };\n\n sdk: ReturnType<typeof createSdk>;\n\n #updateExecState: FlowStateUpdateFn;\n\n descopeUI: Promise<DescopeUI>;\n\n constructor(updateExecState: FlowStateUpdateFn) {\n super();\n this.#updateExecState = updateExecState;\n\n this.#initShadowDom();\n }\n\n #initShadowDom() {\n this.shadowRoot.appendChild(initTemplate.content.cloneNode(true));\n this.slotElement = document.createElement('slot');\n this.slotElement.classList.add('hidden');\n this.rootElement.appendChild(this.slotElement);\n }\n\n get flowId() {\n return this.getAttribute('flow-id');\n }\n\n get client() {\n try {\n return (JSON.parse(this.getAttribute('client')) || {}) as Record<\n string,\n any\n >;\n } catch (e) {\n return {};\n }\n }\n\n get tenantId() {\n return this.getAttribute('tenant') || undefined;\n }\n\n get redirectUrl() {\n return this.getAttribute('redirect-url') || undefined;\n }\n\n get debug() {\n return this.getAttribute('debug') === 'true';\n }\n\n get locale() {\n return this.getAttribute('locale') || undefined;\n }\n\n get autoFocus(): AutoFocusOptions {\n const res = this.getAttribute('auto-focus') ?? 'true';\n if (res === 'skipFirstScreen') {\n return res;\n }\n return res === 'true';\n }\n\n get validateOnBlur() {\n return this.getAttribute('validate-on-blur') === 'true';\n }\n\n get storeLastAuthenticatedUser() {\n const res = this.getAttribute('store-last-authenticated-user') ?? 'true';\n return res === 'true';\n }\n\n get keepLastAuthenticatedUserAfterLogout() {\n const res = this.getAttribute('keep-last-authenticated-user-after-logout');\n return res === 'true';\n }\n\n get storagePrefix() {\n return this.getAttribute('storage-prefix') || '';\n }\n\n get preview() {\n return !!this.getAttribute('preview');\n }\n\n get formConfig() {\n return transformFlowInputFormData(this.form);\n }\n\n get form() {\n return this.getAttribute('form');\n }\n\n get formConfigValues() {\n return extractNestedAttribute(this.formConfig, 'value');\n }\n\n #validateAttrs() {\n const optionalAttributes = [\n 'base-url',\n 'tenant',\n 'locale',\n 'debug',\n 'redirect-url',\n 'auto-focus',\n 'store-last-authenticated-user',\n 'keep-last-authenticated-user-after-logout',\n 'preview',\n 'storage-prefix',\n 'form',\n 'client',\n 'validate-on-blur',\n 'style-id',\n ];\n\n BaseDescopeWc.observedAttributes.forEach((attr: string) => {\n if (!optionalAttributes.includes(attr) && !this[camelCase(attr)])\n throw Error(`${attr} cannot be empty`);\n });\n }\n\n #syncStateIdFromUrl() {\n const { stepId, executionId } = getRunIdsFromUrl(this.flowId);\n this.#flowState.update({ stepId, executionId });\n }\n\n #createSdk(projectId: string, baseUrl: string) {\n this.sdk = createSdk({\n // Use persist tokens options in order to add existing tokens in outgoing requests (if they exists)\n persistTokens: true,\n preview: this.preview,\n storagePrefix: this.storagePrefix,\n storeLastAuthenticatedUser: this.storeLastAuthenticatedUser,\n keepLastAuthenticatedUserAfterLogout:\n this.keepLastAuthenticatedUserAfterLogout,\n ...BaseDescopeWc.sdkConfigOverrides,\n projectId,\n baseUrl,\n });\n\n // we are wrapping the next & start function so we can indicate the request status\n ['start', 'next'].forEach((key) => {\n const origFn = this.sdk.flow[key];\n\n this.sdk.flow[key] = async (...args: Parameters<typeof origFn>) => {\n this.nextRequestStatus.update({ isLoading: true });\n try {\n const resp = await origFn(...args);\n return resp;\n } catch (e) {\n // return a generic error object in case of an error\n return {\n error: {\n errorCode: FETCH_EXCEPTION_ERROR_CODE,\n errorDescription: e.toString(),\n },\n };\n } finally {\n this.nextRequestStatus.update({ isLoading: false });\n }\n };\n });\n }\n\n async #onFlowChange(\n currentState: FlowState,\n _prevState: FlowState,\n isChanged: IsChanged<FlowState>,\n ) {\n const { projectId, baseUrl } = currentState;\n\n const shouldCreateSdkInstance =\n isChanged('projectId') || isChanged('baseUrl');\n\n if (shouldCreateSdkInstance) {\n if (!projectId) return;\n // Initialize the sdk when got a new project id\n this.#createSdk(projectId, baseUrl);\n }\n\n // update runtime state\n this.#updateExecState(currentState);\n }\n\n async #getIsFlowsVersionMismatch() {\n const config = await this.getConfig();\n\n return (\n 'isMissingConfig' in config &&\n config.isMissingConfig &&\n (await this.#isPrevVerConfig())\n );\n }\n\n // we are not using fetchStaticResource here\n // because we do not want to use the fallbacks mechanism\n async #isPrevVerConfig() {\n const prevVerConfigUrl = getContentUrl({\n projectId: this.projectId,\n filename: CONFIG_FILENAME,\n assetsFolder: PREV_VER_ASSETS_FOLDER,\n baseUrl: this.baseStaticUrl,\n });\n try {\n await fetchContent(prevVerConfigUrl, 'json');\n return true;\n } catch (e) {\n return false;\n }\n }\n\n getConfig = async () => (await this.config) || { isMissingConfig: true };\n\n #handleComponentsContext(e: CustomEvent) {\n this.#componentsContext = { ...this.#componentsContext, ...e.detail };\n }\n\n get isRestartOnError() {\n return this.getAttribute('restart-on-error') === 'true';\n }\n\n async getExecutionContext() {\n const config = await this.getConfig();\n return 'executionContext' in config ? config.executionContext : undefined;\n }\n\n #disableDebugger() {\n this.#debuggerEle?.remove();\n this.#debuggerEle = null;\n }\n\n async #handleDebugMode({ isDebug }) {\n if (isDebug) {\n this.#debuggerEle = document.createElement(\n 'descope-debugger',\n ) as HTMLElement & {\n updateData: (data: DebuggerMessage | DebuggerMessage[]) => void;\n };\n\n Object.assign(this.#debuggerEle.style, {\n position: 'fixed',\n top: '0',\n right: '0',\n height: '100vh',\n width: '100vw',\n pointerEvents: 'none',\n zIndex: 99999,\n });\n\n // we are importing the debugger dynamically so we won't load it when it's not needed\n await import('../debugger-wc');\n\n document.body.appendChild(this.#debuggerEle);\n } else {\n this.#disableDebugger();\n }\n }\n\n #updateDebuggerMessages(title: string, description: string) {\n if (title && this.debug)\n this.#debuggerEle?.updateData({ title, description });\n }\n\n async getProjectConfig(): Promise<ProjectConfiguration> {\n const config = await this.getConfig();\n return 'projectConfig' in config ? config.projectConfig : undefined;\n }\n\n async getFlowConfig(): Promise<FlowConfig> {\n const projectConfig = await this.getProjectConfig();\n\n const flowConfig =\n projectConfig?.flows?.[this.flowId] || ({} as FlowConfig);\n flowConfig.version ??= 0;\n return flowConfig;\n }\n\n async getTargetLocales() {\n const flowConfig = await this.getFlowConfig();\n return (flowConfig?.targetLocales || []).map((locale: string) =>\n locale.toLowerCase(),\n );\n }\n\n #handleKeyPress() {\n // we want to simulate submit when the user presses Enter\n this.rootElement.onkeydown = (e) => {\n // we do not want to submit the form if the focus is on a link element\n const isLinkEleFocused =\n !!this.shadowRoot.activeElement?.getAttribute('href');\n const isIgnoredElementFocused = ELEMENTS_TO_IGNORE_ENTER_KEY_ON.includes(\n this.shadowRoot.activeElement?.localName ?? '',\n );\n\n if (e.key !== 'Enter' || isLinkEleFocused || isIgnoredElementFocused)\n return;\n\n e.preventDefault();\n const buttons: NodeListOf<HTMLButtonElement> =\n this.rootElement.querySelectorAll('descope-button');\n\n // in case there is a single button on the page, click on it\n if (\n buttons.length === 1 &&\n buttons[0].getAttribute('auto-submit') !== 'false'\n ) {\n buttons[0].click();\n return;\n }\n\n const autoSubmitButtons = Array.from(buttons).filter(\n (button) => button.getAttribute('auto-submit') === 'true',\n );\n if (autoSubmitButtons.length === 1) {\n autoSubmitButtons[0].click();\n return;\n }\n\n const genericButtons = Array.from(buttons).filter(\n (button) => button.getAttribute('data-type') === 'button',\n );\n\n // in case there is a single \"generic\" button on the page, click on it\n if (genericButtons.length === 1) {\n if (genericButtons[0].getAttribute('auto-submit') !== 'false') {\n genericButtons[0].click();\n }\n } else if (genericButtons.length === 0) {\n const ssoButtons = Array.from(buttons).filter(\n (button) => button.getAttribute('data-type') === 'sso',\n );\n\n // in case there is a single \"sso\" button on the page, click on it\n if (ssoButtons.length === 1) {\n if (ssoButtons[0].getAttribute('auto-submit') !== 'false') {\n ssoButtons[0].click();\n }\n }\n }\n };\n }\n\n async getComponentsVersion() {\n const config = await this.getConfig();\n const version =\n 'projectConfig' in config ? config.projectConfig?.componentsVersion : {};\n\n if (version) return version;\n\n this.logger.error('Did not get components version, using latest version');\n\n return 'latest';\n }\n\n static descopeUI: any;\n\n async init() {\n this.flowStatus = 'loading';\n ['ready', 'error', 'success'].forEach((status: FlowStatus) =>\n this.addEventListener(status, () => {\n this.flowStatus = status;\n }),\n );\n\n await super.init?.();\n this.#debugState.subscribe(this.#handleDebugMode.bind(this));\n this.#debugState.update({ isDebug: this.debug });\n\n this.#validateAttrs();\n\n if (await this.#getIsFlowsVersionMismatch()) {\n this.loggerWrapper.error(\n 'This SDK version does not support your flows version',\n 'Make sure to upgrade your flows to the latest version or use an older SDK version',\n );\n\n return;\n }\n\n const config = await this.getConfig();\n if ('isMissingConfig' in config && config.isMissingConfig) {\n this.loggerWrapper.error(\n 'Cannot get config file',\n 'Make sure that your projectId & flowId are correct',\n );\n\n return;\n }\n\n this.#handleKeyPress();\n\n const {\n executionId,\n stepId,\n token,\n code,\n exchangeError,\n redirectAuthCallbackUrl,\n redirectAuthBackupCallbackUri,\n redirectAuthCodeChallenge,\n redirectAuthInitiator,\n ssoQueryParams,\n } = handleUrlParams(this.flowId, this.loggerWrapper);\n\n // we want to update the state when user clicks on back in the browser\n window.addEventListener('popstate', this.#eventsCbRefs.popstate);\n\n // adding event to listen to events coming from components (e.g. recaptcha risk token) that want to add data to the context\n // this data will be sent to the server on the next request\n window.addEventListener(\n 'components-context',\n this.#eventsCbRefs.componentsContext,\n );\n\n this.#flowState.subscribe(this.#onFlowChange.bind(this));\n\n this.#flowState.update({\n projectId: this.projectId,\n flowId: this.flowId,\n baseUrl: this.baseUrl,\n tenant: this.tenantId,\n redirectUrl: this.redirectUrl,\n locale: this.locale,\n stepId,\n executionId,\n token,\n code,\n exchangeError,\n redirectAuthCallbackUrl,\n redirectAuthBackupCallbackUri,\n redirectAuthCodeChallenge,\n redirectAuthInitiator,\n ...ssoQueryParams,\n });\n\n this.#init = true;\n }\n\n disconnectedCallback() {\n this.#flowState.unsubscribeAll();\n this.#debugState.unsubscribeAll();\n this.#disableDebugger();\n window.removeEventListener('popstate', this.#eventsCbRefs.popstate);\n window.removeEventListener(\n 'components-context',\n this.#eventsCbRefs.componentsContext,\n );\n }\n\n attributeChangedCallback(\n attrName: string,\n oldValue: string,\n newValue: string,\n ) {\n if (!this.shadowRoot.isConnected || !this.#init) return;\n\n if (\n oldValue !== newValue &&\n BaseDescopeWc.observedAttributes.includes(attrName)\n ) {\n this.#validateAttrs();\n\n const isInitialRun = oldValue === null;\n\n this.#flowState.update(({ stepId, executionId }) => {\n let newStepId = stepId;\n let newExecutionId = executionId;\n\n // If not initial run and we got a new project/flow, we want to restart the step\n if (!isInitialRun) {\n newExecutionId = null;\n newStepId = null;\n clearRunIdsFromUrl();\n }\n\n return {\n [camelCase(attrName)]: newValue,\n stepId: newStepId,\n executionId: newExecutionId,\n };\n });\n\n this.#debugState.update({ isDebug: this.debug });\n }\n }\n}\n\nexport default BaseDescopeWc;\n"],"names":["BaseClass","compose","themeMixin","staticResourcesMixin","formMountMixin","HTMLElement","BaseDescopeWc","observedAttributes","constructor","updateExecState","super","_BaseDescopeWc_init","set","this","flowStatus","loggerWrapper","error","message","description","logger","Error","__classPrivateFieldGet","call","warn","info","state","debug","_BaseDescopeWc_flowState","State","_BaseDescopeWc_debugState","_BaseDescopeWc_componentsContext","getComponentsContext","nextRequestStatus","isLoading","_BaseDescopeWc_debuggerEle","_BaseDescopeWc_eventsCbRefs","popstate","_BaseDescopeWc_instances","_BaseDescopeWc_syncStateIdFromUrl","bind","componentsContext","_BaseDescopeWc_handleComponentsContext","_BaseDescopeWc_updateExecState","getConfig","config","isMissingConfig","__classPrivateFieldSet","_BaseDescopeWc_initShadowDom","flowId","getAttribute","client","JSON","parse","e","tenantId","undefined","redirectUrl","locale","autoFocus","res","_b","validateOnBlur","storeLastAuthenticatedUser","keepLastAuthenticatedUserAfterLogout","storagePrefix","preview","formConfig","transformFlowInputFormData","form","formConfigValues","extractNestedAttribute","isRestartOnError","getExecutionContext","executionContext","getProjectConfig","projectConfig","getFlowConfig","flowConfig","flows","_c","version","getTargetLocales","targetLocales","map","toLowerCase","getComponentsVersion","componentsVersion","init","forEach","status","addEventListener","_super","subscribe","_BaseDescopeWc_handleDebugMode","update","isDebug","_BaseDescopeWc_validateAttrs","_BaseDescopeWc_getIsFlowsVersionMismatch","_BaseDescopeWc_handleKeyPress","executionId","stepId","token","code","exchangeError","redirectAuthCallbackUrl","redirectAuthBackupCallbackUri","redirectAuthCodeChallenge","redirectAuthInitiator","ssoQueryParams","handleUrlParams","window","_BaseDescopeWc_onFlowChange","Object","assign","projectId","baseUrl","tenant","disconnectedCallback","unsubscribeAll","_BaseDescopeWc_disableDebugger","removeEventListener","attributeChangedCallback","attrName","oldValue","newValue","shadowRoot","isConnected","_a","includes","isInitialRun","newStepId","newExecutionId","clearRunIdsFromUrl","camelCase","appendChild","initTemplate","content","cloneNode","slotElement","document","createElement","classList","add","rootElement","optionalAttributes","attr","getRunIdsFromUrl","_BaseDescopeWc_createSdk","sdk","createSdk","persistTokens","sdkConfigOverrides","key","origFn","flow","args","__awaiter","errorCode","FETCH_EXCEPTION_ERROR_CODE","errorDescription","toString","currentState","_prevState","isChanged","_BaseDescopeWc_isPrevVerConfig","prevVerConfigUrl","getContentUrl","filename","CONFIG_FILENAME","assetsFolder","PREV_VER_ASSETS_FOLDER","baseStaticUrl","fetchContent","detail","remove","arguments","style","position","top","right","height","width","pointerEvents","zIndex","Promise","resolve","then","_interopNamespaceDefaultOnly","require","body","_BaseDescopeWc_updateDebuggerMessages","title","updateData","onkeydown","isLinkEleFocused","activeElement","isIgnoredElementFocused","ELEMENTS_TO_IGNORE_ENTER_KEY_ON","localName","_d","preventDefault","buttons","querySelectorAll","length","click","autoSubmitButtons","Array","from","filter","button","genericButtons","ssoButtons","baseHeaders"],"mappings":"8pBA4CA,MAAMA,EAAYC,EAAOA,QACvBC,EAAUA,WACVC,EAAoBA,qBACpBC,EAAcA,eAHEH,CAIhBI,aAGF,MAAMC,UAAsBN,EAC1B,6BAAWO,GACT,MAAO,CACL,aACA,UACA,WACA,SACA,SACA,QACA,iBACA,UACA,eACA,aACA,gCACA,4CACA,mBACA,WAEH,CA6DD,WAAAC,CAAYC,GACVC,oBApDFC,EAAAC,IAAAC,MAAQ,GAERA,KAAUC,WAAe,UAEzBD,KAAAE,cAAgB,CACdC,MAAO,CAACC,EAAiBC,EAAc,MACrCL,KAAKM,OAAOH,MAAMC,EAASC,EAAa,IAAIE,OAC5CC,yBAAAR,cA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IAA1BiK,EAAeP,OACqC,UAAlDO,EAAe,GAAGjK,aAAa,gBACjCiK,EAAe,GAAGN,aAEf,GAA8B,IAA1BM,EAAeP,OAAc,CACtC,MAAMQ,EAAaL,MAAMC,KAAKN,GAASO,QACpCC,GAAgD,QAArCA,EAAOhK,aAAa,eAIR,IAAtBkK,EAAWR,QACqC,UAA9CQ,EAAW,GAAGlK,aAAa,gBAC7BkK,EAAW,GAAGP,OAGnB,EAEL,EApYOtM,EAAAiJ,mBAAyC,CAC9C6D,YAAa,CACX,qBAAsB,gBACtB,wBAAyB"}
|
|
@@ -1 +1,2 @@
|
|
|
1
|
-
"use strict";var e,t,i,s,o,r,n,a,l,d,c,h,u,p,g,v,m,f,_,b,w,S,I,E=require("tslib"),C=require("@descope/web-js-sdk"),y=require("../constants/index.js"),O=require("../helpers/helpers.js"),P=require("../helpers/state.js"),R=require("../helpers/templates.js"),T=require("../helpers/webauthn.js"),F=require("../helpers/abTestingKey.js"),A=require("../helpers/conditions.js"),k=require("../helpers/lastAuth.js"),N=require("../types.js"),U=require("./BaseDescopeWc.js"),j=require("./sdkScripts/index.js"),x=require("../constants/general.js");t=new WeakMap,i=new WeakMap,s=new WeakMap,n=new WeakMap,a=new WeakMap,l=new WeakMap,d=new WeakMap,_=new WeakMap,e=new WeakSet,o=function(){document.hidden||setTimeout((()=>{this.flowState.update({deferredRedirect:!1})}),300)},r=function(){return E.__awaiter(this,void 0,void 0,(function*(){this.loggerWrapper.debug("Trying to restart the flow");const e=yield this.getComponentsVersion();this.reset();e===(yield this.getComponentsVersion())?(this.loggerWrapper.debug("Components version was not changed, restarting flow"),this.flowState.update({stepId:null,executionId:null})):this.loggerWrapper.error("Components version mismatch, please reload the page")}))},c=function(e){const t=e.getAttribute("name");if(!["email"].includes(t)){const i=`user-${t}`;e.setAttribute("name",i),e.addEventListener("input",(()=>{e.setAttribute("name",e.value?t:i)}))}},h=function(t,s){return E.__awaiter(this,void 0,void 0,(function*(){var o;null===(o=E.__classPrivateFieldGet(this,i,"f"))||void 0===o||o.abort();const r=t.querySelector('*[autocomplete="webauthn"]');if(r&&(yield T.isConditionalLoginSupported())){const{options:t,transactionId:o}=(yield E.__classPrivateFieldGet(this,d,"f").call(this))||{};if(t&&o){E.__classPrivateFieldGet(this,e,"m",c).call(this,r),E.__classPrivateFieldSet(this,i,new AbortController,"f");const n=yield this.getFlowConfig(),a=yield this.getProjectConfig();this.sdk.webauthn.helpers.conditional(t,E.__classPrivateFieldGet(this,i,"f")).then((e=>E.__awaiter(this,void 0,void 0,(function*(){const t=yield s(r.id,n.version,a.componentsVersion,{transactionId:o,response:e});E.__classPrivateFieldGet(this,l,"f").call(this,t)})))).catch((e=>{"AbortError"!==e.name&&this.loggerWrapper.error("Conditional login failed",e.message)}))}}}))},u=function(){let e=!0;return Array.from(this.shadowRoot.querySelectorAll("*[name]")).reverse().forEach((t=>{var i,s;"slot"!==t.localName&&(null===(i=t.reportValidity)||void 0===i||i.call(t),e&&(e=null===(s=t.checkValidity)||void 0===s?void 0:s.call(t)))})),e},p=function(){return E.__awaiter(this,void 0,void 0,(function*(){const e=Array.from(this.shadowRoot.querySelectorAll(`*[name]:not([${y.DESCOPE_ATTRIBUTE_EXCLUDE_FIELD}])`));return(yield Promise.all(e.map((e=>E.__awaiter(this,void 0,void 0,(function*(){return{name:e.getAttribute("name"),value:e.value}})))))).reduce(((e,t)=>Object.assign(Object.assign({},e),{[t.name]:t.value})),{})}))},g=function(e){const t=this.nextRequestStatus.subscribe((({isLoading:i})=>{i?e.setAttribute("loading","true"):(this.nextRequestStatus.unsubscribe(t),e.removeAttribute("loading"))}))},v=function(e={}){var t,i;const s=O.getFirstNonEmptyValue(e,["externalId","email","phone"]),o=O.getFirstNonEmptyValue(e,["newPassword","password"]);if(s&&o)try{if(!globalThis.PasswordCredential)return;const e=new globalThis.PasswordCredential({id:s,password:o});null===(i=null===(t=null===navigator||void 0===navigator?void 0:navigator.credentials)||void 0===t?void 0:t.store)||void 0===i||i.call(t,e)}catch(e){this.loggerWrapper.error("Could not store credentials",e.message)}},m=function(){O.clearPreviousExternalInputs();this.rootElement.querySelectorAll('[external-input="true"]').forEach((t=>E.__classPrivateFieldGet(this,e,"m",f).call(this,t)))},f=function(e){if(!e)return;e.querySelectorAll("input").forEach((t=>{const i=t.getAttribute("slot"),s=`input-${e.id}-${i}`,o=document.createElement("slot");o.setAttribute("name",s),o.setAttribute("slot",i),e.appendChild(o),t.setAttribute("slot",s),this.appendChild(t)}))},b=function(e){this.rootElement.querySelectorAll('descope-passcode[data-auto-submit="true"]').forEach((t=>{t.addEventListener("input",(()=>{var i;(null===(i=t.checkValidity)||void 0===i?void 0:i.call(t))&&E.__classPrivateFieldGet(this,_,"f").call(this,t,e)}))}))},w=function(t){this.rootElement.querySelectorAll(`descope-button:not([${y.DESCOPE_ATTRIBUTE_EXCLUDE_NEXT_BUTTON}])`).forEach((e=>{e.onclick=()=>{E.__classPrivateFieldGet(this,_,"f").call(this,e,t)}})),E.__classPrivateFieldGet(this,e,"m",b).call(this,t)},S=function(e,t){this.rootElement.addEventListener("transitionend",(()=>{this.rootElement.classList.remove("fade-out"),e()}),{once:!0});const i=t===N.Direction.forward?"slide-forward":"slide-backward";Array.from(this.rootElement.getElementsByClassName("input-container")).forEach(((e,t)=>{e.style["transition-delay"]=40*t+"ms",e.classList.add(i)})),this.rootElement.classList.add("fade-out")},I=function(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t}))},module.exports=class extends U{static set sdkConfigOverrides(e){U.sdkConfigOverrides=e}static get sdkConfigOverrides(){return U.sdkConfigOverrides}constructor(){const c=new P({deferredRedirect:!1});super(c.update.bind(c)),e.add(this),this.stepState=new P({},{updateOnlyOnChange:!1}),t.set(this,void 0),i.set(this,null),s.set(this,{visibilitychange:E.__classPrivateFieldGet(this,e,"m",o).bind(this)}),this.bridgeVersion=1,this.nativeResume=(e,t)=>{var i;const s=JSON.parse(t);if(this.logger.info(`nativeResume received payload of type '${e}'`),"oauthWeb"===e||"sso"===e){let{exchangeCode:e}=s;if(!e){e=null===(i=new URL(s.url).searchParams)||void 0===i?void 0:i.get(y.URL_CODE_PARAM_NAME)}this.nativeComplete({exchangeCode:e,idpInitiated:!0})}else if("magicLink"===e){const e=new URL(s.url),t=e.searchParams.get(y.URL_TOKEN_PARAM_NAME),i=e.searchParams.get(y.URL_RUN_IDS_PARAM_NAME).split("_").pop();E.__classPrivateFieldGet(this,a,"f").call(this),this.flowState.update({token:t,stepId:i,action:void 0})}else this.nativeComplete(s)},n.set(this,((e,i,s,o,r=!1)=>{if(this.flowState.current.action===y.RESPONSE_ACTIONS.poll){this.logger.debug("polling - Scheduling polling request");const a=Date.now(),d=r?500:2e3;E.__classPrivateFieldSet(this,t,setTimeout((()=>E.__awaiter(this,void 0,void 0,(function*(){var t;this.logger.debug("polling - Calling next");const c=this.sdk.flow.next(e,i,y.CUSTOM_INTERACTIONS.polling,s,o,{}),h=document.hidden&&!r&&Date.now()-a>d+500;let u;h&&this.logger.debug("polling - The polling seems to be throttled");try{const e=h?1e3:6e3;u=yield O.timeoutPromise(e,c)}catch(t){return this.logger.warn(`polling - The ${h?"throttled fetch":"fetch"} call timed out or was aborted`),void E.__classPrivateFieldGet(this,n,"f").call(this,e,i,s,o,h)}if((null===(t=null==u?void 0:u.error)||void 0===t?void 0:t.errorCode)===x.FETCH_EXCEPTION_ERROR_CODE)return this.logger.debug("polling - Got a generic error due to exception in fetch call"),void E.__classPrivateFieldGet(this,n,"f").call(this,e,i,s,o);this.logger.debug("polling - Got a response"),(null==u?void 0:u.error)&&this.logger.debug("polling - Response has an error",JSON.stringify(u.error,null,4)),E.__classPrivateFieldGet(this,l,"f").call(this,u),E.__classPrivateFieldGet(this,n,"f").call(this,e,i,s,o)}))),d),"f")}})),a.set(this,(()=>{clearTimeout(E.__classPrivateFieldGet(this,t,"f")),E.__classPrivateFieldSet(this,t,null,"f")})),l.set(this,(t=>{var i,s,o,n,a,l,d,c,h,u,p,g;if(!(null==t?void 0:t.ok)){const d=null===(i=null==t?void 0:t.response)||void 0===i?void 0:i.url,c=`${null===(s=null==t?void 0:t.response)||void 0===s?void 0:s.status} - ${null===(o=null==t?void 0:t.response)||void 0===o?void 0:o.statusText}`;E.__classPrivateFieldGet(this,e,"m",I).call(this,"error",(null==t?void 0:t.error)||{errorCode:x.FETCH_ERROR_RESPONSE_ERROR_CODE,errorDescription:c,errorMessage:d}),this.loggerWrapper.error((null===(n=null==t?void 0:t.error)||void 0===n?void 0:n.errorDescription)||d,(null===(a=null==t?void 0:t.error)||void 0===a?void 0:a.errorMessage)||c);const h=null===(l=null==t?void 0:t.error)||void 0===l?void 0:l.errorCode;return void("E102004"!==h&&"E103205"!==h||!this.isRestartOnError||E.__classPrivateFieldGet(this,e,"m",r).call(this))}null===(c=null===(d=t.data)||void 0===d?void 0:d.runnerLogs)||void 0===c||c.forEach((e=>{const{level:t,title:i,log:s}=e;t&&this.loggerWrapper[t]?this.loggerWrapper[t](i,s):this.loggerWrapper.info(i,s)}));const v=null===(p=null===(u=null===(h=t.data)||void 0===h?void 0:h.screen)||void 0===u?void 0:u.state)||void 0===p?void 0:p.errorText;(null===(g=t.data)||void 0===g?void 0:g.error)?this.loggerWrapper.error(`[${t.data.error.code}]: ${t.data.error.description}`,`${v?`${v} - `:""}${t.data.error.message}`):v&&this.loggerWrapper.error(v);const{status:m,authInfo:f,lastAuth:_}=t.data;if("completed"===m)return this.storeLastAuthenticatedUser&&k.setLastAuth(_),void E.__classPrivateFieldGet(this,e,"m",I).call(this,"success",f);const{executionId:b,stepId:w,stepName:S,action:C,screen:O,redirect:P,openInNewTabUrl:R,webauthn:T,error:F,samlIdpResponse:A,nativeResponse:N}=t.data;C!==y.RESPONSE_ACTIONS.poll?(this.loggerWrapper.info(`Step "${S||`#${w}`}" is ${m}`,"",{screen:O,status:m,stepId:w,stepName:S,action:C,error:F}),this.flowState.update({stepId:w,executionId:b,action:C,redirectTo:null==P?void 0:P.url,openInNewTabUrl:R,screenId:null==O?void 0:O.id,screenState:null==O?void 0:O.state,webauthnTransactionId:null==T?void 0:T.transactionId,webauthnOptions:null==T?void 0:T.options,samlIdpResponseUrl:null==A?void 0:A.url,samlIdpResponseSamlResponse:null==A?void 0:A.samlResponse,samlIdpResponseRelayState:null==A?void 0:A.relayState,nativeResponseType:null==N?void 0:N.type,nativePayload:null==N?void 0:N.payload})):this.flowState.update({action:C})})),d.set(this,O.withMemCache((()=>E.__awaiter(this,void 0,void 0,(function*(){var e;try{const t=yield this.sdk.webauthn.signIn.start("",window.location.origin);return t.ok||this.loggerWrapper.warn("Webauthn start failed",null===(e=null==t?void 0:t.error)||void 0===e?void 0:e.errorMessage),t.data}catch(e){this.loggerWrapper.warn("Webauthn start failed",e.message)}}))))),_.set(this,O.leadingDebounce(((t,i)=>E.__awaiter(this,void 0,void 0,(function*(){var s;if("true"===t.getAttribute("formnovalidate")||E.__classPrivateFieldGet(this,e,"m",u).call(this)){const o=null==t?void 0:t.getAttribute("id");E.__classPrivateFieldGet(this,e,"m",g).call(this,t);const r=yield E.__classPrivateFieldGet(this,e,"m",p).call(this),n=O.getElementDescopeAttributes(t),a=this.getComponentsContext(),d=Object.assign(Object.assign(Object.assign(Object.assign({},a),n),r),{origin:(null===(s=this.nativeOptions)||void 0===s?void 0:s.origin)||window.location.origin}),c=yield this.getFlowConfig(),h=yield this.getProjectConfig(),u=yield i(o,c.version,h.componentsVersion,d);E.__classPrivateFieldGet(this,l,"f").call(this,u),E.__classPrivateFieldGet(this,e,"m",v).call(this,r)}}))))),this.flowState=c}loadSdkScripts(){return E.__awaiter(this,void 0,void 0,(function*(){const e=(yield this.getFlowConfig()).sdkScripts;null==e||e.forEach((e=>E.__awaiter(this,void 0,void 0,(function*(){(yield j.default(e.id))(e.initArgs,{baseUrl:this.baseUrl},(t=>{this.dispatchEvent(new CustomEvent("components-context",{detail:{[j.getScriptResultPath(e.id,e.resultKey)]:t},bubbles:!0,composed:!0}))}))}))))}))}init(){const e=Object.create(null,{init:{get:()=>super.init}});return E.__awaiter(this,void 0,void 0,(function*(){var t,i,o;this.shadowRoot.isConnected&&(null===(t=this.flowState)||void 0===t||t.subscribe(this.onFlowChange.bind(this)),null===(i=this.stepState)||void 0===i||i.subscribe(this.onStepChange.bind(this)),window.addEventListener("visibilitychange",E.__classPrivateFieldGet(this,s,"f").visibilitychange)),yield null===(o=e.init)||void 0===o?void 0:o.call(this)}))}disconnectedCallback(){var e;super.disconnectedCallback(),this.flowState.unsubscribeAll(),this.stepState.unsubscribeAll(),null===(e=E.__classPrivateFieldGet(this,i,"f"))||void 0===e||e.abort(),E.__classPrivateFieldSet(this,i,null,"f"),window.removeEventListener("visibilitychange",E.__classPrivateFieldGet(this,s,"f").visibilitychange)}getHtmlFilenameWithLocale(e,t){return E.__awaiter(this,void 0,void 0,(function*(){let i;const s=O.getUserLocale(e),o=yield this.getTargetLocales();return o.includes(s.locale)?i=`${t}-${s.locale}.html`:o.includes(s.fallback)&&(i=`${t}-${s.fallback}.html`),i}))}getPageContent(e,t){return E.__awaiter(this,void 0,void 0,(function*(){if(t)try{const{body:e}=yield this.fetchStaticResource(t,"text");return e}catch(i){this.loggerWrapper.error(`Failed to fetch flow page from ${t}. Fallback to url ${e}`,i)}try{const{body:t}=yield this.fetchStaticResource(e,"text");return t}catch(e){this.loggerWrapper.error("Failed to fetch flow page",e.message)}return null}))}onFlowChange(t,s,o){return E.__awaiter(this,void 0,void 0,(function*(){var r,a;const{projectId:d,flowId:c,tenant:h,stepId:u,executionId:p,action:g,screenId:v,screenState:m,redirectTo:f,openInNewTabUrl:_,redirectUrl:b,token:w,code:S,exchangeError:P,webauthnTransactionId:R,webauthnOptions:T,redirectAuthCodeChallenge:N,redirectAuthCallbackUrl:U,redirectAuthBackupCallbackUri:j,redirectAuthInitiator:x,locale:G,samlIdpResponseUrl:L,samlIdpResponseSamlResponse:W,samlIdpResponseRelayState:q,nativeResponseType:D,nativePayload:M}=t,$=E.__rest(t,["projectId","flowId","tenant","stepId","executionId","action","screenId","screenState","redirectTo","openInNewTabUrl","redirectUrl","token","code","exchangeError","webauthnTransactionId","webauthnOptions","redirectAuthCodeChallenge","redirectAuthCallbackUrl","redirectAuthBackupCallbackUri","redirectAuthInitiator","locale","samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState","nativeResponseType","nativePayload"]);let V,B;const K=F.getABTestingKey(),H=this.sdk.getLastUserLoginId(),X=yield this.getFlowConfig(),J=yield this.getProjectConfig(),Y=Object.entries(J.flows||{}).reduce(((e,[t,i])=>(e[t]=i.version,e)),{}),z=U&&N?{callbackUrl:U,codeChallenge:N,backupCallbackUri:j}:void 0,Q=this.nativeOptions?{platform:this.nativeOptions.platform,oauthProvider:this.nativeOptions.oauthProvider,oauthRedirect:this.nativeOptions.oauthRedirect,magicLinkRedirect:this.nativeOptions.magicLinkRedirect,ssoRedirect:this.nativeOptions.ssoRedirect}:void 0;if(!p&&(this.loadSdkScripts(),X.fingerprintEnabled&&X.fingerprintKey?yield C.ensureFingerprintIds(X.fingerprintKey,this.baseUrl):C.clearFingerprintData(),X.conditions?({startScreenId:V,conditionInteractionId:B}=A.calculateConditions({loginId:H,code:S,token:w,abTestingKey:K},X.conditions)):X.condition?({startScreenId:V,conditionInteractionId:B}=A.calculateCondition(X.condition,{loginId:H,code:S,token:w,abTestingKey:K})):V=X.startScreenId,!O.showFirstScreenOnExecutionInit(V,$))){const e=yield this.sdk.flow.start(c,Object.assign(Object.assign(Object.assign(Object.assign({tenant:h,redirectAuth:z},$),{client:this.client}),b&&{redirectUrl:b}),{lastAuth:k.getLastAuth(H),abTestingKey:K,locale:O.getUserLocale(G).locale,nativeOptions:Q}),B,"",J.componentsVersion,Y,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),S?{exchangeCode:S,idpInitiated:!0}:{}),$.descopeIdpInitiated&&{idpInitiated:!0}),w?{token:w}:{}),$.oidcLoginHint?{externalId:$.oidcLoginHint}:{}));return E.__classPrivateFieldGet(this,l,"f").call(this,e),void("completed"!==(null===(r=null==e?void 0:e.data)||void 0===r?void 0:r.status)&&this.flowState.update({code:void 0,token:void 0}))}if(p&&(o("token")&&w||o("code")&&S||o("exchangeError")&&P)){const e=yield this.sdk.flow.next(p,u,y.CUSTOM_INTERACTIONS.submit,X.version,J.componentsVersion,{token:w,exchangeCode:S,exchangeError:P});return E.__classPrivateFieldGet(this,l,"f").call(this,e),void this.flowState.update({token:void 0,code:void 0,exchangeError:void 0})}if(g===y.RESPONSE_ACTIONS.loadForm&&["samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState"].some((e=>o(e)))){if(!L||!W)return void this.loggerWrapper.error("Did not get saml idp params data to load");O.injectSamlIdpForm(L,W,q||"",O.submitForm)}if(g===y.RESPONSE_ACTIONS.redirect&&(o("redirectTo")||o("deferredRedirect")))return f?"android"===x&&document.hidden?void this.flowState.update({deferredRedirect:!0}):void window.location.assign(f):void this.loggerWrapper.error("Did not get redirect url");if(g===y.RESPONSE_ACTIONS.webauthnCreate||g===y.RESPONSE_ACTIONS.webauthnGet){if(!R||!T)return void this.loggerWrapper.error("Did not get webauthn transaction id or options");let e,t;null===(a=E.__classPrivateFieldGet(this,i,"f"))||void 0===a||a.abort(),E.__classPrivateFieldSet(this,i,null,"f");try{e=g===y.RESPONSE_ACTIONS.webauthnCreate?yield this.sdk.webauthn.helpers.create(T):yield this.sdk.webauthn.helpers.get(T)}catch(e){"InvalidStateError"===e.name?this.loggerWrapper.warn("WebAuthn operation failed",e.message):"NotAllowedError"!==e.name&&this.loggerWrapper.error(e.message),t=e.name}const s=yield this.sdk.flow.next(p,u,y.CUSTOM_INTERACTIONS.submit,X.version,J.componentsVersion,{transactionId:R,response:e,failure:t});E.__classPrivateFieldGet(this,l,"f").call(this,s)}if(g===y.RESPONSE_ACTIONS.nativeBridge)return this.nativeComplete=e=>E.__awaiter(this,void 0,void 0,(function*(){const t=yield this.sdk.flow.next(p,u,y.CUSTOM_INTERACTIONS.submit,X.version,J.componentsVersion,e);E.__classPrivateFieldGet(this,l,"f").call(this,t)})),void E.__classPrivateFieldGet(this,e,"m",I).call(this,"bridge",{type:D,payload:M});if(E.__classPrivateFieldGet(this,n,"f").call(this,p,u,X.version,J.componentsVersion),!v&&!V)return void this.loggerWrapper.warn("No screen was found to show");const Z=V||v,ee=yield this.getHtmlFilenameWithLocale(G,Z),{oidcLoginHint:te,oidcPrompt:ie,oidcErrorRedirectUri:se,samlIdpUsername:oe}=$,re={direction:O.getAnimationDirection(u,s.stepId),screenState:Object.assign(Object.assign({},m),{form:Object.assign(Object.assign({},this.formConfigValues),null==m?void 0:m.form),lastAuth:{loginId:H,name:this.sdk.getLastUserDisplayName()||H}}),htmlFilename:`${Z}.html`,htmlLocaleFilename:ee,samlIdpUsername:oe,oidcLoginHint:te,oidcPrompt:ie,oidcErrorRedirectUri:se,openInNewTabUrl:_},ne=k.getLastAuth(H);O.showFirstScreenOnExecutionInit(V,$)?re.next=(e,t,i,s)=>this.sdk.flow.start(c,Object.assign(Object.assign(Object.assign(Object.assign({tenant:h,redirectAuth:z},$),{lastAuth:ne,preview:this.preview,abTestingKey:K,client:this.client}),b&&{redirectUrl:b}),{locale:O.getUserLocale(G).locale,nativeOptions:Q}),B,e,i,Y,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),s),S&&{exchangeCode:S,idpInitiated:!0}),$.descopeIdpInitiated&&{idpInitiated:!0}),w&&{token:w})):(o("projectId")||o("baseUrl")||o("executionId")||o("stepId"))&&(re.next=(...e)=>this.sdk.flow.next(p,u,...e)),this.stepState.update(re)}))}onStepChange(t,i){return E.__awaiter(this,void 0,void 0,(function*(){var s,o;const{htmlFilename:r,htmlLocaleFilename:n,direction:a,next:d,screenState:c,openInNewTabUrl:u}=t,p=document.createElement("template");p.innerHTML=yield this.getPageContent(r,n);const g=p.content.cloneNode(!0),v=this.loadDescopeUiComponents(p);this.sdk.webauthn.helpers.isSupported()?yield E.__classPrivateFieldGet(this,e,"m",h).call(this,g,d):R.disableWebauthnButtons(g),!t.samlIdpUsername||(null===(s=c.form)||void 0===s?void 0:s.loginId)||(null===(o=c.form)||void 0===o?void 0:o.email)||(c.form||(c.form={}),c.form.loginId=t.samlIdpUsername,c.form.email=t.samlIdpUsername),R.updateTemplateFromScreenState(g,c,c.componentsConfig,this.formConfig,this.errorTransformer,this.loggerWrapper);const{geo:f}=yield this.getExecutionContext();R.setPhoneAutoDetectDefaultCode(g,f);const _=()=>E.__awaiter(this,void 0,void 0,(function*(){var t,s;yield v;const o=this.shadowRoot.querySelector("div");R.setTOTPVariable(o,null===(t=null==c?void 0:c.totp)||void 0===t?void 0:t.image),R.setNOTPVariable(o,null===(s=null==c?void 0:c.notp)||void 0===s?void 0:s.image),R.setCssVars(o,g,c.cssVars,this.loggerWrapper),this.rootElement.replaceChildren(g);const r=!i.htmlFilename;setTimeout((()=>{E.__classPrivateFieldGet(this,e,"m",m).call(this),O.handleAutoFocus(this.rootElement,this.autoFocus,r),this.validateOnBlur&&O.handleReportValidityOnBlur(this.rootElement),R.updateScreenFromScreenState(this.rootElement,c)})),E.__classPrivateFieldGet(this,e,"m",w).call(this,d),r&&E.__classPrivateFieldGet(this,e,"m",I).call(this,"ready",{}),E.__classPrivateFieldGet(this,e,"m",I).call(this,"page-updated",{});if(this.rootElement.querySelector(`[${y.ELEMENT_TYPE_ATTRIBUTE}="polling"]`)){const e=yield this.getFlowConfig(),t=yield this.getProjectConfig(),i=yield d(y.CUSTOM_INTERACTIONS.polling,e.version,t.componentsVersion,{});E.__classPrivateFieldGet(this,l,"f").call(this,i)}u&&!i.openInNewTabUrl&&window.open(u,"_blank")}));a?E.__classPrivateFieldGet(this,e,"m",S).call(this,_,a):_()}))}};
|
|
1
|
+
"use strict";var e,t,i,s,n,o,r,a,l,d,c,h,u,p,v,g,m,f,_,b,w,S,I,E,C,R,y=require("tslib"),O=require("@descope/web-js-sdk"),P=require("../constants/index.js"),F=require("../helpers/helpers.js"),T=require("../helpers/state.js"),A=require("../helpers/templates.js"),N=require("../helpers/webauthn.js"),k=require("../helpers/abTestingKey.js"),U=require("../helpers/conditions.js"),j=require("../helpers/lastAuth.js"),G=require("../types.js"),x=require("./BaseDescopeWc.js"),L=require("./sdkScripts/index.js"),W=require("../constants/general.js");t=new WeakMap,i=new WeakMap,s=new WeakMap,a=new WeakMap,l=new WeakMap,d=new WeakMap,c=new WeakMap,h=new WeakMap,S=new WeakMap,e=new WeakSet,n=function(){document.hidden||setTimeout((()=>{this.flowState.update({deferredRedirect:!1})}),300)},o=function(){return y.__awaiter(this,void 0,void 0,(function*(){this.loggerWrapper.debug("Trying to restart the flow");const e=yield this.getComponentsVersion();this.reset();e===(yield this.getComponentsVersion())?(this.loggerWrapper.debug("Components version was not changed, restarting flow"),this.flowState.update({stepId:null,executionId:null})):this.loggerWrapper.error("Components version mismatch, please reload the page")}))},r=function(t){return y.__awaiter(this,void 0,void 0,(function*(){var i;const s=Object.assign(Object.assign({},this.stepState.current),t),{next:n,stepName:o}=s,r=y.__rest(s,["next","stepName"]),l=Boolean(yield null===(i=this.onScreenUpdate)||void 0===i?void 0:i.call(this,o,F.transformStepStateForCustomScreen(r),n,this));if(l){this.loggerWrapper.debug("Rendering a custom screen"),this.contentRootElement.innerHTML="",y.__classPrivateFieldGet(this,e,"m",v).call(this,{isFirstScreen:!this.stepState.current.htmlFilename,stepName:t.stepName}),this.stepState.unsubscribeAll();const i=this.stepState.subscribe((()=>{var e;this.stepState.unsubscribe(i),null===(e=this.stepState)||void 0===e||e.subscribe(this.onStepChange.bind(this))}))}y.__classPrivateFieldGet(this,a,"f").call(this,l),this.flowState.forceUpdate=l}))},u=function(e){const t=e.getAttribute("name");if(!["email"].includes(t)){const i=`user-${t}`;e.setAttribute("name",i),e.addEventListener("input",(()=>{e.setAttribute("name",e.value?t:i)}))}},p=function(t,s){return y.__awaiter(this,void 0,void 0,(function*(){var n;null===(n=y.__classPrivateFieldGet(this,i,"f"))||void 0===n||n.abort();const o=t.querySelector('*[autocomplete="webauthn"]');if(o&&(yield N.isConditionalLoginSupported())){const{options:t,transactionId:n}=(yield y.__classPrivateFieldGet(this,h,"f").call(this))||{};t&&n&&(y.__classPrivateFieldGet(this,e,"m",u).call(this,o),y.__classPrivateFieldSet(this,i,new AbortController,"f"),this.sdk.webauthn.helpers.conditional(t,y.__classPrivateFieldGet(this,i,"f")).then((e=>y.__awaiter(this,void 0,void 0,(function*(){s(o.id,{transactionId:n,response:e})})))).catch((e=>{"AbortError"!==e.name&&this.loggerWrapper.error("Conditional login failed",e.message)})))}}))},v=function({isFirstScreen:t,stepName:i}){t&&y.__classPrivateFieldGet(this,e,"m",R).call(this,"ready",{}),y.__classPrivateFieldGet(this,e,"m",R).call(this,"page-updated",{screenName:i}),y.__classPrivateFieldGet(this,e,"m",R).call(this,"screen-updated",{screenName:i})},g=function(){let e=!0;return Array.from(this.shadowRoot.querySelectorAll("*[name]")).reverse().forEach((t=>{var i,s;"slot"!==t.localName&&(null===(i=t.reportValidity)||void 0===i||i.call(t),e&&(e=null===(s=t.checkValidity)||void 0===s?void 0:s.call(t)))})),e},m=function(){return y.__awaiter(this,void 0,void 0,(function*(){const e=Array.from(this.shadowRoot.querySelectorAll(`*[name]:not([${P.DESCOPE_ATTRIBUTE_EXCLUDE_FIELD}])`));return(yield Promise.all(e.map((e=>y.__awaiter(this,void 0,void 0,(function*(){return{name:e.getAttribute("name"),value:e.value}})))))).reduce(((e,t)=>Object.assign(Object.assign({},e),{[t.name]:t.value})),{})}))},f=function(e){const t=this.nextRequestStatus.subscribe((({isLoading:i})=>{i?e.setAttribute("loading","true"):(this.nextRequestStatus.unsubscribe(t),e.removeAttribute("loading"))}))},_=function(e={}){var t,i;const s=F.getFirstNonEmptyValue(e,["externalId","email","phone"]),n=F.getFirstNonEmptyValue(e,["newPassword","password"]);if(s&&n)try{if(!globalThis.PasswordCredential)return;const e=new globalThis.PasswordCredential({id:s,password:n});null===(i=null===(t=null===navigator||void 0===navigator?void 0:navigator.credentials)||void 0===t?void 0:t.store)||void 0===i||i.call(t,e)}catch(e){this.loggerWrapper.error("Could not store credentials",e.message)}},b=function(){F.clearPreviousExternalInputs();this.contentRootElement.querySelectorAll('[external-input="true"]').forEach((t=>y.__classPrivateFieldGet(this,e,"m",w).call(this,t)))},w=function(e){if(!e)return;e.querySelectorAll("input").forEach((t=>{const i=t.getAttribute("slot"),s=`input-${e.id}-${i}`,n=document.createElement("slot");n.setAttribute("name",s),n.setAttribute("slot",i),e.appendChild(n),t.setAttribute("slot",s),this.appendChild(t)}))},I=function(e){this.contentRootElement.querySelectorAll('descope-passcode[data-auto-submit="true"]').forEach((t=>{t.addEventListener("input",(()=>{var i;(null===(i=t.checkValidity)||void 0===i?void 0:i.call(t))&&y.__classPrivateFieldGet(this,S,"f").call(this,t,e)}))}))},E=function(t){this.contentRootElement.querySelectorAll(`descope-button:not([${P.DESCOPE_ATTRIBUTE_EXCLUDE_NEXT_BUTTON}])`).forEach((e=>{e.onclick=()=>{y.__classPrivateFieldGet(this,S,"f").call(this,e,t)}})),y.__classPrivateFieldGet(this,e,"m",I).call(this,t)},C=function(e,t){this.contentRootElement.addEventListener("transitionend",(()=>{this.contentRootElement.classList.remove("fade-out"),e()}),{once:!0});const i=t===G.Direction.forward?"slide-forward":"slide-backward";Array.from(this.contentRootElement.getElementsByClassName("input-container")).forEach(((e,t)=>{e.style["transition-delay"]=40*t+"ms",e.classList.add(i)})),this.contentRootElement.classList.add("fade-out")},R=function(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t}))},module.exports=class extends x{static set sdkConfigOverrides(e){x.sdkConfigOverrides=e}static get sdkConfigOverrides(){return x.sdkConfigOverrides}constructor(){const r=new T({deferredRedirect:!1});super(r.update.bind(r)),e.add(this),this.stepState=new T({},{forceUpdate:!0}),t.set(this,void 0),i.set(this,null),s.set(this,{visibilitychange:y.__classPrivateFieldGet(this,e,"m",n).bind(this)}),this.bridgeVersion=1,this.nativeResume=(e,t)=>{var i;const s=JSON.parse(t);if(this.logger.info(`nativeResume received payload of type '${e}'`),"oauthWeb"===e||"sso"===e){let{exchangeCode:e}=s;if(!e){e=null===(i=new URL(s.url).searchParams)||void 0===i?void 0:i.get(P.URL_CODE_PARAM_NAME)}this.nativeComplete({exchangeCode:e,idpInitiated:!0})}else if("magicLink"===e){const e=new URL(s.url),t=e.searchParams.get(P.URL_TOKEN_PARAM_NAME),i=e.searchParams.get(P.URL_RUN_IDS_PARAM_NAME).split("_").pop();y.__classPrivateFieldGet(this,d,"f").call(this),this.flowState.update({token:t,stepId:i,action:void 0})}else this.nativeComplete(s)},a.set(this,(e=>{this.contentRootElement.classList.toggle("hidden",e),this.slotElement.classList.toggle("hidden",!e)})),l.set(this,((e,i,s,n,o=!1)=>{if(this.flowState.current.action===P.RESPONSE_ACTIONS.poll){this.logger.debug("polling - Scheduling polling request");const r=Date.now(),a=o?500:2e3;y.__classPrivateFieldSet(this,t,setTimeout((()=>y.__awaiter(this,void 0,void 0,(function*(){var t;this.logger.debug("polling - Calling next");const d=this.sdk.flow.next(e,i,P.CUSTOM_INTERACTIONS.polling,s,n,{}),h=document.hidden&&!o&&Date.now()-r>a+500;let u;h&&this.logger.debug("polling - The polling seems to be throttled");try{const e=h?1e3:6e3;u=yield F.timeoutPromise(e,d)}catch(t){return this.logger.warn(`polling - The ${h?"throttled fetch":"fetch"} call timed out or was aborted`),void y.__classPrivateFieldGet(this,l,"f").call(this,e,i,s,n,h)}if((null===(t=null==u?void 0:u.error)||void 0===t?void 0:t.errorCode)===W.FETCH_EXCEPTION_ERROR_CODE)return this.logger.debug("polling - Got a generic error due to exception in fetch call"),void y.__classPrivateFieldGet(this,l,"f").call(this,e,i,s,n);this.logger.debug("polling - Got a response"),(null==u?void 0:u.error)&&this.logger.debug("polling - Response has an error",JSON.stringify(u.error,null,4)),y.__classPrivateFieldGet(this,c,"f").call(this,u),y.__classPrivateFieldGet(this,l,"f").call(this,e,i,s,n)}))),a),"f")}})),d.set(this,(()=>{clearTimeout(y.__classPrivateFieldGet(this,t,"f")),y.__classPrivateFieldSet(this,t,null,"f")})),c.set(this,(t=>{var i,s,n,r,a,l,d,c,h,u,p,v;if(!(null==t?void 0:t.ok)){const d=null===(i=null==t?void 0:t.response)||void 0===i?void 0:i.url,c=`${null===(s=null==t?void 0:t.response)||void 0===s?void 0:s.status} - ${null===(n=null==t?void 0:t.response)||void 0===n?void 0:n.statusText}`;y.__classPrivateFieldGet(this,e,"m",R).call(this,"error",(null==t?void 0:t.error)||{errorCode:W.FETCH_ERROR_RESPONSE_ERROR_CODE,errorDescription:c,errorMessage:d}),this.loggerWrapper.error((null===(r=null==t?void 0:t.error)||void 0===r?void 0:r.errorDescription)||d,(null===(a=null==t?void 0:t.error)||void 0===a?void 0:a.errorMessage)||c);const h=null===(l=null==t?void 0:t.error)||void 0===l?void 0:l.errorCode;return void("E102004"!==h&&"E103205"!==h||!this.isRestartOnError||y.__classPrivateFieldGet(this,e,"m",o).call(this))}null===(c=null===(d=t.data)||void 0===d?void 0:d.runnerLogs)||void 0===c||c.forEach((e=>{const{level:t,title:i,log:s}=e;t&&this.loggerWrapper[t]?this.loggerWrapper[t](i,s):this.loggerWrapper.info(i,s)}));const g=null===(p=null===(u=null===(h=t.data)||void 0===h?void 0:h.screen)||void 0===u?void 0:u.state)||void 0===p?void 0:p.errorText;(null===(v=t.data)||void 0===v?void 0:v.error)?this.loggerWrapper.error(`[${t.data.error.code}]: ${t.data.error.description}`,`${g?`${g} - `:""}${t.data.error.message}`):g&&this.loggerWrapper.error(g);const{status:m,authInfo:f,lastAuth:_}=t.data;if("completed"===m)return this.storeLastAuthenticatedUser&&j.setLastAuth(_),void y.__classPrivateFieldGet(this,e,"m",R).call(this,"success",f);const{executionId:b,stepId:w,stepName:S,action:I,screen:E,redirect:C,openInNewTabUrl:O,webauthn:F,error:T,samlIdpResponse:A,nativeResponse:N}=t.data;I!==P.RESPONSE_ACTIONS.poll?(this.loggerWrapper.info(`Step "${S||`#${w}`}" is ${m}`,"",{screen:E,status:m,stepId:w,stepName:S,action:I,error:T}),this.flowState.update({stepId:w,stepName:S,executionId:b,action:I,redirectTo:null==C?void 0:C.url,openInNewTabUrl:O,screenId:null==E?void 0:E.id,screenState:null==E?void 0:E.state,webauthnTransactionId:null==F?void 0:F.transactionId,webauthnOptions:null==F?void 0:F.options,samlIdpResponseUrl:null==A?void 0:A.url,samlIdpResponseSamlResponse:null==A?void 0:A.samlResponse,samlIdpResponseRelayState:null==A?void 0:A.relayState,nativeResponseType:null==N?void 0:N.type,nativePayload:null==N?void 0:N.payload})):this.flowState.update({action:I})})),h.set(this,F.withMemCache((()=>y.__awaiter(this,void 0,void 0,(function*(){var e;try{const t=yield this.sdk.webauthn.signIn.start("",window.location.origin);return t.ok||this.loggerWrapper.warn("Webauthn start failed",null===(e=null==t?void 0:t.error)||void 0===e?void 0:e.errorMessage),t.data}catch(e){this.loggerWrapper.warn("Webauthn start failed",e.message)}}))))),S.set(this,F.leadingDebounce(((t,i)=>y.__awaiter(this,void 0,void 0,(function*(){var s;if("true"===t.getAttribute("formnovalidate")||y.__classPrivateFieldGet(this,e,"m",g).call(this)){const n=null==t?void 0:t.getAttribute("id");y.__classPrivateFieldGet(this,e,"m",f).call(this,t);const o=yield y.__classPrivateFieldGet(this,e,"m",m).call(this),r=F.getElementDescopeAttributes(t),a=this.getComponentsContext(),l=Object.assign(Object.assign(Object.assign(Object.assign({},a),r),o),{origin:(null===(s=this.nativeOptions)||void 0===s?void 0:s.origin)||window.location.origin});i(n,l),y.__classPrivateFieldGet(this,e,"m",_).call(this,o)}}))))),this.flowState=r}loadSdkScripts(){return y.__awaiter(this,void 0,void 0,(function*(){const e=(yield this.getFlowConfig()).sdkScripts;null==e||e.forEach((e=>y.__awaiter(this,void 0,void 0,(function*(){(yield L.default(e.id))(e.initArgs,{baseUrl:this.baseUrl},(t=>{this.dispatchEvent(new CustomEvent("components-context",{detail:{[L.getScriptResultPath(e.id,e.resultKey)]:t},bubbles:!0,composed:!0}))}))}))))}))}init(){if(!window.isDescopeBridge)return this._init();this.lazyInit=this._init}_init(){const e=Object.create(null,{init:{get:()=>super.init}});return y.__awaiter(this,void 0,void 0,(function*(){var t,i,n;this.shadowRoot.isConnected&&(null===(t=this.flowState)||void 0===t||t.subscribe(this.onFlowChange.bind(this)),null===(i=this.stepState)||void 0===i||i.subscribe(this.onStepChange.bind(this)),window.addEventListener("visibilitychange",y.__classPrivateFieldGet(this,s,"f").visibilitychange)),yield null===(n=e.init)||void 0===n?void 0:n.call(this)}))}disconnectedCallback(){var e;super.disconnectedCallback(),this.flowState.unsubscribeAll(),this.stepState.unsubscribeAll(),null===(e=y.__classPrivateFieldGet(this,i,"f"))||void 0===e||e.abort(),y.__classPrivateFieldSet(this,i,null,"f"),window.removeEventListener("visibilitychange",y.__classPrivateFieldGet(this,s,"f").visibilitychange)}getHtmlFilenameWithLocale(e,t){return y.__awaiter(this,void 0,void 0,(function*(){let i;const s=F.getUserLocale(e),n=yield this.getTargetLocales();return n.includes(s.locale)?i=`${t}-${s.locale}.html`:n.includes(s.fallback)&&(i=`${t}-${s.fallback}.html`),i}))}getPageContent(e,t){return y.__awaiter(this,void 0,void 0,(function*(){if(t)try{const{body:e}=yield this.fetchStaticResource(t,"text");return e}catch(i){this.loggerWrapper.error(`Failed to fetch flow page from ${t}. Fallback to url ${e}`,i)}try{const{body:t}=yield this.fetchStaticResource(e,"text");return t}catch(e){this.loggerWrapper.error("Failed to fetch flow page",e.message)}return null}))}onFlowChange(t,s,n){return y.__awaiter(this,void 0,void 0,(function*(){var o,a;const{projectId:d,flowId:h,tenant:u,stepId:p,executionId:v,action:g,screenId:m,screenState:f,redirectTo:_,openInNewTabUrl:b,redirectUrl:w,token:S,code:I,exchangeError:E,webauthnTransactionId:C,webauthnOptions:T,redirectAuthCodeChallenge:A,redirectAuthCallbackUrl:N,redirectAuthBackupCallbackUri:G,redirectAuthInitiator:x,locale:L,samlIdpResponseUrl:W,samlIdpResponseSamlResponse:D,samlIdpResponseRelayState:M,nativeResponseType:q,nativePayload:$}=t,V=y.__rest(t,["projectId","flowId","tenant","stepId","executionId","action","screenId","screenState","redirectTo","openInNewTabUrl","redirectUrl","token","code","exchangeError","webauthnTransactionId","webauthnOptions","redirectAuthCodeChallenge","redirectAuthCallbackUrl","redirectAuthBackupCallbackUri","redirectAuthInitiator","locale","samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState","nativeResponseType","nativePayload"]);let B,H,K;const X=k.getABTestingKey(),J=this.sdk.getLastUserLoginId(),z=yield this.getFlowConfig(),Y=yield this.getProjectConfig(),Q=Object.entries(Y.flows||{}).reduce(((e,[t,i])=>(e[t]=i.version,e)),{}),Z=N&&A?{callbackUrl:N,codeChallenge:A,backupCallbackUri:G}:void 0,ee=this.nativeOptions?{platform:this.nativeOptions.platform,oauthProvider:this.nativeOptions.oauthProvider,oauthRedirect:this.nativeOptions.oauthRedirect,magicLinkRedirect:this.nativeOptions.magicLinkRedirect,ssoRedirect:this.nativeOptions.ssoRedirect}:void 0;if(!v&&(this.loadSdkScripts(),z.fingerprintEnabled&&z.fingerprintKey?yield O.ensureFingerprintIds(z.fingerprintKey,this.baseUrl):O.clearFingerprintData(),z.conditions?({startScreenId:B,conditionInteractionId:K,startScreenName:H}=U.calculateConditions({loginId:J,code:I,token:S,abTestingKey:X},z.conditions)):z.condition?({startScreenId:B,conditionInteractionId:K}=U.calculateCondition(z.condition,{loginId:J,code:I,token:S,abTestingKey:X})):(H=z.startScreenName,B=z.startScreenId),!F.showFirstScreenOnExecutionInit(B,V))){const e=yield this.sdk.flow.start(h,Object.assign(Object.assign(Object.assign(Object.assign({tenant:u,redirectAuth:Z},V),{client:this.client}),w&&{redirectUrl:w}),{lastAuth:j.getLastAuth(J),abTestingKey:X,locale:F.getUserLocale(L).locale,nativeOptions:ee}),K,"",Y.componentsVersion,Q,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),I?{exchangeCode:I,idpInitiated:!0}:{}),V.descopeIdpInitiated&&{idpInitiated:!0}),S?{token:S}:{}),V.oidcLoginHint?{externalId:V.oidcLoginHint}:{}));return y.__classPrivateFieldGet(this,c,"f").call(this,e),void("completed"!==(null===(o=null==e?void 0:e.data)||void 0===o?void 0:o.status)&&this.flowState.update({code:void 0,token:void 0}))}if(v&&(n("token")&&S||n("code")&&I||n("exchangeError")&&E)){const e=yield this.sdk.flow.next(v,p,P.CUSTOM_INTERACTIONS.submit,z.version,Y.componentsVersion,{token:S,exchangeCode:I,exchangeError:E});return y.__classPrivateFieldGet(this,c,"f").call(this,e),void this.flowState.update({token:void 0,code:void 0,exchangeError:void 0})}if(g===P.RESPONSE_ACTIONS.loadForm&&["samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState"].some((e=>n(e)))){if(!W||!D)return void this.loggerWrapper.error("Did not get saml idp params data to load");F.injectSamlIdpForm(W,D,M||"",F.submitForm)}if(g===P.RESPONSE_ACTIONS.redirect&&(n("redirectTo")||n("deferredRedirect")))return _?"android"===x&&document.hidden?void this.flowState.update({deferredRedirect:!0}):void window.location.assign(_):void this.loggerWrapper.error("Did not get redirect url");if(g===P.RESPONSE_ACTIONS.webauthnCreate||g===P.RESPONSE_ACTIONS.webauthnGet){if(!C||!T)return void this.loggerWrapper.error("Did not get webauthn transaction id or options");let e,t;null===(a=y.__classPrivateFieldGet(this,i,"f"))||void 0===a||a.abort(),y.__classPrivateFieldSet(this,i,null,"f");try{e=g===P.RESPONSE_ACTIONS.webauthnCreate?yield this.sdk.webauthn.helpers.create(T):yield this.sdk.webauthn.helpers.get(T)}catch(e){"InvalidStateError"===e.name?this.loggerWrapper.warn("WebAuthn operation failed",e.message):"NotAllowedError"!==e.name&&this.loggerWrapper.error(e.message),t=e.name}const s=yield this.sdk.flow.next(v,p,P.CUSTOM_INTERACTIONS.submit,z.version,Y.componentsVersion,{transactionId:C,response:e,failure:t});y.__classPrivateFieldGet(this,c,"f").call(this,s)}if(g===P.RESPONSE_ACTIONS.nativeBridge)return this.nativeComplete=e=>y.__awaiter(this,void 0,void 0,(function*(){const t=yield this.sdk.flow.next(v,p,P.CUSTOM_INTERACTIONS.submit,z.version,Y.componentsVersion,e);y.__classPrivateFieldGet(this,c,"f").call(this,t)})),void y.__classPrivateFieldGet(this,e,"m",R).call(this,"bridge",{type:q,payload:$});if(y.__classPrivateFieldGet(this,l,"f").call(this,v,p,z.version,Y.componentsVersion),!m&&!B)return void this.loggerWrapper.warn("No screen was found to show");const te=B||m,ie=yield this.getHtmlFilenameWithLocale(L,te),{oidcLoginHint:se,oidcPrompt:ne,oidcErrorRedirectUri:oe,samlIdpUsername:re}=V,ae={direction:F.getAnimationDirection(p,s.stepId),screenState:Object.assign(Object.assign({},f),{form:Object.assign(Object.assign({},this.formConfigValues),null==f?void 0:f.form),lastAuth:{loginId:J,name:this.sdk.getLastUserDisplayName()||J}}),htmlFilename:`${te}.html`,htmlLocaleFilename:ie,screenId:te,stepName:t.stepName||H,samlIdpUsername:re,oidcLoginHint:se,oidcPrompt:ne,oidcErrorRedirectUri:oe,openInNewTabUrl:b},le=j.getLastAuth(J);F.showFirstScreenOnExecutionInit(B,V)?ae.next=(e,t)=>y.__awaiter(this,void 0,void 0,(function*(){const i=yield this.sdk.flow.start(h,Object.assign(Object.assign(Object.assign(Object.assign({tenant:u,redirectAuth:Z},V),{lastAuth:le,preview:this.preview,abTestingKey:X,client:this.client}),w&&{redirectUrl:w}),{locale:F.getUserLocale(L).locale,nativeOptions:ee}),K,e,Y.componentsVersion,Q,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),t),I&&{exchangeCode:I,idpInitiated:!0}),V.descopeIdpInitiated&&{idpInitiated:!0}),S&&{token:S}));return y.__classPrivateFieldGet(this,c,"f").call(this,i),i})):(n("projectId")||n("baseUrl")||n("executionId")||n("stepId"))&&(ae.next=(e,t)=>y.__awaiter(this,void 0,void 0,(function*(){const i=yield this.sdk.flow.next(v,p,e,z.version,Y.componentsVersion,t);return y.__classPrivateFieldGet(this,c,"f").call(this,i),i}))),this.loggerWrapper.debug("Going to render screen with id",ae.screenId),yield y.__classPrivateFieldGet(this,e,"m",r).call(this,ae),this.stepState.update(ae)}))}onStepChange(t,i){return y.__awaiter(this,void 0,void 0,(function*(){var s,n;const{htmlFilename:o,htmlLocaleFilename:r,direction:a,next:l,screenState:d,openInNewTabUrl:c}=t;this.loggerWrapper.debug("Rendering a flow screen");const h=document.createElement("template");h.innerHTML=yield this.getPageContent(o,r);const u=h.content.cloneNode(!0),g=this.loadDescopeUiComponents(h);this.sdk.webauthn.helpers.isSupported()?yield y.__classPrivateFieldGet(this,e,"m",p).call(this,u,l):A.disableWebauthnButtons(u),!t.samlIdpUsername||(null===(s=d.form)||void 0===s?void 0:s.loginId)||(null===(n=d.form)||void 0===n?void 0:n.email)||(d.form||(d.form={}),d.form.loginId=t.samlIdpUsername,d.form.email=t.samlIdpUsername),A.updateTemplateFromScreenState(u,d,d.componentsConfig,this.formConfig,this.errorTransformer,this.loggerWrapper);const{geo:m}=yield this.getExecutionContext();A.setPhoneAutoDetectDefaultCode(u,m);const f=()=>y.__awaiter(this,void 0,void 0,(function*(){var s,n;yield g;const o=this.contentRootElement;A.setTOTPVariable(o,null===(s=null==d?void 0:d.totp)||void 0===s?void 0:s.image),A.setNOTPVariable(o,null===(n=null==d?void 0:d.notp)||void 0===n?void 0:n.image),A.setCssVars(o,u,d.cssVars,this.loggerWrapper),o.replaceChildren(u);const r=!i.htmlFilename;setTimeout((()=>{y.__classPrivateFieldGet(this,e,"m",b).call(this),this.validateOnBlur&&F.handleReportValidityOnBlur(o),A.updateScreenFromScreenState(o,d),y.__classPrivateFieldGet(this,e,"m",v).call(this,{isFirstScreen:r,stepName:t.stepName}),F.handleAutoFocus(o,this.autoFocus,r)})),y.__classPrivateFieldGet(this,e,"m",E).call(this,l);o.querySelector(`[${P.ELEMENT_TYPE_ATTRIBUTE}="polling"]`)&&l(P.CUSTOM_INTERACTIONS.polling,{}),c&&!i.openInNewTabUrl&&window.open(c,"_blank")}));a?y.__classPrivateFieldGet(this,e,"m",C).call(this,f,a):f()}))}};
|
|
2
|
+
//# sourceMappingURL=DescopeWc.js.map
|