@descope/web-component 4.4.5 → 4.4.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/descope-wc/BaseDescopeWc.js +1 -1
- package/dist/cjs/mixins/componentConditionsMixin.js +1 -1
- package/dist/cjs/mixins/componentConditionsMixin.js.map +1 -1
- package/dist/esm/descope-wc/BaseDescopeWc.js +1 -1
- package/dist/esm/mixins/componentConditionsMixin.js +1 -1
- package/dist/esm/mixins/componentConditionsMixin.js.map +1 -1
- package/dist/index.js +1 -1
- package/package.json +4 -4
|
@@ -1,2 +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/sdk-mixins/inject-style-mixin"),n=require("@descope/sdk-mixins/telemetry-mixin"),o=require("@descope/web-js-sdk"),a=require("../constants/index.js"),l=require("../helpers/helpers.js"),d=require("../helpers/state.js");require("@descope/escape-markdown"),require("../helpers/webauthn.js");var u,c,h,g,f,p,v,_,m,b,w,k,C,P,x,F,y,A,E,S,G,I,j,M,O,q,U=require("../helpers/storage.js"),L=require("../helpers/flowInputs.js"),R=require("../mixins/formMountMixin.js"),T=require("../mixins/componentConditionsMixin.js"),W=require("../mixins/duplicateFlowWarningMixin.js"),N=require("../mixins/passwordManagerMixin.js"),D=require("../mixins/validationTrackingMixin.js"),K=require("../constants/content.js"),V=require("../constants/general.js");function z(t){return Object.freeze({__proto__:null,default:t})}const H=e.compose(s.themeMixin,i.staticResourcesMixin,R.formMountMixin,T.componentConditionsMixin,W.duplicateFlowWarningMixin,N.passwordManagerMixin,r.injectStyleMixin,n.telemetryMixin,D.validationTrackingMixin)(HTMLElement);class J extends H{static get observedAttributes(){return["project-id","flow-id","base-url","tenant","locale","debug","storage-prefix","preview","redirect-url","auto-focus","store-last-authenticated-user","refresh-cookie-name","keep-last-authenticated-user-after-logout","validate-on-blur","send-session-token","style-id"]}constructor(e){super(),u.add(this),this.sdkVersion="4.4.5",h.set(this,!1),g.set(this,void 0),this.flowStatus="initial",this.loggerWrapper={error:(e,i="")=>{this.logger.error(e,i,new Error),t.__classPrivateFieldGet(this,u,"m",q).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)}},f.set(this,new d),p.set(this,new d),v.set(this,{}),this.getComponentsContext=()=>t.__classPrivateFieldGet(this,v,"f"),this.nextRequestStatus=new d({isLoading:!1}),_.set(this,void 0),m.set(this,{popstate:t.__classPrivateFieldGet(this,u,"m",P).bind(this),componentsContext:t.__classPrivateFieldGet(this,u,"m",S).bind(this)}),b.set(this,void 0),this.getConfig=()=>t.__awaiter(this,void 0,void 0,(function*(){return(yield this.config)||{isMissingConfig:!0}})),G.set(this,void 0),I.set(this,void 0),t.__classPrivateFieldSet(this,b,e,"f"),t.__classPrivateFieldGet(this,u,"m",k).call(this)}get client(){try{return JSON.parse(this.getAttribute("client"))||{}}catch(t){return{}}}get redirectUrl(){return this.getAttribute("redirect-url")||void 0}get debug(){return"true"===this.getAttribute("debug")}get locale(){return this.getAttribute("locale")||void 0}get autoFocus(){var t;const e=null!==(t=this.getAttribute("auto-focus"))&&void 0!==t?t:"true";return"skipFirstScreen"===e?e:"true"===e}get validateOnBlur(){return"true"===this.getAttribute("validate-on-blur")}get storeLastAuthenticatedUser(){var t;return"true"===(null!==(t=this.getAttribute("store-last-authenticated-user"))&&void 0!==t?t:"true")}get refreshCookieName(){return this.getAttribute("refresh-cookie-name")||""}get keepLastAuthenticatedUserAfterLogout(){return"true"===this.getAttribute("keep-last-authenticated-user-after-logout")}get storagePrefix(){return this.getAttribute("storage-prefix")||""}get sendSessionToken(){return"true"===this.getAttribute("send-session-token")}get preview(){return!!this.getAttribute("preview")}get formConfig(){return L.transformFlowInputFormData(this.form)}get form(){return this.getAttribute("form")}get formConfigValues(){return L.extractNestedAttribute(this.formConfig,"value")}get outboundAppId(){return this.getAttribute("outbound-app-id")}get outboundAppScopes(){try{const t=JSON.parse(this.getAttribute("outbound-app-scopes"));return t||null}catch(t){return null}}get popupOrigin(){return this.getAttribute("popup-origin")}get customStorage(){return t.__classPrivateFieldGet(this,g,"f")}set customStorage(e){if(e&&"function"!=typeof e.getItem)throw new Error("Custom storage must have a getItem method");if(e&&"function"!=typeof e.setItem)throw new Error("Custom storage must have a setItem method");if(e&&"function"!=typeof e.removeItem)throw new Error("Custom storage must have a removeItem method");t.__classPrivateFieldSet(this,g,e,"f"),U.setCustomStorage(e)}get lazyStart(){return"true"===this.getAttribute("lazy-start")}start(){var e;null===(e=t.__classPrivateFieldGet(this,I,"f"))||void 0===e||e.call(this),t.__classPrivateFieldSet(this,G,Promise.resolve(),"f")}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()))}))}handleKeyPress(){this.logger.debug("Enable key press handler"),this.rootElement.onkeydown=t=>{var e,i,s;const r=!!(null===(e=this.shadowRoot.activeElement)||void 0===e?void 0:e.getAttribute("href")),n=a.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 o=this.rootElement.querySelectorAll("descope-button");if(1===o.length&&"false"!==o[0].getAttribute("auto-submit"))return void o[0].click();const l=Array.from(o).filter((t=>"true"===t.getAttribute("auto-submit")));if(1===l.length)return void l[0].click();const d=Array.from(o).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(o).filter((t=>"sso"===t.getAttribute("data-type")));1===t.length&&"false"!==t[0].getAttribute("auto-submit")&&t[0].click()}}}disableKeyPressHandler(){this.logger.debug("Disable key press handler"),this.rootElement.onkeydown=null}getComponentsVersion(){return 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,p,"f").subscribe(t.__classPrivateFieldGet(this,u,"m",O).bind(this)),t.__classPrivateFieldGet(this,p,"f").update({isDebug:this.debug}),t.__classPrivateFieldGet(this,u,"m",C).call(this),yield t.__classPrivateFieldGet(this,u,"m",A).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");const{executionId:r,stepId:n,token:o,code:a,isPopup:d,exchangeError:c,redirectAuthCallbackUrl:g,redirectAuthBackupCallbackUri:v,redirectAuthCodeChallenge:_,redirectAuthInitiator:b,ssoQueryParams:w}=l.handleUrlParams(this.flowId,this.loggerWrapper);window.addEventListener("popstate",t.__classPrivateFieldGet(this,m,"f").popstate),window.addEventListener("components-context",t.__classPrivateFieldGet(this,m,"f").componentsContext),t.__classPrivateFieldGet(this,f,"f").subscribe(t.__classPrivateFieldGet(this,u,"m",y).bind(this)),t.__classPrivateFieldGet(this,f,"f").update(Object.assign({projectId:this.projectId,flowId:this.flowId,baseUrl:this.baseUrl,tenant:this.tenantId,redirectUrl:this.redirectUrl,locale:this.locale,stepId:n,executionId:r,token:o,code:a,isPopup:d,exchangeError:c,redirectAuthCallbackUrl:g,redirectAuthBackupCallbackUri:v,redirectAuthCodeChallenge:_,redirectAuthInitiator:b},w)),t.__classPrivateFieldSet(this,h,!0,"f")}))}disconnectedCallback(){var e;t.__classPrivateFieldGet(this,f,"f").unsubscribeAll(),t.__classPrivateFieldGet(this,p,"f").unsubscribeAll(),t.__classPrivateFieldGet(this,u,"m",M).call(this),window.removeEventListener("popstate",t.__classPrivateFieldGet(this,m,"f").popstate),window.removeEventListener("components-context",t.__classPrivateFieldGet(this,m,"f").componentsContext),null===(e=super.disconnectedCallback)||void 0===e||e.call(this)}attributeChangedCallback(e,i,s){var r;if(null===(r=super.attributeChangedCallback)||void 0===r||r.call(this,e,i,s),this.shadowRoot.isConnected&&t.__classPrivateFieldGet(this,h,"f")&&i!==s&&c.observedAttributes.includes(e)){t.__classPrivateFieldGet(this,u,"m",C).call(this);const r=null===i;t.__classPrivateFieldGet(this,f,"f").update((({stepId:t,executionId:i})=>{let n=t,o=i;return r||(o=null,n=null,l.clearRunIdsFromUrl()),{[l.camelCase(e)]:s,stepId:n,executionId:o}})),t.__classPrivateFieldGet(this,p,"f").update({isDebug:this.debug})}}}c=J,h=new WeakMap,g=new WeakMap,f=new WeakMap,p=new WeakMap,v=new WeakMap,_=new WeakMap,m=new WeakMap,b=new WeakMap,G=new WeakMap,I=new WeakMap,u=new WeakSet,w=function(){this.injectStyle("\n :host {\n\t\t\twidth: 100%;\n display: block;\n\t\t}\n\n\t\t#root {\n\t\t\theight: 100%;\n display: flex;\n flex-direction: column;\n\t\t}\n\n #content-root {\n all: initial;\n transition: opacity 200ms ease-in-out;\n }\n\n\t\t#root[data-theme] {\n\t\t\tbackground-color: transparent;\n\t\t}\n\n\t\t.fade-out {\n\t\t\topacity: 0.1!important;\n\t\t}\n\n .hidden {\n display: none;\n }\n ")},k=function(){t.__classPrivateFieldGet(this,u,"m",w).call(this),this.slotElement=document.createElement("slot"),this.slotElement.classList.add("hidden"),this.rootElement.appendChild(this.slotElement)},C=function(){const t=["base-url","tenant","locale","debug","redirect-url","auto-focus","store-last-authenticated-user","refresh-cookie-name","keep-last-authenticated-user-after-logout","preview","storage-prefix","form","client","validate-on-blur","send-session-token","style-id","outbound-app-id","outbound-app-scopes","theme-override"];c.observedAttributes.forEach((e=>{if(!t.includes(e)&&!this[l.camelCase(e)])throw Error(`${e} cannot be empty`)}))},P=function(){const{stepId:e,executionId:i}=l.getRunIdsFromUrl(this.flowId);t.__classPrivateFieldGet(this,f,"f").update({stepId:e,executionId:i})},x=function(e,i){o.createSdk&&"function"==typeof o.createSdk||this.logger.error("SDK was not loaded properly",o.createSdk,JSON.stringify(o.createSdk));const s=Object.assign(Object.assign({persistTokens:!0,preview:this.preview,storagePrefix:this.storagePrefix,storeLastAuthenticatedUser:this.storeLastAuthenticatedUser,keepLastAuthenticatedUserAfterLogout:this.keepLastAuthenticatedUserAfterLogout,refreshCookieName:this.refreshCookieName},c.sdkConfigOverrides),{projectId:e,baseUrl:i});t.__classPrivateFieldGet(this,g,"f")&&(s.customStorage=t.__classPrivateFieldGet(this,g,"f")),this.sdk=o.createSdk(s);const r={start:1,next:7};["start","next"].forEach((e=>{const i=this.sdk.flow[e],s=l.withRetry(i,1e3,3);this.sdk.flow[e]=(...i)=>t.__awaiter(this,void 0,void 0,(function*(){const n=[...i],o=r[e],a=t.__classPrivateFieldGet(this,u,"m",F).call(this,n[o]);void 0!==a&&(n[o]=a);try{return yield s(...n)}catch(t){return this.logger.error(`Error in sdk flow ${e} function`,t),{error:{errorCode:V.FETCH_EXCEPTION_ERROR_CODE,errorDescription:t.toString()}}}}))}));const n=this.sdk.flow.start;this.sdk.flow.start=(...e)=>t.__awaiter(this,void 0,void 0,(function*(){return yield t.__classPrivateFieldGet(this,u,"m",j).call(this),n.apply(this.sdk.flow,e)}))},F=function(t){if(!this.sendSessionToken)return t;const e=null===o.getSessionToken||void 0===o.getSessionToken?void 0:o.getSessionToken(this.storagePrefix);return e?Object.assign(Object.assign({},null!=t?t:{}),{sessionJwt:e}):t},y=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,u,"m",x).call(this,i,r)}t.__classPrivateFieldGet(this,b,"f").call(this,e)}))},A=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,u,"m",E).call(this))}))},E=function(){return t.__awaiter(this,void 0,void 0,(function*(){const t=l.getContentUrl({projectId:this.projectId,filename:K.CONFIG_FILENAME,assetsFolder:K.PREV_VER_ASSETS_FOLDER,baseUrl:this.baseStaticUrl});try{return yield l.fetchContent(t,"json"),!0}catch(t){return!1}}))},S=function(e){t.__classPrivateFieldSet(this,v,Object.assign(Object.assign({},t.__classPrivateFieldGet(this,v,"f")),e.detail),"f")},j=function(){return this.lazyStart?(t.__classPrivateFieldGet(this,G,"f")||t.__classPrivateFieldSet(this,G,new Promise((e=>{t.__classPrivateFieldSet(this,I,e,"f")})),"f"),t.__classPrivateFieldGet(this,G,"f")):Promise.resolve()},M=function(){var e;null===(e=t.__classPrivateFieldGet(this,_,"f"))||void 0===e||e.remove(),t.__classPrivateFieldSet(this,_,null,"f")},O=function(e){return t.__awaiter(this,arguments,void 0,(function*({isDebug:e}){e?(t.__classPrivateFieldSet(this,_,document.createElement("descope-debugger"),"f"),Object.assign(t.__classPrivateFieldGet(this,_,"f").style,{position:"fixed",top:"0",right:"0",height:"100vh",width:"100vw",pointerEvents:"none",zIndex:99999}),yield Promise.resolve().then((function(){return z(require("../debugger-wc.js"))})),document.body.appendChild(t.__classPrivateFieldGet(this,_,"f"))):t.__classPrivateFieldGet(this,u,"m",M).call(this)}))},q=function(e,i){var s;e&&this.debug&&(null===(s=t.__classPrivateFieldGet(this,_,"f"))||void 0===s||s.updateData({title:e,description:i}))},J.sdkConfigOverrides={baseHeaders:{"x-descope-sdk-name":"web-component","x-descope-sdk-version":"4.4.5"}},module.exports=J;
|
|
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/sdk-mixins/inject-style-mixin"),n=require("@descope/sdk-mixins/telemetry-mixin"),o=require("@descope/web-js-sdk"),a=require("../constants/index.js"),l=require("../helpers/helpers.js"),d=require("../helpers/state.js");require("@descope/escape-markdown"),require("../helpers/webauthn.js");var u,c,h,g,f,p,v,_,m,b,w,k,C,P,x,F,y,A,E,S,G,I,j,M,O,q,U=require("../helpers/storage.js"),L=require("../helpers/flowInputs.js"),R=require("../mixins/formMountMixin.js"),T=require("../mixins/componentConditionsMixin.js"),W=require("../mixins/duplicateFlowWarningMixin.js"),N=require("../mixins/passwordManagerMixin.js"),D=require("../mixins/validationTrackingMixin.js"),K=require("../constants/content.js"),V=require("../constants/general.js");function z(t){return Object.freeze({__proto__:null,default:t})}const H=e.compose(s.themeMixin,i.staticResourcesMixin,R.formMountMixin,T.componentConditionsMixin,W.duplicateFlowWarningMixin,N.passwordManagerMixin,r.injectStyleMixin,n.telemetryMixin,D.validationTrackingMixin)(HTMLElement);class J extends H{static get observedAttributes(){return["project-id","flow-id","base-url","tenant","locale","debug","storage-prefix","preview","redirect-url","auto-focus","store-last-authenticated-user","refresh-cookie-name","keep-last-authenticated-user-after-logout","validate-on-blur","send-session-token","style-id"]}constructor(e){super(),u.add(this),this.sdkVersion="4.4.6",h.set(this,!1),g.set(this,void 0),this.flowStatus="initial",this.loggerWrapper={error:(e,i="")=>{this.logger.error(e,i,new Error),t.__classPrivateFieldGet(this,u,"m",q).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)}},f.set(this,new d),p.set(this,new d),v.set(this,{}),this.getComponentsContext=()=>t.__classPrivateFieldGet(this,v,"f"),this.nextRequestStatus=new d({isLoading:!1}),_.set(this,void 0),m.set(this,{popstate:t.__classPrivateFieldGet(this,u,"m",P).bind(this),componentsContext:t.__classPrivateFieldGet(this,u,"m",S).bind(this)}),b.set(this,void 0),this.getConfig=()=>t.__awaiter(this,void 0,void 0,(function*(){return(yield this.config)||{isMissingConfig:!0}})),G.set(this,void 0),I.set(this,void 0),t.__classPrivateFieldSet(this,b,e,"f"),t.__classPrivateFieldGet(this,u,"m",k).call(this)}get client(){try{return JSON.parse(this.getAttribute("client"))||{}}catch(t){return{}}}get redirectUrl(){return this.getAttribute("redirect-url")||void 0}get debug(){return"true"===this.getAttribute("debug")}get locale(){return this.getAttribute("locale")||void 0}get autoFocus(){var t;const e=null!==(t=this.getAttribute("auto-focus"))&&void 0!==t?t:"true";return"skipFirstScreen"===e?e:"true"===e}get validateOnBlur(){return"true"===this.getAttribute("validate-on-blur")}get storeLastAuthenticatedUser(){var t;return"true"===(null!==(t=this.getAttribute("store-last-authenticated-user"))&&void 0!==t?t:"true")}get refreshCookieName(){return this.getAttribute("refresh-cookie-name")||""}get keepLastAuthenticatedUserAfterLogout(){return"true"===this.getAttribute("keep-last-authenticated-user-after-logout")}get storagePrefix(){return this.getAttribute("storage-prefix")||""}get sendSessionToken(){return"true"===this.getAttribute("send-session-token")}get preview(){return!!this.getAttribute("preview")}get formConfig(){return L.transformFlowInputFormData(this.form)}get form(){return this.getAttribute("form")}get formConfigValues(){return L.extractNestedAttribute(this.formConfig,"value")}get outboundAppId(){return this.getAttribute("outbound-app-id")}get outboundAppScopes(){try{const t=JSON.parse(this.getAttribute("outbound-app-scopes"));return t||null}catch(t){return null}}get popupOrigin(){return this.getAttribute("popup-origin")}get customStorage(){return t.__classPrivateFieldGet(this,g,"f")}set customStorage(e){if(e&&"function"!=typeof e.getItem)throw new Error("Custom storage must have a getItem method");if(e&&"function"!=typeof e.setItem)throw new Error("Custom storage must have a setItem method");if(e&&"function"!=typeof e.removeItem)throw new Error("Custom storage must have a removeItem method");t.__classPrivateFieldSet(this,g,e,"f"),U.setCustomStorage(e)}get lazyStart(){return"true"===this.getAttribute("lazy-start")}start(){var e;null===(e=t.__classPrivateFieldGet(this,I,"f"))||void 0===e||e.call(this),t.__classPrivateFieldSet(this,G,Promise.resolve(),"f")}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()))}))}handleKeyPress(){this.logger.debug("Enable key press handler"),this.rootElement.onkeydown=t=>{var e,i,s;const r=!!(null===(e=this.shadowRoot.activeElement)||void 0===e?void 0:e.getAttribute("href")),n=a.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 o=this.rootElement.querySelectorAll("descope-button");if(1===o.length&&"false"!==o[0].getAttribute("auto-submit"))return void o[0].click();const l=Array.from(o).filter((t=>"true"===t.getAttribute("auto-submit")));if(1===l.length)return void l[0].click();const d=Array.from(o).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(o).filter((t=>"sso"===t.getAttribute("data-type")));1===t.length&&"false"!==t[0].getAttribute("auto-submit")&&t[0].click()}}}disableKeyPressHandler(){this.logger.debug("Disable key press handler"),this.rootElement.onkeydown=null}getComponentsVersion(){return 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,p,"f").subscribe(t.__classPrivateFieldGet(this,u,"m",O).bind(this)),t.__classPrivateFieldGet(this,p,"f").update({isDebug:this.debug}),t.__classPrivateFieldGet(this,u,"m",C).call(this),yield t.__classPrivateFieldGet(this,u,"m",A).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");const{executionId:r,stepId:n,token:o,code:a,isPopup:d,exchangeError:c,redirectAuthCallbackUrl:g,redirectAuthBackupCallbackUri:v,redirectAuthCodeChallenge:_,redirectAuthInitiator:b,ssoQueryParams:w}=l.handleUrlParams(this.flowId,this.loggerWrapper);window.addEventListener("popstate",t.__classPrivateFieldGet(this,m,"f").popstate),window.addEventListener("components-context",t.__classPrivateFieldGet(this,m,"f").componentsContext),t.__classPrivateFieldGet(this,f,"f").subscribe(t.__classPrivateFieldGet(this,u,"m",y).bind(this)),t.__classPrivateFieldGet(this,f,"f").update(Object.assign({projectId:this.projectId,flowId:this.flowId,baseUrl:this.baseUrl,tenant:this.tenantId,redirectUrl:this.redirectUrl,locale:this.locale,stepId:n,executionId:r,token:o,code:a,isPopup:d,exchangeError:c,redirectAuthCallbackUrl:g,redirectAuthBackupCallbackUri:v,redirectAuthCodeChallenge:_,redirectAuthInitiator:b},w)),t.__classPrivateFieldSet(this,h,!0,"f")}))}disconnectedCallback(){var e;t.__classPrivateFieldGet(this,f,"f").unsubscribeAll(),t.__classPrivateFieldGet(this,p,"f").unsubscribeAll(),t.__classPrivateFieldGet(this,u,"m",M).call(this),window.removeEventListener("popstate",t.__classPrivateFieldGet(this,m,"f").popstate),window.removeEventListener("components-context",t.__classPrivateFieldGet(this,m,"f").componentsContext),null===(e=super.disconnectedCallback)||void 0===e||e.call(this)}attributeChangedCallback(e,i,s){var r;if(null===(r=super.attributeChangedCallback)||void 0===r||r.call(this,e,i,s),this.shadowRoot.isConnected&&t.__classPrivateFieldGet(this,h,"f")&&i!==s&&c.observedAttributes.includes(e)){t.__classPrivateFieldGet(this,u,"m",C).call(this);const r=null===i;t.__classPrivateFieldGet(this,f,"f").update((({stepId:t,executionId:i})=>{let n=t,o=i;return r||(o=null,n=null,l.clearRunIdsFromUrl()),{[l.camelCase(e)]:s,stepId:n,executionId:o}})),t.__classPrivateFieldGet(this,p,"f").update({isDebug:this.debug})}}}c=J,h=new WeakMap,g=new WeakMap,f=new WeakMap,p=new WeakMap,v=new WeakMap,_=new WeakMap,m=new WeakMap,b=new WeakMap,G=new WeakMap,I=new WeakMap,u=new WeakSet,w=function(){this.injectStyle("\n :host {\n\t\t\twidth: 100%;\n display: block;\n\t\t}\n\n\t\t#root {\n\t\t\theight: 100%;\n display: flex;\n flex-direction: column;\n\t\t}\n\n #content-root {\n all: initial;\n transition: opacity 200ms ease-in-out;\n }\n\n\t\t#root[data-theme] {\n\t\t\tbackground-color: transparent;\n\t\t}\n\n\t\t.fade-out {\n\t\t\topacity: 0.1!important;\n\t\t}\n\n .hidden {\n display: none;\n }\n ")},k=function(){t.__classPrivateFieldGet(this,u,"m",w).call(this),this.slotElement=document.createElement("slot"),this.slotElement.classList.add("hidden"),this.rootElement.appendChild(this.slotElement)},C=function(){const t=["base-url","tenant","locale","debug","redirect-url","auto-focus","store-last-authenticated-user","refresh-cookie-name","keep-last-authenticated-user-after-logout","preview","storage-prefix","form","client","validate-on-blur","send-session-token","style-id","outbound-app-id","outbound-app-scopes","theme-override"];c.observedAttributes.forEach((e=>{if(!t.includes(e)&&!this[l.camelCase(e)])throw Error(`${e} cannot be empty`)}))},P=function(){const{stepId:e,executionId:i}=l.getRunIdsFromUrl(this.flowId);t.__classPrivateFieldGet(this,f,"f").update({stepId:e,executionId:i})},x=function(e,i){o.createSdk&&"function"==typeof o.createSdk||this.logger.error("SDK was not loaded properly",o.createSdk,JSON.stringify(o.createSdk));const s=Object.assign(Object.assign({persistTokens:!0,preview:this.preview,storagePrefix:this.storagePrefix,storeLastAuthenticatedUser:this.storeLastAuthenticatedUser,keepLastAuthenticatedUserAfterLogout:this.keepLastAuthenticatedUserAfterLogout,refreshCookieName:this.refreshCookieName},c.sdkConfigOverrides),{projectId:e,baseUrl:i});t.__classPrivateFieldGet(this,g,"f")&&(s.customStorage=t.__classPrivateFieldGet(this,g,"f")),this.sdk=o.createSdk(s);const r={start:1,next:7};["start","next"].forEach((e=>{const i=this.sdk.flow[e],s=l.withRetry(i,1e3,3);this.sdk.flow[e]=(...i)=>t.__awaiter(this,void 0,void 0,(function*(){const n=[...i],o=r[e],a=t.__classPrivateFieldGet(this,u,"m",F).call(this,n[o]);void 0!==a&&(n[o]=a);try{return yield s(...n)}catch(t){return this.logger.error(`Error in sdk flow ${e} function`,t),{error:{errorCode:V.FETCH_EXCEPTION_ERROR_CODE,errorDescription:t.toString()}}}}))}));const n=this.sdk.flow.start;this.sdk.flow.start=(...e)=>t.__awaiter(this,void 0,void 0,(function*(){return yield t.__classPrivateFieldGet(this,u,"m",j).call(this),n.apply(this.sdk.flow,e)}))},F=function(t){if(!this.sendSessionToken)return t;const e=null===o.getSessionToken||void 0===o.getSessionToken?void 0:o.getSessionToken(this.storagePrefix);return e?Object.assign(Object.assign({},null!=t?t:{}),{sessionJwt:e}):t},y=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,u,"m",x).call(this,i,r)}t.__classPrivateFieldGet(this,b,"f").call(this,e)}))},A=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,u,"m",E).call(this))}))},E=function(){return t.__awaiter(this,void 0,void 0,(function*(){const t=l.getContentUrl({projectId:this.projectId,filename:K.CONFIG_FILENAME,assetsFolder:K.PREV_VER_ASSETS_FOLDER,baseUrl:this.baseStaticUrl});try{return yield l.fetchContent(t,"json"),!0}catch(t){return!1}}))},S=function(e){t.__classPrivateFieldSet(this,v,Object.assign(Object.assign({},t.__classPrivateFieldGet(this,v,"f")),e.detail),"f")},j=function(){return this.lazyStart?(t.__classPrivateFieldGet(this,G,"f")||t.__classPrivateFieldSet(this,G,new Promise((e=>{t.__classPrivateFieldSet(this,I,e,"f")})),"f"),t.__classPrivateFieldGet(this,G,"f")):Promise.resolve()},M=function(){var e;null===(e=t.__classPrivateFieldGet(this,_,"f"))||void 0===e||e.remove(),t.__classPrivateFieldSet(this,_,null,"f")},O=function(e){return t.__awaiter(this,arguments,void 0,(function*({isDebug:e}){e?(t.__classPrivateFieldSet(this,_,document.createElement("descope-debugger"),"f"),Object.assign(t.__classPrivateFieldGet(this,_,"f").style,{position:"fixed",top:"0",right:"0",height:"100vh",width:"100vw",pointerEvents:"none",zIndex:99999}),yield Promise.resolve().then((function(){return z(require("../debugger-wc.js"))})),document.body.appendChild(t.__classPrivateFieldGet(this,_,"f"))):t.__classPrivateFieldGet(this,u,"m",M).call(this)}))},q=function(e,i){var s;e&&this.debug&&(null===(s=t.__classPrivateFieldGet(this,_,"f"))||void 0===s||s.updateData({title:e,description:i}))},J.sdkConfigOverrides={baseHeaders:{"x-descope-sdk-name":"web-component","x-descope-sdk-version":"4.4.6"}},module.exports=J;
|
|
2
2
|
//# sourceMappingURL=BaseDescopeWc.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var e=require("tslib"),t=require("@descope/sdk-helpers"),n=require("@descope/sdk-mixins"),i=require("../helpers/realtime-conditions/config.js"),s=require("../helpers/realtime-conditions/evaluator.js"),o=require("../helpers/realtime-conditions/applier.js"),r=require("../constants/index.js");const l="component-conditions:";function c(e){return e instanceof HTMLInputElement?"checkbox"===e.type?e.checked:e.value:"checked"in e?e.checked:"value"in e?e.value:void 0}function a(e,t){const n=Object.keys(e),i=Object.keys(t);return n.length===i.length&&n.every((n=>e[n]===t[n]))}function u(){return{conditions:[],touchedIds:new Set,snapshot:{},applied:{},serverBaseline:{},debounceTimer:null,paused:!1,unsubscribePauseListener:null,inputHandler:()=>{},root:null}}function d(e,t,n){const i={};return n.forEach((n=>{e[n]?i[n]=e[n]:t[n]&&(i[n]=t[n])})),i}const
|
|
1
|
+
"use strict";var e=require("tslib"),t=require("@descope/sdk-helpers"),n=require("@descope/sdk-mixins"),i=require("../helpers/realtime-conditions/config.js"),s=require("../helpers/realtime-conditions/evaluator.js"),o=require("../helpers/realtime-conditions/applier.js"),r=require("../constants/index.js");const l="component-conditions:";function c(e){return e instanceof HTMLInputElement?"checkbox"===e.type?e.checked:e.value:"checked"in e?e.checked:"value"in e?e.value:void 0}function a(e,t){const n=Object.keys(e),i=Object.keys(t);return n.length===i.length&&n.every((n=>e[n]===t[n]))}function u(){return{conditions:[],touchedIds:new Set,snapshot:{},applied:{},serverBaseline:{},debounceTimer:null,paused:!1,unsubscribePauseListener:null,inputHandler:()=>{},root:null}}function d(e,t,n){const i={};return n.forEach((n=>{e[n]?i[n]=e[n]:t[n]&&(i[n]=t[n])})),i}const h=t.createSingletonMixin((h=>{var p,m,v,f,b,E;const T=t.compose(n.loggerMixin)(h);return E=class extends T{constructor(){super(...arguments),p.add(this),m.set(this,u())}applyComponentsState(e,t){t&&(Object.entries(t).forEach((([e,t])=>{o.COMPONENT_ACTIONS.includes(t)||this.logger.error(`Unknown component action "${t}" for component with id "${e}"`,`Valid actions are ${o.COMPONENT_ACTIONS.map((e=>`"${e}"`)).join(", ")}`)})),o.apply(e,{},t))}initRealtimeConditions(t,n){var r,u,h,f;e.__classPrivateFieldGet(this,p,"m",b).call(this);const E=null!==(r=null==n?void 0:n.realtimeComponentsConditions)&&void 0!==r?r:[];if(!E.length)return void this.logger.debug(`${l} no real-time rules to apply on this screen`);this.logger.info(`${l} found ${E.length} real-time rule(s) for this screen`);const T={};Object.entries(null!==(u=null==n?void 0:n.form)&&void 0!==u?u:{}).forEach((([e,t])=>{T[`form.${e}`]=t})),s.collectReferencedFormKeys(E).forEach((e=>{const n=function(e,t){const n=t.startsWith("form.")?t.slice(5):t;return e.querySelector(`[name="${o.escapeSelector(t)}"]`)||e.querySelector(`[name="${o.escapeSelector(n)}"]`)}(t,e);if(!n)return;const i=c(n);void 0!==i&&(T[e]=i)}));const g=s.collectTouchedComponentIds(E),_={},O={};Object.entries(null!==(h=null==n?void 0:n.componentsState)&&void 0!==h?h:{}).forEach((([e,t])=>{g.has(e)&&(O[e]=t)})),Object.entries(null!==(f=null==n?void 0:n.serverOnlyComponentsState)&&void 0!==f?f:{}).forEach((([e,t])=>{g.has(e)&&(_[e]=t)}));const S={conditions:E,touchedIds:g,snapshot:T,applied:O,serverBaseline:_,debounceTimer:null,paused:!1,unsubscribePauseListener:null,inputHandler:()=>{},root:t},I=d(s.evaluateAll(E,T),_,g);a(O,I)||(S.applied=o.apply(t,O,I)),S.inputHandler=t=>e.__classPrivateFieldGet(this,p,"m",v).call(this,t),i.REALTIME_CONDITION_EVENTS.forEach((e=>{t.addEventListener(e,S.inputHandler,!0)})),this.logger.debug(`${l} listening for "${i.REALTIME_CONDITION_EVENTS.join('" and "')}" events on form fields; ${Object.keys(O).length} component(s) start hidden / disabled / read-only by these rules`);const C=this.nextRequestStatus;if(null==C?void 0:C.subscribe){const e=({isLoading:e})=>{S.paused=e,e&&S.debounceTimer&&(clearTimeout(S.debounceTimer),S.debounceTimer=null)},t=C.subscribe(e);S.unsubscribePauseListener=()=>{var e;null!=t&&(null===(e=C.unsubscribe)||void 0===e||e.call(C,t))}}e.__classPrivateFieldSet(this,m,S,"f")}disconnectedCallback(){var t;null===(t=super.disconnectedCallback)||void 0===t||t.call(this),e.__classPrivateFieldGet(this,p,"m",b).call(this)}},m=new WeakMap,p=new WeakSet,v=function(t){var n,s;const o=e.__classPrivateFieldGet(this,m,"f");if(!o.root||o.paused)return;const l=t.target;if(!l)return;if(null===(n=l.hasAttribute)||void 0===n?void 0:n.call(l,r.DESCOPE_ATTRIBUTE_EXCLUDE_FIELD))return;const a=null===(s=l.getAttribute)||void 0===s?void 0:s.call(l,"name");if(!a)return;const u=function(e){return e.startsWith("form.")?e:`form.${e}`}(a);o.snapshot[u]=c(l),o.debounceTimer&&clearTimeout(o.debounceTimer),o.debounceTimer=setTimeout((()=>{o.debounceTimer=null,e.__classPrivateFieldGet(this,p,"m",f).call(this)}),i.REALTIME_CONDITION_DEBOUNCE_MS)},f=function(){const t=e.__classPrivateFieldGet(this,m,"f");if(!t.root)return;let n;try{n=d(s.evaluateAll(t.conditions,t.snapshot),t.serverBaseline,t.touchedIds)}catch(e){return void this.logger.error(`${l} failed to evaluate real-time rules — keeping the previous state`,null==e?void 0:e.message)}const i=t.applied;a(i,n)||(this.logger.debug(`${l} form changed — updating components: was ${JSON.stringify(i)}, now ${JSON.stringify(n)}`),t.applied=o.apply(t.root,i,n))},b=function(){const t=e.__classPrivateFieldGet(this,m,"f");t.debounceTimer&&clearTimeout(t.debounceTimer),t.unsubscribePauseListener&&t.unsubscribePauseListener(),t.root&&i.REALTIME_CONDITION_EVENTS.forEach((e=>{t.root.removeEventListener(e,t.inputHandler,!0)})),e.__classPrivateFieldSet(this,m,u(),"f")},E}));exports.componentConditionsMixin=h;
|
|
2
2
|
//# sourceMappingURL=componentConditionsMixin.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"componentConditionsMixin.js","sources":["../../../src/lib/mixins/componentConditionsMixin.ts"],"sourcesContent":["/* eslint-disable import/prefer-default-export, no-param-reassign */\nimport { compose, createSingletonMixin } from '@descope/sdk-helpers';\nimport { loggerMixin } from '@descope/sdk-mixins';\nimport {\n REALTIME_CONDITION_DEBOUNCE_MS,\n REALTIME_CONDITION_EVENTS,\n} from '../helpers/realtime-conditions/config';\nimport {\n collectReferencedFormKeys,\n collectTouchedComponentIds,\n evaluateAll,\n FormSnapshot,\n} from '../helpers/realtime-conditions/evaluator';\nimport {\n apply,\n COMPONENT_ACTIONS,\n escapeSelector,\n} from '../helpers/realtime-conditions/applier';\nimport { DESCOPE_ATTRIBUTE_EXCLUDE_FIELD } from '../constants';\nimport type { RealtimeComponentsCondition, ScreenState } from '../types';\n\nconst LOG_PREFIX = 'component-conditions:';\n\n// What the mixin needs from its host: a way to subscribe to loading state\n// so input handling can pause while the next request is in flight. Defined\n// as an interface (not imported) to avoid a circular dependency on BaseDescopeWc.\nexport interface PausableHost {\n nextRequestStatus?: {\n // subscribe returns a token; pass that token to unsubscribe — not the handler.\n subscribe: (cb: (v: { isLoading: boolean }) => void) => string;\n unsubscribe?: (token: string) => void;\n };\n}\n\nexport interface RealtimeRuntime {\n conditions: RealtimeComponentsCondition[];\n // IDs of components that any rule can change\n touchedIds: Set<string>;\n // latest form values on screen\n snapshot: FormSnapshot;\n // what's currently applied on screen for touched components.\n // Compared against on each re-evaluation to know what to change.\n applied: Record<string, string>;\n // What the server told us to apply for these components. Stays fixed for\n // the screen's lifetime so we can fall back to it when a real-time rule\n // stops matching. Without this, a server-set action could disappear when\n // a real-time rule briefly fires on the same component.\n serverBaseline: Record<string, string>;\n debounceTimer: ReturnType<typeof setTimeout> | null;\n // true while paused (during submit, to avoid stale updates)\n paused: boolean;\n unsubscribePauseListener: (() => void) | null;\n // the listener we attach to form events (kept so we can detach)\n inputHandler: (e: Event) => void;\n // the screen root we work against\n root: HTMLElement | null;\n}\n\n// Some inputs already have `name=\"form.x\"`, others use `name=\"x\"`. Always\n// return the `form.x` form so it lines up with what rules reference.\nfunction toFormKey(name: string): string {\n return name.startsWith('form.') ? name : `form.${name}`;\n}\n\n// Try the full `form.x` first (descope components), then `x` (plain inputs).\nfunction findInputForFormKey(\n root: ParentNode,\n formKey: string,\n): Element | null {\n const bare = formKey.startsWith('form.')\n ? formKey.slice('form.'.length)\n : formKey;\n return (\n root.querySelector(`[name=\"${escapeSelector(formKey)}\"]`) ||\n root.querySelector(`[name=\"${escapeSelector(bare)}\"]`)\n );\n}\n\n// Read the current value off a form input. Reads JS properties (not HTML\n// attributes) so we pick up both the component's default and any value\n// carried over from earlier screens.\n//\n// Native <input type=checkbox> needs special handling: `.value` is always\n// \"on\", only `.checked` reflects the real state. Descope boolean components\n// (descope-checkbox, descope-switch-toggle) expose `.checked` on their class.\nfunction readInputValue(el: Element): unknown {\n if (el instanceof HTMLInputElement) {\n return el.type === 'checkbox' ? el.checked : el.value;\n }\n if ('checked' in el) {\n return (el as unknown as { checked: boolean }).checked;\n }\n if ('value' in el) {\n return (el as unknown as { value: unknown }).value;\n }\n return undefined;\n}\n\nfunction shallowEqualStringMap(\n a: Record<string, string>,\n b: Record<string, string>,\n): boolean {\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n if (keysA.length !== keysB.length) return false;\n return keysA.every((k) => a[k] === b[k]);\n}\n\nfunction emptyRuntime(): RealtimeRuntime {\n return {\n conditions: [],\n touchedIds: new Set(),\n snapshot: {},\n applied: {},\n serverBaseline: {},\n debounceTimer: null,\n paused: false,\n unsubscribePauseListener: null,\n inputHandler: () => {},\n root: null,\n };\n}\n\n// For each touched component, pick the real-time action if a rule is firing\n// for it, otherwise fall back to the server's action. Components that no rule\n// touches are not in the result — those were already painted by\n// applyComponentsState.\nfunction effectiveActions(\n realtimeVerdict: Record<string, string>,\n serverBaseline: Record<string, string>,\n touchedIds: Set<string>,\n): Record<string, string> {\n const out: Record<string, string> = {};\n touchedIds.forEach((id) => {\n if (realtimeVerdict[id]) {\n out[id] = realtimeVerdict[id];\n } else if (serverBaseline[id]) {\n out[id] = serverBaseline[id];\n }\n });\n return out;\n}\n\nexport const componentConditionsMixin = createSingletonMixin(\n <T extends CustomElementConstructor>(superclass: T) => {\n // Pull in loggerMixin so `this.logger` is available no matter where\n // this mixin sits in the chain.\n const BaseClass = compose(loggerMixin)(superclass);\n\n return class ComponentConditionsMixin extends BaseClass {\n // One runtime per <descope-wc> element.\n #rtRuntime: RealtimeRuntime = emptyRuntime();\n\n /**\n * Apply the server's hide/disable/read-only actions to the DOM.\n * Logs unknown actions here (runs once per screen) but stays quiet on\n * the keystroke path to avoid log spam.\n */\n applyComponentsState(\n root: ParentNode,\n componentsState: Record<string, string> | undefined,\n ): void {\n if (!componentsState) return;\n Object.entries(componentsState).forEach(([id, action]) => {\n if (!(COMPONENT_ACTIONS as readonly string[]).includes(action)) {\n this.logger.error(\n `Unknown component action \"${action}\" for component with id \"${id}\"`,\n `Valid actions are ${COMPONENT_ACTIONS.map((a) => `\"${a}\"`).join(\n ', ',\n )}`,\n );\n }\n });\n apply(root, {}, componentsState);\n }\n\n /**\n * Set up real-time conditions for the current screen. Safe to call\n * twice — a second call rebuilds from screenState.\n *\n * Must run AFTER `updateScreenFromScreenState`, so the DOM reads below\n * see both server-shipped values and any component defaults from the\n * HTML.\n */\n initRealtimeConditions(\n rootElement: HTMLElement,\n screenState: ScreenState | undefined,\n ): void {\n this.#teardownRealtimeRuntime();\n\n const conditions = screenState?.realtimeComponentsConditions ?? [];\n if (!conditions.length) {\n this.logger.debug(\n `${LOG_PREFIX} no real-time rules to apply on this screen`,\n );\n return;\n }\n this.logger.info(\n `${LOG_PREFIX} found ${conditions.length} real-time rule(s) for this screen`,\n );\n\n // screenState.form uses \"phone\"; rules reference \"form.phone\".\n // Add the prefix on the way in.\n const initialSnapshot: FormSnapshot = {};\n Object.entries(screenState?.form ?? {}).forEach(([k, v]) => {\n initialSnapshot[`form.${k}`] = v;\n });\n\n // For every key the rules reference, read the current DOM value.\n // Component defaults (e.g. `checked=\"true\"` on a descope-checkbox)\n // live only in the HTML and don't make it into screenState.form, so\n // without this read the first evaluation would miss them.\n collectReferencedFormKeys(conditions).forEach((formKey) => {\n const el = findInputForFormKey(rootElement, formKey);\n if (!el) return;\n const v = readInputValue(el);\n if (v !== undefined) initialSnapshot[formKey] = v;\n });\n\n const touchedIds = collectTouchedComponentIds(conditions);\n\n // What to fall back to when a real-time rule stops matching for a\n // touched component — the actions set by server-only rules (rules\n // with no client-side conditions).\n const serverBaseline: Record<string, string> = {};\n // What's already painted on the DOM (touched components only), so\n // the first real-time evaluation can diff against the right state.\n const initialApplied: Record<string, string> = {};\n\n Object.entries(screenState?.componentsState ?? {}).forEach(\n ([id, action]) => {\n if (!touchedIds.has(id)) return;\n initialApplied[id] = action;\n },\n );\n\n Object.entries(screenState?.serverOnlyComponentsState ?? {}).forEach(\n ([id, action]) => {\n if (touchedIds.has(id)) {\n serverBaseline[id] = action;\n }\n },\n );\n\n const runtime: RealtimeRuntime = {\n conditions,\n touchedIds,\n snapshot: initialSnapshot,\n applied: initialApplied,\n serverBaseline,\n debounceTimer: null,\n paused: false,\n unsubscribePauseListener: null,\n inputHandler: () => {},\n root: rootElement,\n };\n\n // Re-run the rules now that we've read the real DOM values. The\n // server evaluated without seeing component defaults, so its\n // `componentsState` can disagree with what the user actually sees.\n // Apply the diff once before listening for input.\n const reconciled = effectiveActions(\n evaluateAll(conditions, initialSnapshot),\n serverBaseline,\n touchedIds,\n );\n if (!shallowEqualStringMap(initialApplied, reconciled)) {\n runtime.applied = apply(rootElement, initialApplied, reconciled);\n }\n\n runtime.inputHandler = (e: Event) =>\n this.#handleRealtimeInput(e as InputEvent);\n\n REALTIME_CONDITION_EVENTS.forEach((ev) => {\n rootElement.addEventListener(ev, runtime.inputHandler, true);\n });\n this.logger.debug(\n `${LOG_PREFIX} listening for \"${REALTIME_CONDITION_EVENTS.join(\n '\" and \"',\n )}\" events on form fields; ${\n Object.keys(initialApplied).length\n } component(s) start hidden / disabled / read-only by these rules`,\n );\n\n // Pause while a /next request is in flight. Without this, a debounced\n // evaluation could run between submit and the next screen render and\n // change components that are about to be replaced — causing flicker,\n // or hiding something the next screen needs visible.\n const pauseState = (this as unknown as PausableHost).nextRequestStatus;\n if (pauseState?.subscribe) {\n const handler = ({ isLoading }: { isLoading: boolean }) => {\n runtime.paused = isLoading;\n if (isLoading && runtime.debounceTimer) {\n clearTimeout(runtime.debounceTimer);\n runtime.debounceTimer = null;\n }\n };\n // subscribe returns a token; unsubscribe needs that token, not the\n // handler. Without storing it, handlers leak across screens and\n // keep old runtimes (and their DOM roots) alive.\n const token = pauseState.subscribe(handler);\n runtime.unsubscribePauseListener = () => {\n if (token !== undefined && token !== null) {\n pauseState.unsubscribe?.(token);\n }\n };\n }\n\n this.#rtRuntime = runtime;\n }\n\n #handleRealtimeInput(e: InputEvent): void {\n const runtime = this.#rtRuntime;\n if (!runtime.root || runtime.paused) return;\n\n const target = e.target as Element | null;\n if (!target) return;\n if (target.hasAttribute?.(DESCOPE_ATTRIBUTE_EXCLUDE_FIELD)) return;\n\n const name = target.getAttribute?.('name');\n if (!name) return;\n\n // Update the snapshot only — evaluation is debounced. Use readInputValue\n // so checkboxes read the same way as at mount; otherwise `target.value`\n // would be the string \"on\" for native checkboxes and break is-true rules.\n const key = toFormKey(name);\n runtime.snapshot[key] = readInputValue(target);\n\n if (runtime.debounceTimer) {\n clearTimeout(runtime.debounceTimer);\n }\n runtime.debounceTimer = setTimeout(() => {\n runtime.debounceTimer = null;\n this.#reEvaluateRealtime();\n }, REALTIME_CONDITION_DEBOUNCE_MS);\n }\n\n #reEvaluateRealtime(): void {\n const runtime = this.#rtRuntime;\n if (!runtime.root) return;\n\n let next: Record<string, string>;\n try {\n next = effectiveActions(\n evaluateAll(runtime.conditions, runtime.snapshot),\n runtime.serverBaseline,\n runtime.touchedIds,\n );\n } catch (e) {\n this.logger.error(\n `${LOG_PREFIX} failed to evaluate real-time rules — keeping the previous state`,\n (e as Error)?.message,\n );\n return;\n }\n\n const prevApplied = runtime.applied;\n if (shallowEqualStringMap(prevApplied, next)) return;\n\n this.logger.debug(\n `${LOG_PREFIX} form changed — updating components: was ${JSON.stringify(\n prevApplied,\n )}, now ${JSON.stringify(next)}`,\n );\n runtime.applied = apply(runtime.root, prevApplied, next);\n }\n\n // Clean up listeners and timers when the host leaves the DOM. Reaches\n // us only if BaseDescopeWc calls `super.disconnectedCallback?.()`;\n // otherwise teardown happens lazily on the next initRealtimeConditions.\n disconnectedCallback() {\n // disconnectedCallback isn't on HTMLElement in the lib types, but it\n // exists at runtime — forward into super in case the chain uses it.\n super.disconnectedCallback?.();\n this.#teardownRealtimeRuntime();\n }\n\n #teardownRealtimeRuntime(): void {\n const r = this.#rtRuntime;\n if (r.debounceTimer) {\n clearTimeout(r.debounceTimer);\n }\n if (r.unsubscribePauseListener) {\n r.unsubscribePauseListener();\n }\n if (r.root) {\n // Undo anything we applied so the next screen starts clean. Skip\n // if the root is already gone (replaced by the next screen) —\n // nothing left to undo.\n if (Object.keys(r.applied).length > 0 && r.root.isConnected) {\n apply(r.root, r.applied, {});\n }\n REALTIME_CONDITION_EVENTS.forEach((ev) => {\n r.root!.removeEventListener(ev, r.inputHandler, true);\n });\n }\n this.#rtRuntime = emptyRuntime();\n }\n };\n },\n);\n"],"names":["LOG_PREFIX","readInputValue","el","HTMLInputElement","type","checked","value","shallowEqualStringMap","a","b","keysA","Object","keys","keysB","length","every","k","emptyRuntime","conditions","touchedIds","Set","snapshot","applied","serverBaseline","debounceTimer","paused","unsubscribePauseListener","inputHandler","root","effectiveActions","realtimeVerdict","out","forEach","id","componentConditionsMixin","createSingletonMixin","superclass","BaseClass","compose","loggerMixin","_a","constructor","_ComponentConditionsMixin_rtRuntime","set","this","applyComponentsState","componentsState","entries","action","COMPONENT_ACTIONS","includes","logger","error","map","join","apply","initRealtimeConditions","rootElement","screenState","__classPrivateFieldGet","_ComponentConditionsMixin_instances","_ComponentConditionsMixin_teardownRealtimeRuntime","call","_b","realtimeComponentsConditions","debug","info","initialSnapshot","_c","form","v","collectReferencedFormKeys","formKey","bare","startsWith","slice","querySelector","escapeSelector","findInputForFormKey","undefined","collectTouchedComponentIds","initialApplied","_d","has","_e","serverOnlyComponentsState","runtime","reconciled","evaluateAll","e","REALTIME_CONDITION_EVENTS","ev","addEventListener","pauseState","nextRequestStatus","subscribe","handler","isLoading","clearTimeout","token","unsubscribe","__classPrivateFieldSet","disconnectedCallback","super","target","hasAttribute","DESCOPE_ATTRIBUTE_EXCLUDE_FIELD","name","getAttribute","key","toFormKey","setTimeout","_ComponentConditionsMixin_reEvaluateRealtime","REALTIME_CONDITION_DEBOUNCE_MS","next","message","prevApplied","JSON","stringify","r","isConnected","removeEventListener"],"mappings":"gTAqBA,MAAMA,EAAa,wBAgEnB,SAASC,EAAeC,GACtB,OAAIA,aAAcC,iBACG,aAAZD,EAAGE,KAAsBF,EAAGG,QAAUH,EAAGI,MAE9C,YAAaJ,EACPA,EAAuCG,QAE7C,UAAWH,EACLA,EAAqCI,WAD/C,CAIF,CAEA,SAASC,EACPC,EACAC,GAEA,MAAMC,EAAQC,OAAOC,KAAKJ,GACpBK,EAAQF,OAAOC,KAAKH,GAC1B,OAAIC,EAAMI,SAAWD,EAAMC,QACpBJ,EAAMK,OAAOC,GAAMR,EAAEQ,KAAOP,EAAEO,IACvC,CAEA,SAASC,IACP,MAAO,CACLC,WAAY,GACZC,WAAY,IAAIC,IAChBC,SAAU,CAAE,EACZC,QAAS,CAAE,EACXC,eAAgB,CAAE,EAClBC,cAAe,KAC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ACjCzB,EAAQ9D,cAAgB,KACxBmC,EAAAA,uBAAAf,KAAIgB,EAAA,IAAAoD,GAAJlD,KAAAlB,KAA0B,GACzBqE,EAA8BA,+BAClC,eAGC,MAAM3B,EAAU3B,EAAAA,uBAAAf,YAChB,IAAK0C,EAAQ1D,KAAM,OAEnB,IAAIsF,EACJ,IACEA,EAAOrF,EACL2D,cAAYF,EAAQpE,WAAYoE,EAAQjE,UACxCiE,EAAQ/D,eACR+D,EAAQnE,WAEX,CAAC,MAAOsE,GAKP,YAJA7C,KAAKO,OAAOC,MACV,GAAGpD,oEACFyF,aAAC,EAADA,EAAa0B,QAGjB,CAED,MAAMC,EAAc9B,EAAQhE,QACxBf,EAAsB6G,EAAaF,KAEvCtE,KAAKO,OAAOc,MACV,GAAGjE,6CAAsDqH,KAAKC,UAC5DF,WACQC,KAAKC,UAAUJ,MAE3B5B,EAAQhE,QAAUiC,QAAM+B,EAAQ1D,KAAMwF,EAAaF,GACpD,eAaC,MAAMK,EAAI5D,EAAAA,uBAAAf,YACN2E,EAAE/F,eACJ0E,aAAaqB,EAAE/F,eAEb+F,EAAE7F,0BACJ6F,EAAE7F,2BAEA6F,EAAE3F,OAIAjB,OAAOC,KAAK2G,EAAEjG,SAASR,OAAS,GAAKyG,EAAE3F,KAAK4F,aAC9CjE,EAAKA,MAACgE,EAAE3F,KAAM2F,EAAEjG,QAAS,CAAE,GAE7BoE,4BAA0B1D,SAAS2D,IACjC4B,EAAE3F,KAAM6F,oBAAoB9B,EAAI4B,EAAE5F,cAAc,EAAK,KAGzD0E,EAAAA,uBAAAzD,KAAIF,EAAczB,QACnB,EACDuB,CAAA"}
|
|
1
|
+
{"version":3,"file":"componentConditionsMixin.js","sources":["../../../src/lib/mixins/componentConditionsMixin.ts"],"sourcesContent":["/* eslint-disable import/prefer-default-export, no-param-reassign */\nimport { compose, createSingletonMixin } from '@descope/sdk-helpers';\nimport { loggerMixin } from '@descope/sdk-mixins';\nimport {\n REALTIME_CONDITION_DEBOUNCE_MS,\n REALTIME_CONDITION_EVENTS,\n} from '../helpers/realtime-conditions/config';\nimport {\n collectReferencedFormKeys,\n collectTouchedComponentIds,\n evaluateAll,\n FormSnapshot,\n} from '../helpers/realtime-conditions/evaluator';\nimport {\n apply,\n COMPONENT_ACTIONS,\n escapeSelector,\n} from '../helpers/realtime-conditions/applier';\nimport { DESCOPE_ATTRIBUTE_EXCLUDE_FIELD } from '../constants';\nimport type { RealtimeComponentsCondition, ScreenState } from '../types';\n\nconst LOG_PREFIX = 'component-conditions:';\n\n// What the mixin needs from its host: a way to subscribe to loading state\n// so input handling can pause while the next request is in flight. Defined\n// as an interface (not imported) to avoid a circular dependency on BaseDescopeWc.\nexport interface PausableHost {\n nextRequestStatus?: {\n // subscribe returns a token; pass that token to unsubscribe — not the handler.\n subscribe: (cb: (v: { isLoading: boolean }) => void) => string;\n unsubscribe?: (token: string) => void;\n };\n}\n\nexport interface RealtimeRuntime {\n conditions: RealtimeComponentsCondition[];\n // IDs of components that any rule can change\n touchedIds: Set<string>;\n // latest form values on screen\n snapshot: FormSnapshot;\n // what's currently applied on screen for touched components.\n // Compared against on each re-evaluation to know what to change.\n applied: Record<string, string>;\n // What the server told us to apply for these components. Stays fixed for\n // the screen's lifetime so we can fall back to it when a real-time rule\n // stops matching. Without this, a server-set action could disappear when\n // a real-time rule briefly fires on the same component.\n serverBaseline: Record<string, string>;\n debounceTimer: ReturnType<typeof setTimeout> | null;\n // true while paused (during submit, to avoid stale updates)\n paused: boolean;\n unsubscribePauseListener: (() => void) | null;\n // the listener we attach to form events (kept so we can detach)\n inputHandler: (e: Event) => void;\n // the screen root we work against\n root: HTMLElement | null;\n}\n\n// Some inputs already have `name=\"form.x\"`, others use `name=\"x\"`. Always\n// return the `form.x` form so it lines up with what rules reference.\nfunction toFormKey(name: string): string {\n return name.startsWith('form.') ? name : `form.${name}`;\n}\n\n// Try the full `form.x` first (descope components), then `x` (plain inputs).\nfunction findInputForFormKey(\n root: ParentNode,\n formKey: string,\n): Element | null {\n const bare = formKey.startsWith('form.')\n ? formKey.slice('form.'.length)\n : formKey;\n return (\n root.querySelector(`[name=\"${escapeSelector(formKey)}\"]`) ||\n root.querySelector(`[name=\"${escapeSelector(bare)}\"]`)\n );\n}\n\n// Read the current value off a form input. Reads JS properties (not HTML\n// attributes) so we pick up both the component's default and any value\n// carried over from earlier screens.\n//\n// Native <input type=checkbox> needs special handling: `.value` is always\n// \"on\", only `.checked` reflects the real state. Descope boolean components\n// (descope-checkbox, descope-switch-toggle) expose `.checked` on their class.\nfunction readInputValue(el: Element): unknown {\n if (el instanceof HTMLInputElement) {\n return el.type === 'checkbox' ? el.checked : el.value;\n }\n if ('checked' in el) {\n return (el as unknown as { checked: boolean }).checked;\n }\n if ('value' in el) {\n return (el as unknown as { value: unknown }).value;\n }\n return undefined;\n}\n\nfunction shallowEqualStringMap(\n a: Record<string, string>,\n b: Record<string, string>,\n): boolean {\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n if (keysA.length !== keysB.length) return false;\n return keysA.every((k) => a[k] === b[k]);\n}\n\nfunction emptyRuntime(): RealtimeRuntime {\n return {\n conditions: [],\n touchedIds: new Set(),\n snapshot: {},\n applied: {},\n serverBaseline: {},\n debounceTimer: null,\n paused: false,\n unsubscribePauseListener: null,\n inputHandler: () => {},\n root: null,\n };\n}\n\n// For each touched component, pick the real-time action if a rule is firing\n// for it, otherwise fall back to the server's action. Components that no rule\n// touches are not in the result — those were already painted by\n// applyComponentsState.\nfunction effectiveActions(\n realtimeVerdict: Record<string, string>,\n serverBaseline: Record<string, string>,\n touchedIds: Set<string>,\n): Record<string, string> {\n const out: Record<string, string> = {};\n touchedIds.forEach((id) => {\n if (realtimeVerdict[id]) {\n out[id] = realtimeVerdict[id];\n } else if (serverBaseline[id]) {\n out[id] = serverBaseline[id];\n }\n });\n return out;\n}\n\nexport const componentConditionsMixin = createSingletonMixin(\n <T extends CustomElementConstructor>(superclass: T) => {\n // Pull in loggerMixin so `this.logger` is available no matter where\n // this mixin sits in the chain.\n const BaseClass = compose(loggerMixin)(superclass);\n\n return class ComponentConditionsMixin extends BaseClass {\n // One runtime per <descope-wc> element.\n #rtRuntime: RealtimeRuntime = emptyRuntime();\n\n /**\n * Apply the server's hide/disable/read-only actions to the DOM.\n * Logs unknown actions here (runs once per screen) but stays quiet on\n * the keystroke path to avoid log spam.\n */\n applyComponentsState(\n root: ParentNode,\n componentsState: Record<string, string> | undefined,\n ): void {\n if (!componentsState) return;\n Object.entries(componentsState).forEach(([id, action]) => {\n if (!(COMPONENT_ACTIONS as readonly string[]).includes(action)) {\n this.logger.error(\n `Unknown component action \"${action}\" for component with id \"${id}\"`,\n `Valid actions are ${COMPONENT_ACTIONS.map((a) => `\"${a}\"`).join(\n ', ',\n )}`,\n );\n }\n });\n apply(root, {}, componentsState);\n }\n\n /**\n * Set up real-time conditions for the current screen. Safe to call\n * twice — a second call rebuilds from screenState.\n *\n * Must run AFTER `updateScreenFromScreenState`, so the DOM reads below\n * see both server-shipped values and any component defaults from the\n * HTML.\n */\n initRealtimeConditions(\n rootElement: HTMLElement,\n screenState: ScreenState | undefined,\n ): void {\n this.#teardownRealtimeRuntime();\n\n const conditions = screenState?.realtimeComponentsConditions ?? [];\n if (!conditions.length) {\n this.logger.debug(\n `${LOG_PREFIX} no real-time rules to apply on this screen`,\n );\n return;\n }\n this.logger.info(\n `${LOG_PREFIX} found ${conditions.length} real-time rule(s) for this screen`,\n );\n\n // screenState.form uses \"phone\"; rules reference \"form.phone\".\n // Add the prefix on the way in.\n const initialSnapshot: FormSnapshot = {};\n Object.entries(screenState?.form ?? {}).forEach(([k, v]) => {\n initialSnapshot[`form.${k}`] = v;\n });\n\n // For every key the rules reference, read the current DOM value.\n // Component defaults (e.g. `checked=\"true\"` on a descope-checkbox)\n // live only in the HTML and don't make it into screenState.form, so\n // without this read the first evaluation would miss them.\n collectReferencedFormKeys(conditions).forEach((formKey) => {\n const el = findInputForFormKey(rootElement, formKey);\n if (!el) return;\n const v = readInputValue(el);\n if (v !== undefined) initialSnapshot[formKey] = v;\n });\n\n const touchedIds = collectTouchedComponentIds(conditions);\n\n // What to fall back to when a real-time rule stops matching for a\n // touched component — the actions set by server-only rules (rules\n // with no client-side conditions).\n const serverBaseline: Record<string, string> = {};\n // What's already painted on the DOM (touched components only), so\n // the first real-time evaluation can diff against the right state.\n const initialApplied: Record<string, string> = {};\n\n Object.entries(screenState?.componentsState ?? {}).forEach(\n ([id, action]) => {\n if (!touchedIds.has(id)) return;\n initialApplied[id] = action;\n },\n );\n\n Object.entries(screenState?.serverOnlyComponentsState ?? {}).forEach(\n ([id, action]) => {\n if (touchedIds.has(id)) {\n serverBaseline[id] = action;\n }\n },\n );\n\n const runtime: RealtimeRuntime = {\n conditions,\n touchedIds,\n snapshot: initialSnapshot,\n applied: initialApplied,\n serverBaseline,\n debounceTimer: null,\n paused: false,\n unsubscribePauseListener: null,\n inputHandler: () => {},\n root: rootElement,\n };\n\n // Re-run the rules now that we've read the real DOM values. The\n // server evaluated without seeing component defaults, so its\n // `componentsState` can disagree with what the user actually sees.\n // Apply the diff once before listening for input.\n const reconciled = effectiveActions(\n evaluateAll(conditions, initialSnapshot),\n serverBaseline,\n touchedIds,\n );\n if (!shallowEqualStringMap(initialApplied, reconciled)) {\n runtime.applied = apply(rootElement, initialApplied, reconciled);\n }\n\n runtime.inputHandler = (e: Event) =>\n this.#handleRealtimeInput(e as InputEvent);\n\n REALTIME_CONDITION_EVENTS.forEach((ev) => {\n rootElement.addEventListener(ev, runtime.inputHandler, true);\n });\n this.logger.debug(\n `${LOG_PREFIX} listening for \"${REALTIME_CONDITION_EVENTS.join(\n '\" and \"',\n )}\" events on form fields; ${\n Object.keys(initialApplied).length\n } component(s) start hidden / disabled / read-only by these rules`,\n );\n\n // Pause while a /next request is in flight. Without this, a debounced\n // evaluation could run between submit and the next screen render and\n // change components that are about to be replaced — causing flicker,\n // or hiding something the next screen needs visible.\n const pauseState = (this as unknown as PausableHost).nextRequestStatus;\n if (pauseState?.subscribe) {\n const handler = ({ isLoading }: { isLoading: boolean }) => {\n runtime.paused = isLoading;\n if (isLoading && runtime.debounceTimer) {\n clearTimeout(runtime.debounceTimer);\n runtime.debounceTimer = null;\n }\n };\n // subscribe returns a token; unsubscribe needs that token, not the\n // handler. Without storing it, handlers leak across screens and\n // keep old runtimes (and their DOM roots) alive.\n const token = pauseState.subscribe(handler);\n runtime.unsubscribePauseListener = () => {\n if (token !== undefined && token !== null) {\n pauseState.unsubscribe?.(token);\n }\n };\n }\n\n this.#rtRuntime = runtime;\n }\n\n #handleRealtimeInput(e: InputEvent): void {\n const runtime = this.#rtRuntime;\n if (!runtime.root || runtime.paused) return;\n\n const target = e.target as Element | null;\n if (!target) return;\n if (target.hasAttribute?.(DESCOPE_ATTRIBUTE_EXCLUDE_FIELD)) return;\n\n const name = target.getAttribute?.('name');\n if (!name) return;\n\n // Update the snapshot only — evaluation is debounced. Use readInputValue\n // so checkboxes read the same way as at mount; otherwise `target.value`\n // would be the string \"on\" for native checkboxes and break is-true rules.\n const key = toFormKey(name);\n runtime.snapshot[key] = readInputValue(target);\n\n if (runtime.debounceTimer) {\n clearTimeout(runtime.debounceTimer);\n }\n runtime.debounceTimer = setTimeout(() => {\n runtime.debounceTimer = null;\n this.#reEvaluateRealtime();\n }, REALTIME_CONDITION_DEBOUNCE_MS);\n }\n\n #reEvaluateRealtime(): void {\n const runtime = this.#rtRuntime;\n if (!runtime.root) return;\n\n let next: Record<string, string>;\n try {\n next = effectiveActions(\n evaluateAll(runtime.conditions, runtime.snapshot),\n runtime.serverBaseline,\n runtime.touchedIds,\n );\n } catch (e) {\n this.logger.error(\n `${LOG_PREFIX} failed to evaluate real-time rules — keeping the previous state`,\n (e as Error)?.message,\n );\n return;\n }\n\n const prevApplied = runtime.applied;\n if (shallowEqualStringMap(prevApplied, next)) return;\n\n this.logger.debug(\n `${LOG_PREFIX} form changed — updating components: was ${JSON.stringify(\n prevApplied,\n )}, now ${JSON.stringify(next)}`,\n );\n runtime.applied = apply(runtime.root, prevApplied, next);\n }\n\n // Clean up listeners and timers when the host leaves the DOM. Reaches\n // us only if BaseDescopeWc calls `super.disconnectedCallback?.()`;\n // otherwise teardown happens lazily on the next initRealtimeConditions.\n disconnectedCallback() {\n // disconnectedCallback isn't on HTMLElement in the lib types, but it\n // exists at runtime — forward into super in case the chain uses it.\n super.disconnectedCallback?.();\n this.#teardownRealtimeRuntime();\n }\n\n #teardownRealtimeRuntime(): void {\n const r = this.#rtRuntime;\n if (r.debounceTimer) {\n clearTimeout(r.debounceTimer);\n }\n if (r.unsubscribePauseListener) {\n r.unsubscribePauseListener();\n }\n if (r.root) {\n // Deliberately NOT undoing what we applied. `r.root` is the host's\n // content root, which is built once in the constructor and never\n // replaced. Only its children are. By the time we get here the caller\n // has already swapped in the next screen, so looking our component\n // ids up in `r.root` finds the NEW screen's elements and would strip\n // the state the server just painted on them. Nothing needs undoing\n // anyway, because the elements we touched went with the old screen.\n REALTIME_CONDITION_EVENTS.forEach((ev) => {\n r.root!.removeEventListener(ev, r.inputHandler, true);\n });\n }\n this.#rtRuntime = emptyRuntime();\n }\n };\n },\n);\n"],"names":["LOG_PREFIX","readInputValue","el","HTMLInputElement","type","checked","value","shallowEqualStringMap","a","b","keysA","Object","keys","keysB","length","every","k","emptyRuntime","conditions","touchedIds","Set","snapshot","applied","serverBaseline","debounceTimer","paused","unsubscribePauseListener","inputHandler","root","effectiveActions","realtimeVerdict","out","forEach","id","componentConditionsMixin","createSingletonMixin","superclass","BaseClass","compose","loggerMixin","_a","constructor","_ComponentConditionsMixin_rtRuntime","set","this","applyComponentsState","componentsState","entries","action","COMPONENT_ACTIONS","includes","logger","error","map","join","apply","initRealtimeConditions","rootElement","screenState","__classPrivateFieldGet","_ComponentConditionsMixin_instances","_ComponentConditionsMixin_teardownRealtimeRuntime","call","_b","realtimeComponentsConditions","debug","info","initialSnapshot","_c","form","v","collectReferencedFormKeys","formKey","bare","startsWith","slice","querySelector","escapeSelector","findInputForFormKey","undefined","collectTouchedComponentIds","initialApplied","_d","has","_e","serverOnlyComponentsState","runtime","reconciled","evaluateAll","e","REALTIME_CONDITION_EVENTS","ev","addEventListener","pauseState","nextRequestStatus","subscribe","handler","isLoading","clearTimeout","token","unsubscribe","__classPrivateFieldSet","disconnectedCallback","super","target","hasAttribute","DESCOPE_ATTRIBUTE_EXCLUDE_FIELD","name","getAttribute","key","toFormKey","setTimeout","_ComponentConditionsMixin_reEvaluateRealtime","REALTIME_CONDITION_DEBOUNCE_MS","next","message","prevApplied","JSON","stringify","r","removeEventListener"],"mappings":"gTAqBA,MAAMA,EAAa,wBAgEnB,SAASC,EAAeC,GACtB,OAAIA,aAAcC,iBACG,aAAZD,EAAGE,KAAsBF,EAAGG,QAAUH,EAAGI,MAE9C,YAAaJ,EACPA,EAAuCG,QAE7C,UAAWH,EACLA,EAAqCI,WAD/C,CAIF,CAEA,SAASC,EACPC,EACAC,GAEA,MAAMC,EAAQC,OAAOC,KAAKJ,GACpBK,EAAQF,OAAOC,KAAKH,GAC1B,OAAIC,EAAMI,SAAWD,EAAMC,QACpBJ,EAAMK,OAAOC,GAAMR,EAAEQ,KAAOP,EAAEO,IACvC,CAEA,SAASC,IACP,MAAO,CACLC,WAAY,GACZC,WAAY,IAAIC,IAChBC,SAAU,CAAE,EACZC,QAAS,CAAE,EACXC,eAAgB,CAAE,EAClBC,cAAe,KACfC,QAAQ,EACRC,yBAA0B,KAC1BC,aAAc,OACdC,KAAM,KAEV,CAMA,SAASC,EACPC,EACAP,EACAJ,GAEA,MAAMY,EAA8B,CAAA,EAQpC,OAPAZ,EAAWa,SAASC,IACdH,EAAgBG,GAClBF,EAAIE,GAAMH,EAAgBG,GACjBV,EAAeU,KACxBF,EAAIE,GAAMV,EAAeU,GAC1B,IAEIF,CACT,OAEaG,EAA2BC,EAAAA,sBACDC,oBAGnC,MAAMC,EAAYC,EAAOA,QAACC,cAARD,CAAqBF,GAEvC,OAAOI,EAAA,cAAuCH,EAAvC,WAAA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,EAADA,EAAa0B,QAGjB,CAED,MAAMC,EAAc9B,EAAQhE,QACxBf,EAAsB6G,EAAaF,KAEvCtE,KAAKO,OAAOc,MACV,GAAGjE,6CAAsDqH,KAAKC,UAC5DF,WACQC,KAAKC,UAAUJ,MAE3B5B,EAAQhE,QAAUiC,QAAM+B,EAAQ1D,KAAMwF,EAAaF,GACpD,eAaC,MAAMK,EAAI5D,EAAAA,uBAAAf,YACN2E,EAAE/F,eACJ0E,aAAaqB,EAAE/F,eAEb+F,EAAE7F,0BACJ6F,EAAE7F,2BAEA6F,EAAE3F,MAQJ8D,4BAA0B1D,SAAS2D,IACjC4B,EAAE3F,KAAM4F,oBAAoB7B,EAAI4B,EAAE5F,cAAc,EAAK,IAGzD0E,EAAAA,uBAAAzD,KAAIF,EAAczB,QACnB,EACDuB,CAAA"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{__classPrivateFieldGet as t,__awaiter as e,__classPrivateFieldSet as i}from"tslib";import{compose as s}from"@descope/sdk-helpers";import{staticResourcesMixin as r}from"@descope/sdk-mixins/static-resources-mixin";import{themeMixin as o}from"@descope/sdk-mixins/theme-mixin";import{injectStyleMixin as n}from"@descope/sdk-mixins/inject-style-mixin";import{telemetryMixin as a}from"@descope/sdk-mixins/telemetry-mixin";import{createSdk as u,getSessionToken as l}from"@descope/web-js-sdk";import{ELEMENTS_TO_IGNORE_ENTER_KEY_ON as d}from"../constants/index.js";import{handleUrlParams as h,clearRunIdsFromUrl as c,camelCase as f,getRunIdsFromUrl as g,getContentUrl as p,fetchContent as m,withRetry as v}from"../helpers/helpers.js";import b from"../helpers/state.js";import"@descope/escape-markdown";import"../helpers/webauthn.js";import{setCustomStorage as w}from"../helpers/storage.js";import{transformFlowInputFormData as k,extractNestedAttribute as y}from"../helpers/flowInputs.js";import{formMountMixin as C}from"../mixins/formMountMixin.js";import{componentConditionsMixin as x}from"../mixins/componentConditionsMixin.js";import{duplicateFlowWarningMixin as A}from"../mixins/duplicateFlowWarningMixin.js";import{passwordManagerMixin as j}from"../mixins/passwordManagerMixin.js";import{validationTrackingMixin as I}from"../mixins/validationTrackingMixin.js";import{CONFIG_FILENAME as E,PREV_VER_ASSETS_FOLDER as M}from"../constants/content.js";import{FETCH_EXCEPTION_ERROR_CODE as S}from"../constants/general.js";var L,U,O,W,P,D,N,T,F,K,R,z,J,V,B,H,q,$,Q,G,X,Y,Z,_,tt,et;const it=s(o,r,C,x,A,j,n,a,I)(HTMLElement);class st extends it{static get observedAttributes(){return["project-id","flow-id","base-url","tenant","locale","debug","storage-prefix","preview","redirect-url","auto-focus","store-last-authenticated-user","refresh-cookie-name","keep-last-authenticated-user-after-logout","validate-on-blur","send-session-token","style-id"]}constructor(s){super(),L.add(this),this.sdkVersion="4.4.5",O.set(this,!1),W.set(this,void 0),this.flowStatus="initial",this.loggerWrapper={error:(e,i="")=>{this.logger.error(e,i,new Error),t(this,L,"m",et).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)}},P.set(this,new b),D.set(this,new b),N.set(this,{}),this.getComponentsContext=()=>t(this,N,"f"),this.nextRequestStatus=new b({isLoading:!1}),T.set(this,void 0),F.set(this,{popstate:t(this,L,"m",V).bind(this),componentsContext:t(this,L,"m",G).bind(this)}),K.set(this,void 0),this.getConfig=()=>e(this,void 0,void 0,(function*(){return(yield this.config)||{isMissingConfig:!0}})),X.set(this,void 0),Y.set(this,void 0),i(this,K,s,"f"),t(this,L,"m",z).call(this)}get client(){try{return JSON.parse(this.getAttribute("client"))||{}}catch(t){return{}}}get redirectUrl(){return this.getAttribute("redirect-url")||void 0}get debug(){return"true"===this.getAttribute("debug")}get locale(){return this.getAttribute("locale")||void 0}get autoFocus(){var t;const e=null!==(t=this.getAttribute("auto-focus"))&&void 0!==t?t:"true";return"skipFirstScreen"===e?e:"true"===e}get validateOnBlur(){return"true"===this.getAttribute("validate-on-blur")}get storeLastAuthenticatedUser(){var t;return"true"===(null!==(t=this.getAttribute("store-last-authenticated-user"))&&void 0!==t?t:"true")}get refreshCookieName(){return this.getAttribute("refresh-cookie-name")||""}get keepLastAuthenticatedUserAfterLogout(){return"true"===this.getAttribute("keep-last-authenticated-user-after-logout")}get storagePrefix(){return this.getAttribute("storage-prefix")||""}get sendSessionToken(){return"true"===this.getAttribute("send-session-token")}get preview(){return!!this.getAttribute("preview")}get formConfig(){return k(this.form)}get form(){return this.getAttribute("form")}get formConfigValues(){return y(this.formConfig,"value")}get outboundAppId(){return this.getAttribute("outbound-app-id")}get outboundAppScopes(){try{const t=JSON.parse(this.getAttribute("outbound-app-scopes"));return t||null}catch(t){return null}}get popupOrigin(){return this.getAttribute("popup-origin")}get customStorage(){return t(this,W,"f")}set customStorage(t){if(t&&"function"!=typeof t.getItem)throw new Error("Custom storage must have a getItem method");if(t&&"function"!=typeof t.setItem)throw new Error("Custom storage must have a setItem method");if(t&&"function"!=typeof t.removeItem)throw new Error("Custom storage must have a removeItem method");i(this,W,t,"f"),w(t)}get lazyStart(){return"true"===this.getAttribute("lazy-start")}start(){var e;null===(e=t(this,Y,"f"))||void 0===e||e.call(this),i(this,X,Promise.resolve(),"f")}get isRestartOnError(){return"true"===this.getAttribute("restart-on-error")}getExecutionContext(){return e(this,void 0,void 0,(function*(){const t=yield this.getConfig();return"executionContext"in t?t.executionContext:void 0}))}getProjectConfig(){return e(this,void 0,void 0,(function*(){const t=yield this.getConfig();return"projectConfig"in t?t.projectConfig:void 0}))}getFlowConfig(){return e(this,void 0,void 0,(function*(){var t,e;const i=yield this.getProjectConfig(),s=(null===(t=null==i?void 0:i.flows)||void 0===t?void 0:t[this.flowId])||{};return null!==(e=s.version)&&void 0!==e||(s.version=0),s}))}getTargetLocales(){return e(this,void 0,void 0,(function*(){const t=yield this.getFlowConfig();return((null==t?void 0:t.targetLocales)||[]).map((t=>t.toLowerCase()))}))}handleKeyPress(){this.logger.debug("Enable key press handler"),this.rootElement.onkeydown=t=>{var e,i,s;const r=!!(null===(e=this.shadowRoot.activeElement)||void 0===e?void 0:e.getAttribute("href")),o=d.includes(null!==(s=null===(i=this.shadowRoot.activeElement)||void 0===i?void 0:i.localName)&&void 0!==s?s:"");if("Enter"!==t.key||r||o)return;t.preventDefault();const n=this.rootElement.querySelectorAll("descope-button");if(1===n.length&&"false"!==n[0].getAttribute("auto-submit"))return void n[0].click();const a=Array.from(n).filter((t=>"true"===t.getAttribute("auto-submit")));if(1===a.length)return void a[0].click();const u=Array.from(n).filter((t=>"button"===t.getAttribute("data-type")));if(1===u.length)"false"!==u[0].getAttribute("auto-submit")&&u[0].click();else if(0===u.length){const t=Array.from(n).filter((t=>"sso"===t.getAttribute("data-type")));1===t.length&&"false"!==t[0].getAttribute("auto-submit")&&t[0].click()}}}disableKeyPressHandler(){this.logger.debug("Disable key press handler"),this.rootElement.onkeydown=null}getComponentsVersion(){return e(this,void 0,void 0,(function*(){var t;const e=yield this.getConfig(),i="projectConfig"in e?null===(t=e.projectConfig)||void 0===t?void 0:t.componentsVersion:{};return i||(this.logger.error("Did not get components version, using latest version"),"latest")}))}init(){const s=Object.create(null,{init:{get:()=>super.init}});return e(this,void 0,void 0,(function*(){var e;if(this.flowStatus="loading",["ready","error","success"].forEach((t=>this.addEventListener(t,(()=>{this.flowStatus=t})))),yield null===(e=s.init)||void 0===e?void 0:e.call(this),t(this,D,"f").subscribe(t(this,L,"m",tt).bind(this)),t(this,D,"f").update({isDebug:this.debug}),t(this,L,"m",J).call(this),yield t(this,L,"m",$).call(this))return void this.loggerWrapper.error("This SDK version does not support your flows version","Make sure to upgrade your flows to the latest version or use an older SDK version");const r=yield this.getConfig();if("isMissingConfig"in r&&r.isMissingConfig)return void this.loggerWrapper.error("Cannot get config file","Make sure that your projectId & flowId are correct");const{executionId:o,stepId:n,token:a,code:u,isPopup:l,exchangeError:d,redirectAuthCallbackUrl:c,redirectAuthBackupCallbackUri:f,redirectAuthCodeChallenge:g,redirectAuthInitiator:p,ssoQueryParams:m}=h(this.flowId,this.loggerWrapper);window.addEventListener("popstate",t(this,F,"f").popstate),window.addEventListener("components-context",t(this,F,"f").componentsContext),t(this,P,"f").subscribe(t(this,L,"m",q).bind(this)),t(this,P,"f").update(Object.assign({projectId:this.projectId,flowId:this.flowId,baseUrl:this.baseUrl,tenant:this.tenantId,redirectUrl:this.redirectUrl,locale:this.locale,stepId:n,executionId:o,token:a,code:u,isPopup:l,exchangeError:d,redirectAuthCallbackUrl:c,redirectAuthBackupCallbackUri:f,redirectAuthCodeChallenge:g,redirectAuthInitiator:p},m)),i(this,O,!0,"f")}))}disconnectedCallback(){var e;t(this,P,"f").unsubscribeAll(),t(this,D,"f").unsubscribeAll(),t(this,L,"m",_).call(this),window.removeEventListener("popstate",t(this,F,"f").popstate),window.removeEventListener("components-context",t(this,F,"f").componentsContext),null===(e=super.disconnectedCallback)||void 0===e||e.call(this)}attributeChangedCallback(e,i,s){var r;if(null===(r=super.attributeChangedCallback)||void 0===r||r.call(this,e,i,s),this.shadowRoot.isConnected&&t(this,O,"f")&&i!==s&&U.observedAttributes.includes(e)){t(this,L,"m",J).call(this);const r=null===i;t(this,P,"f").update((({stepId:t,executionId:i})=>{let o=t,n=i;return r||(n=null,o=null,c()),{[f(e)]:s,stepId:o,executionId:n}})),t(this,D,"f").update({isDebug:this.debug})}}}U=st,O=new WeakMap,W=new WeakMap,P=new WeakMap,D=new WeakMap,N=new WeakMap,T=new WeakMap,F=new WeakMap,K=new WeakMap,X=new WeakMap,Y=new WeakMap,L=new WeakSet,R=function(){this.injectStyle("\n :host {\n\t\t\twidth: 100%;\n display: block;\n\t\t}\n\n\t\t#root {\n\t\t\theight: 100%;\n display: flex;\n flex-direction: column;\n\t\t}\n\n #content-root {\n all: initial;\n transition: opacity 200ms ease-in-out;\n }\n\n\t\t#root[data-theme] {\n\t\t\tbackground-color: transparent;\n\t\t}\n\n\t\t.fade-out {\n\t\t\topacity: 0.1!important;\n\t\t}\n\n .hidden {\n display: none;\n }\n ")},z=function(){t(this,L,"m",R).call(this),this.slotElement=document.createElement("slot"),this.slotElement.classList.add("hidden"),this.rootElement.appendChild(this.slotElement)},J=function(){const t=["base-url","tenant","locale","debug","redirect-url","auto-focus","store-last-authenticated-user","refresh-cookie-name","keep-last-authenticated-user-after-logout","preview","storage-prefix","form","client","validate-on-blur","send-session-token","style-id","outbound-app-id","outbound-app-scopes","theme-override"];U.observedAttributes.forEach((e=>{if(!t.includes(e)&&!this[f(e)])throw Error(`${e} cannot be empty`)}))},V=function(){const{stepId:e,executionId:i}=g(this.flowId);t(this,P,"f").update({stepId:e,executionId:i})},B=function(i,s){u&&"function"==typeof u||this.logger.error("SDK was not loaded properly",u,JSON.stringify(u));const r=Object.assign(Object.assign({persistTokens:!0,preview:this.preview,storagePrefix:this.storagePrefix,storeLastAuthenticatedUser:this.storeLastAuthenticatedUser,keepLastAuthenticatedUserAfterLogout:this.keepLastAuthenticatedUserAfterLogout,refreshCookieName:this.refreshCookieName},U.sdkConfigOverrides),{projectId:i,baseUrl:s});t(this,W,"f")&&(r.customStorage=t(this,W,"f")),this.sdk=u(r);const o={start:1,next:7};["start","next"].forEach((i=>{const s=this.sdk.flow[i],r=v(s,1e3,3);this.sdk.flow[i]=(...s)=>e(this,void 0,void 0,(function*(){const e=[...s],n=o[i],a=t(this,L,"m",H).call(this,e[n]);void 0!==a&&(e[n]=a);try{return yield r(...e)}catch(t){return this.logger.error(`Error in sdk flow ${i} function`,t),{error:{errorCode:S,errorDescription:t.toString()}}}}))}));const n=this.sdk.flow.start;this.sdk.flow.start=(...i)=>e(this,void 0,void 0,(function*(){return yield t(this,L,"m",Z).call(this),n.apply(this.sdk.flow,i)}))},H=function(t){if(!this.sendSessionToken)return t;const e=null==l?void 0:l(this.storagePrefix);return e?Object.assign(Object.assign({},null!=t?t:{}),{sessionJwt:e}):t},q=function(i,s,r){return e(this,void 0,void 0,(function*(){const{projectId:e,baseUrl:s}=i;if(r("projectId")||r("baseUrl")){if(!e)return;t(this,L,"m",B).call(this,e,s)}t(this,K,"f").call(this,i)}))},$=function(){return e(this,void 0,void 0,(function*(){const e=yield this.getConfig();return"isMissingConfig"in e&&e.isMissingConfig&&(yield t(this,L,"m",Q).call(this))}))},Q=function(){return e(this,void 0,void 0,(function*(){const t=p({projectId:this.projectId,filename:E,assetsFolder:M,baseUrl:this.baseStaticUrl});try{return yield m(t,"json"),!0}catch(t){return!1}}))},G=function(e){i(this,N,Object.assign(Object.assign({},t(this,N,"f")),e.detail),"f")},Z=function(){return this.lazyStart?(t(this,X,"f")||i(this,X,new Promise((t=>{i(this,Y,t,"f")})),"f"),t(this,X,"f")):Promise.resolve()},_=function(){var e;null===(e=t(this,T,"f"))||void 0===e||e.remove(),i(this,T,null,"f")},tt=function(s){return e(this,arguments,void 0,(function*({isDebug:e}){e?(i(this,T,document.createElement("descope-debugger"),"f"),Object.assign(t(this,T,"f").style,{position:"fixed",top:"0",right:"0",height:"100vh",width:"100vw",pointerEvents:"none",zIndex:99999}),yield import("../debugger-wc.js"),document.body.appendChild(t(this,T,"f"))):t(this,L,"m",_).call(this)}))},et=function(e,i){var s;e&&this.debug&&(null===(s=t(this,T,"f"))||void 0===s||s.updateData({title:e,description:i}))},st.sdkConfigOverrides={baseHeaders:{"x-descope-sdk-name":"web-component","x-descope-sdk-version":"4.4.5"}};export{st as default};
|
|
1
|
+
import{__classPrivateFieldGet as t,__awaiter as e,__classPrivateFieldSet as i}from"tslib";import{compose as s}from"@descope/sdk-helpers";import{staticResourcesMixin as r}from"@descope/sdk-mixins/static-resources-mixin";import{themeMixin as o}from"@descope/sdk-mixins/theme-mixin";import{injectStyleMixin as n}from"@descope/sdk-mixins/inject-style-mixin";import{telemetryMixin as a}from"@descope/sdk-mixins/telemetry-mixin";import{createSdk as u,getSessionToken as l}from"@descope/web-js-sdk";import{ELEMENTS_TO_IGNORE_ENTER_KEY_ON as d}from"../constants/index.js";import{handleUrlParams as h,clearRunIdsFromUrl as c,camelCase as f,getRunIdsFromUrl as g,getContentUrl as p,fetchContent as m,withRetry as v}from"../helpers/helpers.js";import b from"../helpers/state.js";import"@descope/escape-markdown";import"../helpers/webauthn.js";import{setCustomStorage as w}from"../helpers/storage.js";import{transformFlowInputFormData as k,extractNestedAttribute as y}from"../helpers/flowInputs.js";import{formMountMixin as C}from"../mixins/formMountMixin.js";import{componentConditionsMixin as x}from"../mixins/componentConditionsMixin.js";import{duplicateFlowWarningMixin as A}from"../mixins/duplicateFlowWarningMixin.js";import{passwordManagerMixin as j}from"../mixins/passwordManagerMixin.js";import{validationTrackingMixin as I}from"../mixins/validationTrackingMixin.js";import{CONFIG_FILENAME as E,PREV_VER_ASSETS_FOLDER as M}from"../constants/content.js";import{FETCH_EXCEPTION_ERROR_CODE as S}from"../constants/general.js";var L,U,O,W,P,D,N,T,F,K,R,z,J,V,B,H,q,$,Q,G,X,Y,Z,_,tt,et;const it=s(o,r,C,x,A,j,n,a,I)(HTMLElement);class st extends it{static get observedAttributes(){return["project-id","flow-id","base-url","tenant","locale","debug","storage-prefix","preview","redirect-url","auto-focus","store-last-authenticated-user","refresh-cookie-name","keep-last-authenticated-user-after-logout","validate-on-blur","send-session-token","style-id"]}constructor(s){super(),L.add(this),this.sdkVersion="4.4.6",O.set(this,!1),W.set(this,void 0),this.flowStatus="initial",this.loggerWrapper={error:(e,i="")=>{this.logger.error(e,i,new Error),t(this,L,"m",et).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)}},P.set(this,new b),D.set(this,new b),N.set(this,{}),this.getComponentsContext=()=>t(this,N,"f"),this.nextRequestStatus=new b({isLoading:!1}),T.set(this,void 0),F.set(this,{popstate:t(this,L,"m",V).bind(this),componentsContext:t(this,L,"m",G).bind(this)}),K.set(this,void 0),this.getConfig=()=>e(this,void 0,void 0,(function*(){return(yield this.config)||{isMissingConfig:!0}})),X.set(this,void 0),Y.set(this,void 0),i(this,K,s,"f"),t(this,L,"m",z).call(this)}get client(){try{return JSON.parse(this.getAttribute("client"))||{}}catch(t){return{}}}get redirectUrl(){return this.getAttribute("redirect-url")||void 0}get debug(){return"true"===this.getAttribute("debug")}get locale(){return this.getAttribute("locale")||void 0}get autoFocus(){var t;const e=null!==(t=this.getAttribute("auto-focus"))&&void 0!==t?t:"true";return"skipFirstScreen"===e?e:"true"===e}get validateOnBlur(){return"true"===this.getAttribute("validate-on-blur")}get storeLastAuthenticatedUser(){var t;return"true"===(null!==(t=this.getAttribute("store-last-authenticated-user"))&&void 0!==t?t:"true")}get refreshCookieName(){return this.getAttribute("refresh-cookie-name")||""}get keepLastAuthenticatedUserAfterLogout(){return"true"===this.getAttribute("keep-last-authenticated-user-after-logout")}get storagePrefix(){return this.getAttribute("storage-prefix")||""}get sendSessionToken(){return"true"===this.getAttribute("send-session-token")}get preview(){return!!this.getAttribute("preview")}get formConfig(){return k(this.form)}get form(){return this.getAttribute("form")}get formConfigValues(){return y(this.formConfig,"value")}get outboundAppId(){return this.getAttribute("outbound-app-id")}get outboundAppScopes(){try{const t=JSON.parse(this.getAttribute("outbound-app-scopes"));return t||null}catch(t){return null}}get popupOrigin(){return this.getAttribute("popup-origin")}get customStorage(){return t(this,W,"f")}set customStorage(t){if(t&&"function"!=typeof t.getItem)throw new Error("Custom storage must have a getItem method");if(t&&"function"!=typeof t.setItem)throw new Error("Custom storage must have a setItem method");if(t&&"function"!=typeof t.removeItem)throw new Error("Custom storage must have a removeItem method");i(this,W,t,"f"),w(t)}get lazyStart(){return"true"===this.getAttribute("lazy-start")}start(){var e;null===(e=t(this,Y,"f"))||void 0===e||e.call(this),i(this,X,Promise.resolve(),"f")}get isRestartOnError(){return"true"===this.getAttribute("restart-on-error")}getExecutionContext(){return e(this,void 0,void 0,(function*(){const t=yield this.getConfig();return"executionContext"in t?t.executionContext:void 0}))}getProjectConfig(){return e(this,void 0,void 0,(function*(){const t=yield this.getConfig();return"projectConfig"in t?t.projectConfig:void 0}))}getFlowConfig(){return e(this,void 0,void 0,(function*(){var t,e;const i=yield this.getProjectConfig(),s=(null===(t=null==i?void 0:i.flows)||void 0===t?void 0:t[this.flowId])||{};return null!==(e=s.version)&&void 0!==e||(s.version=0),s}))}getTargetLocales(){return e(this,void 0,void 0,(function*(){const t=yield this.getFlowConfig();return((null==t?void 0:t.targetLocales)||[]).map((t=>t.toLowerCase()))}))}handleKeyPress(){this.logger.debug("Enable key press handler"),this.rootElement.onkeydown=t=>{var e,i,s;const r=!!(null===(e=this.shadowRoot.activeElement)||void 0===e?void 0:e.getAttribute("href")),o=d.includes(null!==(s=null===(i=this.shadowRoot.activeElement)||void 0===i?void 0:i.localName)&&void 0!==s?s:"");if("Enter"!==t.key||r||o)return;t.preventDefault();const n=this.rootElement.querySelectorAll("descope-button");if(1===n.length&&"false"!==n[0].getAttribute("auto-submit"))return void n[0].click();const a=Array.from(n).filter((t=>"true"===t.getAttribute("auto-submit")));if(1===a.length)return void a[0].click();const u=Array.from(n).filter((t=>"button"===t.getAttribute("data-type")));if(1===u.length)"false"!==u[0].getAttribute("auto-submit")&&u[0].click();else if(0===u.length){const t=Array.from(n).filter((t=>"sso"===t.getAttribute("data-type")));1===t.length&&"false"!==t[0].getAttribute("auto-submit")&&t[0].click()}}}disableKeyPressHandler(){this.logger.debug("Disable key press handler"),this.rootElement.onkeydown=null}getComponentsVersion(){return e(this,void 0,void 0,(function*(){var t;const e=yield this.getConfig(),i="projectConfig"in e?null===(t=e.projectConfig)||void 0===t?void 0:t.componentsVersion:{};return i||(this.logger.error("Did not get components version, using latest version"),"latest")}))}init(){const s=Object.create(null,{init:{get:()=>super.init}});return e(this,void 0,void 0,(function*(){var e;if(this.flowStatus="loading",["ready","error","success"].forEach((t=>this.addEventListener(t,(()=>{this.flowStatus=t})))),yield null===(e=s.init)||void 0===e?void 0:e.call(this),t(this,D,"f").subscribe(t(this,L,"m",tt).bind(this)),t(this,D,"f").update({isDebug:this.debug}),t(this,L,"m",J).call(this),yield t(this,L,"m",$).call(this))return void this.loggerWrapper.error("This SDK version does not support your flows version","Make sure to upgrade your flows to the latest version or use an older SDK version");const r=yield this.getConfig();if("isMissingConfig"in r&&r.isMissingConfig)return void this.loggerWrapper.error("Cannot get config file","Make sure that your projectId & flowId are correct");const{executionId:o,stepId:n,token:a,code:u,isPopup:l,exchangeError:d,redirectAuthCallbackUrl:c,redirectAuthBackupCallbackUri:f,redirectAuthCodeChallenge:g,redirectAuthInitiator:p,ssoQueryParams:m}=h(this.flowId,this.loggerWrapper);window.addEventListener("popstate",t(this,F,"f").popstate),window.addEventListener("components-context",t(this,F,"f").componentsContext),t(this,P,"f").subscribe(t(this,L,"m",q).bind(this)),t(this,P,"f").update(Object.assign({projectId:this.projectId,flowId:this.flowId,baseUrl:this.baseUrl,tenant:this.tenantId,redirectUrl:this.redirectUrl,locale:this.locale,stepId:n,executionId:o,token:a,code:u,isPopup:l,exchangeError:d,redirectAuthCallbackUrl:c,redirectAuthBackupCallbackUri:f,redirectAuthCodeChallenge:g,redirectAuthInitiator:p},m)),i(this,O,!0,"f")}))}disconnectedCallback(){var e;t(this,P,"f").unsubscribeAll(),t(this,D,"f").unsubscribeAll(),t(this,L,"m",_).call(this),window.removeEventListener("popstate",t(this,F,"f").popstate),window.removeEventListener("components-context",t(this,F,"f").componentsContext),null===(e=super.disconnectedCallback)||void 0===e||e.call(this)}attributeChangedCallback(e,i,s){var r;if(null===(r=super.attributeChangedCallback)||void 0===r||r.call(this,e,i,s),this.shadowRoot.isConnected&&t(this,O,"f")&&i!==s&&U.observedAttributes.includes(e)){t(this,L,"m",J).call(this);const r=null===i;t(this,P,"f").update((({stepId:t,executionId:i})=>{let o=t,n=i;return r||(n=null,o=null,c()),{[f(e)]:s,stepId:o,executionId:n}})),t(this,D,"f").update({isDebug:this.debug})}}}U=st,O=new WeakMap,W=new WeakMap,P=new WeakMap,D=new WeakMap,N=new WeakMap,T=new WeakMap,F=new WeakMap,K=new WeakMap,X=new WeakMap,Y=new WeakMap,L=new WeakSet,R=function(){this.injectStyle("\n :host {\n\t\t\twidth: 100%;\n display: block;\n\t\t}\n\n\t\t#root {\n\t\t\theight: 100%;\n display: flex;\n flex-direction: column;\n\t\t}\n\n #content-root {\n all: initial;\n transition: opacity 200ms ease-in-out;\n }\n\n\t\t#root[data-theme] {\n\t\t\tbackground-color: transparent;\n\t\t}\n\n\t\t.fade-out {\n\t\t\topacity: 0.1!important;\n\t\t}\n\n .hidden {\n display: none;\n }\n ")},z=function(){t(this,L,"m",R).call(this),this.slotElement=document.createElement("slot"),this.slotElement.classList.add("hidden"),this.rootElement.appendChild(this.slotElement)},J=function(){const t=["base-url","tenant","locale","debug","redirect-url","auto-focus","store-last-authenticated-user","refresh-cookie-name","keep-last-authenticated-user-after-logout","preview","storage-prefix","form","client","validate-on-blur","send-session-token","style-id","outbound-app-id","outbound-app-scopes","theme-override"];U.observedAttributes.forEach((e=>{if(!t.includes(e)&&!this[f(e)])throw Error(`${e} cannot be empty`)}))},V=function(){const{stepId:e,executionId:i}=g(this.flowId);t(this,P,"f").update({stepId:e,executionId:i})},B=function(i,s){u&&"function"==typeof u||this.logger.error("SDK was not loaded properly",u,JSON.stringify(u));const r=Object.assign(Object.assign({persistTokens:!0,preview:this.preview,storagePrefix:this.storagePrefix,storeLastAuthenticatedUser:this.storeLastAuthenticatedUser,keepLastAuthenticatedUserAfterLogout:this.keepLastAuthenticatedUserAfterLogout,refreshCookieName:this.refreshCookieName},U.sdkConfigOverrides),{projectId:i,baseUrl:s});t(this,W,"f")&&(r.customStorage=t(this,W,"f")),this.sdk=u(r);const o={start:1,next:7};["start","next"].forEach((i=>{const s=this.sdk.flow[i],r=v(s,1e3,3);this.sdk.flow[i]=(...s)=>e(this,void 0,void 0,(function*(){const e=[...s],n=o[i],a=t(this,L,"m",H).call(this,e[n]);void 0!==a&&(e[n]=a);try{return yield r(...e)}catch(t){return this.logger.error(`Error in sdk flow ${i} function`,t),{error:{errorCode:S,errorDescription:t.toString()}}}}))}));const n=this.sdk.flow.start;this.sdk.flow.start=(...i)=>e(this,void 0,void 0,(function*(){return yield t(this,L,"m",Z).call(this),n.apply(this.sdk.flow,i)}))},H=function(t){if(!this.sendSessionToken)return t;const e=null==l?void 0:l(this.storagePrefix);return e?Object.assign(Object.assign({},null!=t?t:{}),{sessionJwt:e}):t},q=function(i,s,r){return e(this,void 0,void 0,(function*(){const{projectId:e,baseUrl:s}=i;if(r("projectId")||r("baseUrl")){if(!e)return;t(this,L,"m",B).call(this,e,s)}t(this,K,"f").call(this,i)}))},$=function(){return e(this,void 0,void 0,(function*(){const e=yield this.getConfig();return"isMissingConfig"in e&&e.isMissingConfig&&(yield t(this,L,"m",Q).call(this))}))},Q=function(){return e(this,void 0,void 0,(function*(){const t=p({projectId:this.projectId,filename:E,assetsFolder:M,baseUrl:this.baseStaticUrl});try{return yield m(t,"json"),!0}catch(t){return!1}}))},G=function(e){i(this,N,Object.assign(Object.assign({},t(this,N,"f")),e.detail),"f")},Z=function(){return this.lazyStart?(t(this,X,"f")||i(this,X,new Promise((t=>{i(this,Y,t,"f")})),"f"),t(this,X,"f")):Promise.resolve()},_=function(){var e;null===(e=t(this,T,"f"))||void 0===e||e.remove(),i(this,T,null,"f")},tt=function(s){return e(this,arguments,void 0,(function*({isDebug:e}){e?(i(this,T,document.createElement("descope-debugger"),"f"),Object.assign(t(this,T,"f").style,{position:"fixed",top:"0",right:"0",height:"100vh",width:"100vw",pointerEvents:"none",zIndex:99999}),yield import("../debugger-wc.js"),document.body.appendChild(t(this,T,"f"))):t(this,L,"m",_).call(this)}))},et=function(e,i){var s;e&&this.debug&&(null===(s=t(this,T,"f"))||void 0===s||s.updateData({title:e,description:i}))},st.sdkConfigOverrides={baseHeaders:{"x-descope-sdk-name":"web-component","x-descope-sdk-version":"4.4.6"}};export{st as default};
|
|
2
2
|
//# sourceMappingURL=BaseDescopeWc.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{__classPrivateFieldGet as e,__classPrivateFieldSet as
|
|
1
|
+
import{__classPrivateFieldGet as e,__classPrivateFieldSet as n}from"tslib";import{createSingletonMixin as t,compose as o}from"@descope/sdk-helpers";import{loggerMixin as i}from"@descope/sdk-mixins";import{REALTIME_CONDITION_EVENTS as s,REALTIME_CONDITION_DEBOUNCE_MS as r}from"../helpers/realtime-conditions/config.js";import{collectReferencedFormKeys as l,collectTouchedComponentIds as c,evaluateAll as u}from"../helpers/realtime-conditions/evaluator.js";import{COMPONENT_ACTIONS as a,apply as d,escapeSelector as m}from"../helpers/realtime-conditions/applier.js";import{DESCOPE_ATTRIBUTE_EXCLUDE_FIELD as h}from"../constants/index.js";const p="component-conditions:";function f(e){return e instanceof HTMLInputElement?"checkbox"===e.type?e.checked:e.value:"checked"in e?e.checked:"value"in e?e.value:void 0}function b(e,n){const t=Object.keys(e),o=Object.keys(n);return t.length===o.length&&t.every((t=>e[t]===n[t]))}function v(){return{conditions:[],touchedIds:new Set,snapshot:{},applied:{},serverBaseline:{},debounceTimer:null,paused:!1,unsubscribePauseListener:null,inputHandler:()=>{},root:null}}function g(e,n,t){const o={};return t.forEach((t=>{e[t]?o[t]=e[t]:n[t]&&(o[t]=n[t])})),o}const $=t((t=>{var $,T,k,y,j,E;const O=o(i)(t);return E=class extends O{constructor(){super(...arguments),$.add(this),T.set(this,v())}applyComponentsState(e,n){n&&(Object.entries(n).forEach((([e,n])=>{a.includes(n)||this.logger.error(`Unknown component action "${n}" for component with id "${e}"`,`Valid actions are ${a.map((e=>`"${e}"`)).join(", ")}`)})),d(e,{},n))}initRealtimeConditions(t,o){var i,r,a,h;e(this,$,"m",j).call(this);const v=null!==(i=null==o?void 0:o.realtimeComponentsConditions)&&void 0!==i?i:[];if(!v.length)return void this.logger.debug(`${p} no real-time rules to apply on this screen`);this.logger.info(`${p} found ${v.length} real-time rule(s) for this screen`);const y={};Object.entries(null!==(r=null==o?void 0:o.form)&&void 0!==r?r:{}).forEach((([e,n])=>{y[`form.${e}`]=n})),l(v).forEach((e=>{const n=function(e,n){const t=n.startsWith("form.")?n.slice(5):n;return e.querySelector(`[name="${m(n)}"]`)||e.querySelector(`[name="${m(t)}"]`)}(t,e);if(!n)return;const o=f(n);void 0!==o&&(y[e]=o)}));const E=c(v),O={},S={};Object.entries(null!==(a=null==o?void 0:o.componentsState)&&void 0!==a?a:{}).forEach((([e,n])=>{E.has(e)&&(S[e]=n)})),Object.entries(null!==(h=null==o?void 0:o.serverOnlyComponentsState)&&void 0!==h?h:{}).forEach((([e,n])=>{E.has(e)&&(O[e]=n)}));const L={conditions:v,touchedIds:E,snapshot:y,applied:S,serverBaseline:O,debounceTimer:null,paused:!1,unsubscribePauseListener:null,inputHandler:()=>{},root:t},w=g(u(v,y),O,E);b(S,w)||(L.applied=d(t,S,w)),L.inputHandler=n=>e(this,$,"m",k).call(this,n),s.forEach((e=>{t.addEventListener(e,L.inputHandler,!0)})),this.logger.debug(`${p} listening for "${s.join('" and "')}" events on form fields; ${Object.keys(S).length} component(s) start hidden / disabled / read-only by these rules`);const C=this.nextRequestStatus;if(null==C?void 0:C.subscribe){const e=({isLoading:e})=>{L.paused=e,e&&L.debounceTimer&&(clearTimeout(L.debounceTimer),L.debounceTimer=null)},n=C.subscribe(e);L.unsubscribePauseListener=()=>{var e;null!=n&&(null===(e=C.unsubscribe)||void 0===e||e.call(C,n))}}n(this,T,L,"f")}disconnectedCallback(){var n;null===(n=super.disconnectedCallback)||void 0===n||n.call(this),e(this,$,"m",j).call(this)}},T=new WeakMap,$=new WeakSet,k=function(n){var t,o;const i=e(this,T,"f");if(!i.root||i.paused)return;const s=n.target;if(!s)return;if(null===(t=s.hasAttribute)||void 0===t?void 0:t.call(s,h))return;const l=null===(o=s.getAttribute)||void 0===o?void 0:o.call(s,"name");if(!l)return;const c=function(e){return e.startsWith("form.")?e:`form.${e}`}(l);i.snapshot[c]=f(s),i.debounceTimer&&clearTimeout(i.debounceTimer),i.debounceTimer=setTimeout((()=>{i.debounceTimer=null,e(this,$,"m",y).call(this)}),r)},y=function(){const n=e(this,T,"f");if(!n.root)return;let t;try{t=g(u(n.conditions,n.snapshot),n.serverBaseline,n.touchedIds)}catch(e){return void this.logger.error(`${p} failed to evaluate real-time rules — keeping the previous state`,null==e?void 0:e.message)}const o=n.applied;b(o,t)||(this.logger.debug(`${p} form changed — updating components: was ${JSON.stringify(o)}, now ${JSON.stringify(t)}`),n.applied=d(n.root,o,t))},j=function(){const t=e(this,T,"f");t.debounceTimer&&clearTimeout(t.debounceTimer),t.unsubscribePauseListener&&t.unsubscribePauseListener(),t.root&&s.forEach((e=>{t.root.removeEventListener(e,t.inputHandler,!0)})),n(this,T,v(),"f")},E}));export{$ as componentConditionsMixin};
|
|
2
2
|
//# sourceMappingURL=componentConditionsMixin.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"componentConditionsMixin.js","sources":["../../../src/lib/mixins/componentConditionsMixin.ts"],"sourcesContent":["/* eslint-disable import/prefer-default-export, no-param-reassign */\nimport { compose, createSingletonMixin } from '@descope/sdk-helpers';\nimport { loggerMixin } from '@descope/sdk-mixins';\nimport {\n REALTIME_CONDITION_DEBOUNCE_MS,\n REALTIME_CONDITION_EVENTS,\n} from '../helpers/realtime-conditions/config';\nimport {\n collectReferencedFormKeys,\n collectTouchedComponentIds,\n evaluateAll,\n FormSnapshot,\n} from '../helpers/realtime-conditions/evaluator';\nimport {\n apply,\n COMPONENT_ACTIONS,\n escapeSelector,\n} from '../helpers/realtime-conditions/applier';\nimport { DESCOPE_ATTRIBUTE_EXCLUDE_FIELD } from '../constants';\nimport type { RealtimeComponentsCondition, ScreenState } from '../types';\n\nconst LOG_PREFIX = 'component-conditions:';\n\n// What the mixin needs from its host: a way to subscribe to loading state\n// so input handling can pause while the next request is in flight. Defined\n// as an interface (not imported) to avoid a circular dependency on BaseDescopeWc.\nexport interface PausableHost {\n nextRequestStatus?: {\n // subscribe returns a token; pass that token to unsubscribe — not the handler.\n subscribe: (cb: (v: { isLoading: boolean }) => void) => string;\n unsubscribe?: (token: string) => void;\n };\n}\n\nexport interface RealtimeRuntime {\n conditions: RealtimeComponentsCondition[];\n // IDs of components that any rule can change\n touchedIds: Set<string>;\n // latest form values on screen\n snapshot: FormSnapshot;\n // what's currently applied on screen for touched components.\n // Compared against on each re-evaluation to know what to change.\n applied: Record<string, string>;\n // What the server told us to apply for these components. Stays fixed for\n // the screen's lifetime so we can fall back to it when a real-time rule\n // stops matching. Without this, a server-set action could disappear when\n // a real-time rule briefly fires on the same component.\n serverBaseline: Record<string, string>;\n debounceTimer: ReturnType<typeof setTimeout> | null;\n // true while paused (during submit, to avoid stale updates)\n paused: boolean;\n unsubscribePauseListener: (() => void) | null;\n // the listener we attach to form events (kept so we can detach)\n inputHandler: (e: Event) => void;\n // the screen root we work against\n root: HTMLElement | null;\n}\n\n// Some inputs already have `name=\"form.x\"`, others use `name=\"x\"`. Always\n// return the `form.x` form so it lines up with what rules reference.\nfunction toFormKey(name: string): string {\n return name.startsWith('form.') ? name : `form.${name}`;\n}\n\n// Try the full `form.x` first (descope components), then `x` (plain inputs).\nfunction findInputForFormKey(\n root: ParentNode,\n formKey: string,\n): Element | null {\n const bare = formKey.startsWith('form.')\n ? formKey.slice('form.'.length)\n : formKey;\n return (\n root.querySelector(`[name=\"${escapeSelector(formKey)}\"]`) ||\n root.querySelector(`[name=\"${escapeSelector(bare)}\"]`)\n );\n}\n\n// Read the current value off a form input. Reads JS properties (not HTML\n// attributes) so we pick up both the component's default and any value\n// carried over from earlier screens.\n//\n// Native <input type=checkbox> needs special handling: `.value` is always\n// \"on\", only `.checked` reflects the real state. Descope boolean components\n// (descope-checkbox, descope-switch-toggle) expose `.checked` on their class.\nfunction readInputValue(el: Element): unknown {\n if (el instanceof HTMLInputElement) {\n return el.type === 'checkbox' ? el.checked : el.value;\n }\n if ('checked' in el) {\n return (el as unknown as { checked: boolean }).checked;\n }\n if ('value' in el) {\n return (el as unknown as { value: unknown }).value;\n }\n return undefined;\n}\n\nfunction shallowEqualStringMap(\n a: Record<string, string>,\n b: Record<string, string>,\n): boolean {\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n if (keysA.length !== keysB.length) return false;\n return keysA.every((k) => a[k] === b[k]);\n}\n\nfunction emptyRuntime(): RealtimeRuntime {\n return {\n conditions: [],\n touchedIds: new Set(),\n snapshot: {},\n applied: {},\n serverBaseline: {},\n debounceTimer: null,\n paused: false,\n unsubscribePauseListener: null,\n inputHandler: () => {},\n root: null,\n };\n}\n\n// For each touched component, pick the real-time action if a rule is firing\n// for it, otherwise fall back to the server's action. Components that no rule\n// touches are not in the result — those were already painted by\n// applyComponentsState.\nfunction effectiveActions(\n realtimeVerdict: Record<string, string>,\n serverBaseline: Record<string, string>,\n touchedIds: Set<string>,\n): Record<string, string> {\n const out: Record<string, string> = {};\n touchedIds.forEach((id) => {\n if (realtimeVerdict[id]) {\n out[id] = realtimeVerdict[id];\n } else if (serverBaseline[id]) {\n out[id] = serverBaseline[id];\n }\n });\n return out;\n}\n\nexport const componentConditionsMixin = createSingletonMixin(\n <T extends CustomElementConstructor>(superclass: T) => {\n // Pull in loggerMixin so `this.logger` is available no matter where\n // this mixin sits in the chain.\n const BaseClass = compose(loggerMixin)(superclass);\n\n return class ComponentConditionsMixin extends BaseClass {\n // One runtime per <descope-wc> element.\n #rtRuntime: RealtimeRuntime = emptyRuntime();\n\n /**\n * Apply the server's hide/disable/read-only actions to the DOM.\n * Logs unknown actions here (runs once per screen) but stays quiet on\n * the keystroke path to avoid log spam.\n */\n applyComponentsState(\n root: ParentNode,\n componentsState: Record<string, string> | undefined,\n ): void {\n if (!componentsState) return;\n Object.entries(componentsState).forEach(([id, action]) => {\n if (!(COMPONENT_ACTIONS as readonly string[]).includes(action)) {\n this.logger.error(\n `Unknown component action \"${action}\" for component with id \"${id}\"`,\n `Valid actions are ${COMPONENT_ACTIONS.map((a) => `\"${a}\"`).join(\n ', ',\n )}`,\n );\n }\n });\n apply(root, {}, componentsState);\n }\n\n /**\n * Set up real-time conditions for the current screen. Safe to call\n * twice — a second call rebuilds from screenState.\n *\n * Must run AFTER `updateScreenFromScreenState`, so the DOM reads below\n * see both server-shipped values and any component defaults from the\n * HTML.\n */\n initRealtimeConditions(\n rootElement: HTMLElement,\n screenState: ScreenState | undefined,\n ): void {\n this.#teardownRealtimeRuntime();\n\n const conditions = screenState?.realtimeComponentsConditions ?? [];\n if (!conditions.length) {\n this.logger.debug(\n `${LOG_PREFIX} no real-time rules to apply on this screen`,\n );\n return;\n }\n this.logger.info(\n `${LOG_PREFIX} found ${conditions.length} real-time rule(s) for this screen`,\n );\n\n // screenState.form uses \"phone\"; rules reference \"form.phone\".\n // Add the prefix on the way in.\n const initialSnapshot: FormSnapshot = {};\n Object.entries(screenState?.form ?? {}).forEach(([k, v]) => {\n initialSnapshot[`form.${k}`] = v;\n });\n\n // For every key the rules reference, read the current DOM value.\n // Component defaults (e.g. `checked=\"true\"` on a descope-checkbox)\n // live only in the HTML and don't make it into screenState.form, so\n // without this read the first evaluation would miss them.\n collectReferencedFormKeys(conditions).forEach((formKey) => {\n const el = findInputForFormKey(rootElement, formKey);\n if (!el) return;\n const v = readInputValue(el);\n if (v !== undefined) initialSnapshot[formKey] = v;\n });\n\n const touchedIds = collectTouchedComponentIds(conditions);\n\n // What to fall back to when a real-time rule stops matching for a\n // touched component — the actions set by server-only rules (rules\n // with no client-side conditions).\n const serverBaseline: Record<string, string> = {};\n // What's already painted on the DOM (touched components only), so\n // the first real-time evaluation can diff against the right state.\n const initialApplied: Record<string, string> = {};\n\n Object.entries(screenState?.componentsState ?? {}).forEach(\n ([id, action]) => {\n if (!touchedIds.has(id)) return;\n initialApplied[id] = action;\n },\n );\n\n Object.entries(screenState?.serverOnlyComponentsState ?? {}).forEach(\n ([id, action]) => {\n if (touchedIds.has(id)) {\n serverBaseline[id] = action;\n }\n },\n );\n\n const runtime: RealtimeRuntime = {\n conditions,\n touchedIds,\n snapshot: initialSnapshot,\n applied: initialApplied,\n serverBaseline,\n debounceTimer: null,\n paused: false,\n unsubscribePauseListener: null,\n inputHandler: () => {},\n root: rootElement,\n };\n\n // Re-run the rules now that we've read the real DOM values. The\n // server evaluated without seeing component defaults, so its\n // `componentsState` can disagree with what the user actually sees.\n // Apply the diff once before listening for input.\n const reconciled = effectiveActions(\n evaluateAll(conditions, initialSnapshot),\n serverBaseline,\n touchedIds,\n );\n if (!shallowEqualStringMap(initialApplied, reconciled)) {\n runtime.applied = apply(rootElement, initialApplied, reconciled);\n }\n\n runtime.inputHandler = (e: Event) =>\n this.#handleRealtimeInput(e as InputEvent);\n\n REALTIME_CONDITION_EVENTS.forEach((ev) => {\n rootElement.addEventListener(ev, runtime.inputHandler, true);\n });\n this.logger.debug(\n `${LOG_PREFIX} listening for \"${REALTIME_CONDITION_EVENTS.join(\n '\" and \"',\n )}\" events on form fields; ${\n Object.keys(initialApplied).length\n } component(s) start hidden / disabled / read-only by these rules`,\n );\n\n // Pause while a /next request is in flight. Without this, a debounced\n // evaluation could run between submit and the next screen render and\n // change components that are about to be replaced — causing flicker,\n // or hiding something the next screen needs visible.\n const pauseState = (this as unknown as PausableHost).nextRequestStatus;\n if (pauseState?.subscribe) {\n const handler = ({ isLoading }: { isLoading: boolean }) => {\n runtime.paused = isLoading;\n if (isLoading && runtime.debounceTimer) {\n clearTimeout(runtime.debounceTimer);\n runtime.debounceTimer = null;\n }\n };\n // subscribe returns a token; unsubscribe needs that token, not the\n // handler. Without storing it, handlers leak across screens and\n // keep old runtimes (and their DOM roots) alive.\n const token = pauseState.subscribe(handler);\n runtime.unsubscribePauseListener = () => {\n if (token !== undefined && token !== null) {\n pauseState.unsubscribe?.(token);\n }\n };\n }\n\n this.#rtRuntime = runtime;\n }\n\n #handleRealtimeInput(e: InputEvent): void {\n const runtime = this.#rtRuntime;\n if (!runtime.root || runtime.paused) return;\n\n const target = e.target as Element | null;\n if (!target) return;\n if (target.hasAttribute?.(DESCOPE_ATTRIBUTE_EXCLUDE_FIELD)) return;\n\n const name = target.getAttribute?.('name');\n if (!name) return;\n\n // Update the snapshot only — evaluation is debounced. Use readInputValue\n // so checkboxes read the same way as at mount; otherwise `target.value`\n // would be the string \"on\" for native checkboxes and break is-true rules.\n const key = toFormKey(name);\n runtime.snapshot[key] = readInputValue(target);\n\n if (runtime.debounceTimer) {\n clearTimeout(runtime.debounceTimer);\n }\n runtime.debounceTimer = setTimeout(() => {\n runtime.debounceTimer = null;\n this.#reEvaluateRealtime();\n }, REALTIME_CONDITION_DEBOUNCE_MS);\n }\n\n #reEvaluateRealtime(): void {\n const runtime = this.#rtRuntime;\n if (!runtime.root) return;\n\n let next: Record<string, string>;\n try {\n next = effectiveActions(\n evaluateAll(runtime.conditions, runtime.snapshot),\n runtime.serverBaseline,\n runtime.touchedIds,\n );\n } catch (e) {\n this.logger.error(\n `${LOG_PREFIX} failed to evaluate real-time rules — keeping the previous state`,\n (e as Error)?.message,\n );\n return;\n }\n\n const prevApplied = runtime.applied;\n if (shallowEqualStringMap(prevApplied, next)) return;\n\n this.logger.debug(\n `${LOG_PREFIX} form changed — updating components: was ${JSON.stringify(\n prevApplied,\n )}, now ${JSON.stringify(next)}`,\n );\n runtime.applied = apply(runtime.root, prevApplied, next);\n }\n\n // Clean up listeners and timers when the host leaves the DOM. Reaches\n // us only if BaseDescopeWc calls `super.disconnectedCallback?.()`;\n // otherwise teardown happens lazily on the next initRealtimeConditions.\n disconnectedCallback() {\n // disconnectedCallback isn't on HTMLElement in the lib types, but it\n // exists at runtime — forward into super in case the chain uses it.\n super.disconnectedCallback?.();\n this.#teardownRealtimeRuntime();\n }\n\n #teardownRealtimeRuntime(): void {\n const r = this.#rtRuntime;\n if (r.debounceTimer) {\n clearTimeout(r.debounceTimer);\n }\n if (r.unsubscribePauseListener) {\n r.unsubscribePauseListener();\n }\n if (r.root) {\n // Undo anything we applied so the next screen starts clean. Skip\n // if the root is already gone (replaced by the next screen) —\n // nothing left to undo.\n if (Object.keys(r.applied).length > 0 && r.root.isConnected) {\n apply(r.root, r.applied, {});\n }\n REALTIME_CONDITION_EVENTS.forEach((ev) => {\n r.root!.removeEventListener(ev, r.inputHandler, true);\n });\n }\n this.#rtRuntime = emptyRuntime();\n }\n };\n },\n);\n"],"names":["LOG_PREFIX","readInputValue","el","HTMLInputElement","type","checked","value","shallowEqualStringMap","a","b","keysA","Object","keys","keysB","length","every","k","emptyRuntime","conditions","touchedIds","Set","snapshot","applied","serverBaseline","debounceTimer","paused","unsubscribePauseListener","inputHandler","root","effectiveActions","realtimeVerdict","out","forEach","id","componentConditionsMixin","createSingletonMixin","superclass","BaseClass","compose","loggerMixin","_a","constructor","_ComponentConditionsMixin_rtRuntime","set","this","applyComponentsState","componentsState","entries","action","COMPONENT_ACTIONS","includes","logger","error","map","join","apply","initRealtimeConditions","rootElement","screenState","__classPrivateFieldGet","_ComponentConditionsMixin_instances","_ComponentConditionsMixin_teardownRealtimeRuntime","call","_b","realtimeComponentsConditions","debug","info","initialSnapshot","_c","form","v","collectReferencedFormKeys","formKey","bare","startsWith","slice","querySelector","escapeSelector","findInputForFormKey","undefined","collectTouchedComponentIds","initialApplied","_d","has","_e","serverOnlyComponentsState","runtime","reconciled","evaluateAll","e","REALTIME_CONDITION_EVENTS","ev","addEventListener","pauseState","nextRequestStatus","subscribe","handler","isLoading","clearTimeout","token","unsubscribe","__classPrivateFieldSet","disconnectedCallback","super","target","hasAttribute","DESCOPE_ATTRIBUTE_EXCLUDE_FIELD","name","getAttribute","key","toFormKey","setTimeout","_ComponentConditionsMixin_reEvaluateRealtime","REALTIME_CONDITION_DEBOUNCE_MS","next","message","prevApplied","JSON","stringify","r","isConnected","removeEventListener"],"mappings":"6nBAqBA,MAAMA,EAAa,wBAgEnB,SAASC,EAAeC,GACtB,OAAIA,aAAcC,iBACG,aAAZD,EAAGE,KAAsBF,EAAGG,QAAUH,EAAGI,MAE9C,YAAaJ,EACPA,EAAuCG,QAE7C,UAAWH,EACLA,EAAqCI,WAD/C,CAIF,CAEA,SAASC,EACPC,EACAC,GAEA,MAAMC,EAA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ACnD,CAuQoBG,CAAUH,GACtBrB,EAAQjE,SAASwF,GAAO5G,EAAeuG,GAEnClB,EAAQ9D,eACV0E,aAAaZ,EAAQ9D,eAEvB8D,EAAQ9D,cAAgBuF,YAAW,KACjCzB,EAAQ9D,cAAgB,KACxBmC,EAAAf,KAAIgB,EAAA,IAAAoD,GAAJlD,KAAAlB,KAA0B,GACzBqE,EACJ,eAGC,MAAM3B,EAAU3B,EAAAf,YAChB,IAAK0C,EAAQ1D,KAAM,OAEnB,IAAIsF,EACJ,IACEA,EAAOrF,EACL2D,EAAYF,EAAQpE,WAAYoE,EAAQjE,UACxCiE,EAAQ/D,eACR+D,EAAQnE,WAEX,CAAC,MAAOsE,GAKP,YAJA7C,KAAKO,OAAOC,MACV,GAAGpD,oEACFyF,aAAC,EAADA,EAAa0B,QAGjB,CAED,MAAMC,EAAc9B,EAAQhE,QACxBf,EAAsB6G,EAAaF,KAEvCtE,KAAKO,OAAOc,MACV,GAAGjE,6CAAsDqH,KAAKC,UAC5DF,WACQC,KAAKC,UAAUJ,MAE3B5B,EAAQhE,QAAUiC,EAAM+B,EAAQ1D,KAAMwF,EAAaF,GACpD,eAaC,MAAMK,EAAI5D,EAAAf,YACN2E,EAAE/F,eACJ0E,aAAaqB,EAAE/F,eAEb+F,EAAE7F,0BACJ6F,EAAE7F,2BAEA6F,EAAE3F,OAIAjB,OAAOC,KAAK2G,EAAEjG,SAASR,OAAS,GAAKyG,EAAE3F,KAAK4F,aAC9CjE,EAAMgE,EAAE3F,KAAM2F,EAAEjG,QAAS,CAAE,GAE7BoE,EAA0B1D,SAAS2D,IACjC4B,EAAE3F,KAAM6F,oBAAoB9B,EAAI4B,EAAE5F,cAAc,EAAK,KAGzD0E,EAAAzD,KAAIF,EAAczB,QACnB,EACDuB,CAAA"}
|
|
1
|
+
{"version":3,"file":"componentConditionsMixin.js","sources":["../../../src/lib/mixins/componentConditionsMixin.ts"],"sourcesContent":["/* eslint-disable import/prefer-default-export, no-param-reassign */\nimport { compose, createSingletonMixin } from '@descope/sdk-helpers';\nimport { loggerMixin } from '@descope/sdk-mixins';\nimport {\n REALTIME_CONDITION_DEBOUNCE_MS,\n REALTIME_CONDITION_EVENTS,\n} from '../helpers/realtime-conditions/config';\nimport {\n collectReferencedFormKeys,\n collectTouchedComponentIds,\n evaluateAll,\n FormSnapshot,\n} from '../helpers/realtime-conditions/evaluator';\nimport {\n apply,\n COMPONENT_ACTIONS,\n escapeSelector,\n} from '../helpers/realtime-conditions/applier';\nimport { DESCOPE_ATTRIBUTE_EXCLUDE_FIELD } from '../constants';\nimport type { RealtimeComponentsCondition, ScreenState } from '../types';\n\nconst LOG_PREFIX = 'component-conditions:';\n\n// What the mixin needs from its host: a way to subscribe to loading state\n// so input handling can pause while the next request is in flight. Defined\n// as an interface (not imported) to avoid a circular dependency on BaseDescopeWc.\nexport interface PausableHost {\n nextRequestStatus?: {\n // subscribe returns a token; pass that token to unsubscribe — not the handler.\n subscribe: (cb: (v: { isLoading: boolean }) => void) => string;\n unsubscribe?: (token: string) => void;\n };\n}\n\nexport interface RealtimeRuntime {\n conditions: RealtimeComponentsCondition[];\n // IDs of components that any rule can change\n touchedIds: Set<string>;\n // latest form values on screen\n snapshot: FormSnapshot;\n // what's currently applied on screen for touched components.\n // Compared against on each re-evaluation to know what to change.\n applied: Record<string, string>;\n // What the server told us to apply for these components. Stays fixed for\n // the screen's lifetime so we can fall back to it when a real-time rule\n // stops matching. Without this, a server-set action could disappear when\n // a real-time rule briefly fires on the same component.\n serverBaseline: Record<string, string>;\n debounceTimer: ReturnType<typeof setTimeout> | null;\n // true while paused (during submit, to avoid stale updates)\n paused: boolean;\n unsubscribePauseListener: (() => void) | null;\n // the listener we attach to form events (kept so we can detach)\n inputHandler: (e: Event) => void;\n // the screen root we work against\n root: HTMLElement | null;\n}\n\n// Some inputs already have `name=\"form.x\"`, others use `name=\"x\"`. Always\n// return the `form.x` form so it lines up with what rules reference.\nfunction toFormKey(name: string): string {\n return name.startsWith('form.') ? name : `form.${name}`;\n}\n\n// Try the full `form.x` first (descope components), then `x` (plain inputs).\nfunction findInputForFormKey(\n root: ParentNode,\n formKey: string,\n): Element | null {\n const bare = formKey.startsWith('form.')\n ? formKey.slice('form.'.length)\n : formKey;\n return (\n root.querySelector(`[name=\"${escapeSelector(formKey)}\"]`) ||\n root.querySelector(`[name=\"${escapeSelector(bare)}\"]`)\n );\n}\n\n// Read the current value off a form input. Reads JS properties (not HTML\n// attributes) so we pick up both the component's default and any value\n// carried over from earlier screens.\n//\n// Native <input type=checkbox> needs special handling: `.value` is always\n// \"on\", only `.checked` reflects the real state. Descope boolean components\n// (descope-checkbox, descope-switch-toggle) expose `.checked` on their class.\nfunction readInputValue(el: Element): unknown {\n if (el instanceof HTMLInputElement) {\n return el.type === 'checkbox' ? el.checked : el.value;\n }\n if ('checked' in el) {\n return (el as unknown as { checked: boolean }).checked;\n }\n if ('value' in el) {\n return (el as unknown as { value: unknown }).value;\n }\n return undefined;\n}\n\nfunction shallowEqualStringMap(\n a: Record<string, string>,\n b: Record<string, string>,\n): boolean {\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n if (keysA.length !== keysB.length) return false;\n return keysA.every((k) => a[k] === b[k]);\n}\n\nfunction emptyRuntime(): RealtimeRuntime {\n return {\n conditions: [],\n touchedIds: new Set(),\n snapshot: {},\n applied: {},\n serverBaseline: {},\n debounceTimer: null,\n paused: false,\n unsubscribePauseListener: null,\n inputHandler: () => {},\n root: null,\n };\n}\n\n// For each touched component, pick the real-time action if a rule is firing\n// for it, otherwise fall back to the server's action. Components that no rule\n// touches are not in the result — those were already painted by\n// applyComponentsState.\nfunction effectiveActions(\n realtimeVerdict: Record<string, string>,\n serverBaseline: Record<string, string>,\n touchedIds: Set<string>,\n): Record<string, string> {\n const out: Record<string, string> = {};\n touchedIds.forEach((id) => {\n if (realtimeVerdict[id]) {\n out[id] = realtimeVerdict[id];\n } else if (serverBaseline[id]) {\n out[id] = serverBaseline[id];\n }\n });\n return out;\n}\n\nexport const componentConditionsMixin = createSingletonMixin(\n <T extends CustomElementConstructor>(superclass: T) => {\n // Pull in loggerMixin so `this.logger` is available no matter where\n // this mixin sits in the chain.\n const BaseClass = compose(loggerMixin)(superclass);\n\n return class ComponentConditionsMixin extends BaseClass {\n // One runtime per <descope-wc> element.\n #rtRuntime: RealtimeRuntime = emptyRuntime();\n\n /**\n * Apply the server's hide/disable/read-only actions to the DOM.\n * Logs unknown actions here (runs once per screen) but stays quiet on\n * the keystroke path to avoid log spam.\n */\n applyComponentsState(\n root: ParentNode,\n componentsState: Record<string, string> | undefined,\n ): void {\n if (!componentsState) return;\n Object.entries(componentsState).forEach(([id, action]) => {\n if (!(COMPONENT_ACTIONS as readonly string[]).includes(action)) {\n this.logger.error(\n `Unknown component action \"${action}\" for component with id \"${id}\"`,\n `Valid actions are ${COMPONENT_ACTIONS.map((a) => `\"${a}\"`).join(\n ', ',\n )}`,\n );\n }\n });\n apply(root, {}, componentsState);\n }\n\n /**\n * Set up real-time conditions for the current screen. Safe to call\n * twice — a second call rebuilds from screenState.\n *\n * Must run AFTER `updateScreenFromScreenState`, so the DOM reads below\n * see both server-shipped values and any component defaults from the\n * HTML.\n */\n initRealtimeConditions(\n rootElement: HTMLElement,\n screenState: ScreenState | undefined,\n ): void {\n this.#teardownRealtimeRuntime();\n\n const conditions = screenState?.realtimeComponentsConditions ?? [];\n if (!conditions.length) {\n this.logger.debug(\n `${LOG_PREFIX} no real-time rules to apply on this screen`,\n );\n return;\n }\n this.logger.info(\n `${LOG_PREFIX} found ${conditions.length} real-time rule(s) for this screen`,\n );\n\n // screenState.form uses \"phone\"; rules reference \"form.phone\".\n // Add the prefix on the way in.\n const initialSnapshot: FormSnapshot = {};\n Object.entries(screenState?.form ?? {}).forEach(([k, v]) => {\n initialSnapshot[`form.${k}`] = v;\n });\n\n // For every key the rules reference, read the current DOM value.\n // Component defaults (e.g. `checked=\"true\"` on a descope-checkbox)\n // live only in the HTML and don't make it into screenState.form, so\n // without this read the first evaluation would miss them.\n collectReferencedFormKeys(conditions).forEach((formKey) => {\n const el = findInputForFormKey(rootElement, formKey);\n if (!el) return;\n const v = readInputValue(el);\n if (v !== undefined) initialSnapshot[formKey] = v;\n });\n\n const touchedIds = collectTouchedComponentIds(conditions);\n\n // What to fall back to when a real-time rule stops matching for a\n // touched component — the actions set by server-only rules (rules\n // with no client-side conditions).\n const serverBaseline: Record<string, string> = {};\n // What's already painted on the DOM (touched components only), so\n // the first real-time evaluation can diff against the right state.\n const initialApplied: Record<string, string> = {};\n\n Object.entries(screenState?.componentsState ?? {}).forEach(\n ([id, action]) => {\n if (!touchedIds.has(id)) return;\n initialApplied[id] = action;\n },\n );\n\n Object.entries(screenState?.serverOnlyComponentsState ?? {}).forEach(\n ([id, action]) => {\n if (touchedIds.has(id)) {\n serverBaseline[id] = action;\n }\n },\n );\n\n const runtime: RealtimeRuntime = {\n conditions,\n touchedIds,\n snapshot: initialSnapshot,\n applied: initialApplied,\n serverBaseline,\n debounceTimer: null,\n paused: false,\n unsubscribePauseListener: null,\n inputHandler: () => {},\n root: rootElement,\n };\n\n // Re-run the rules now that we've read the real DOM values. The\n // server evaluated without seeing component defaults, so its\n // `componentsState` can disagree with what the user actually sees.\n // Apply the diff once before listening for input.\n const reconciled = effectiveActions(\n evaluateAll(conditions, initialSnapshot),\n serverBaseline,\n touchedIds,\n );\n if (!shallowEqualStringMap(initialApplied, reconciled)) {\n runtime.applied = apply(rootElement, initialApplied, reconciled);\n }\n\n runtime.inputHandler = (e: Event) =>\n this.#handleRealtimeInput(e as InputEvent);\n\n REALTIME_CONDITION_EVENTS.forEach((ev) => {\n rootElement.addEventListener(ev, runtime.inputHandler, true);\n });\n this.logger.debug(\n `${LOG_PREFIX} listening for \"${REALTIME_CONDITION_EVENTS.join(\n '\" and \"',\n )}\" events on form fields; ${\n Object.keys(initialApplied).length\n } component(s) start hidden / disabled / read-only by these rules`,\n );\n\n // Pause while a /next request is in flight. Without this, a debounced\n // evaluation could run between submit and the next screen render and\n // change components that are about to be replaced — causing flicker,\n // or hiding something the next screen needs visible.\n const pauseState = (this as unknown as PausableHost).nextRequestStatus;\n if (pauseState?.subscribe) {\n const handler = ({ isLoading }: { isLoading: boolean }) => {\n runtime.paused = isLoading;\n if (isLoading && runtime.debounceTimer) {\n clearTimeout(runtime.debounceTimer);\n runtime.debounceTimer = null;\n }\n };\n // subscribe returns a token; unsubscribe needs that token, not the\n // handler. Without storing it, handlers leak across screens and\n // keep old runtimes (and their DOM roots) alive.\n const token = pauseState.subscribe(handler);\n runtime.unsubscribePauseListener = () => {\n if (token !== undefined && token !== null) {\n pauseState.unsubscribe?.(token);\n }\n };\n }\n\n this.#rtRuntime = runtime;\n }\n\n #handleRealtimeInput(e: InputEvent): void {\n const runtime = this.#rtRuntime;\n if (!runtime.root || runtime.paused) return;\n\n const target = e.target as Element | null;\n if (!target) return;\n if (target.hasAttribute?.(DESCOPE_ATTRIBUTE_EXCLUDE_FIELD)) return;\n\n const name = target.getAttribute?.('name');\n if (!name) return;\n\n // Update the snapshot only — evaluation is debounced. Use readInputValue\n // so checkboxes read the same way as at mount; otherwise `target.value`\n // would be the string \"on\" for native checkboxes and break is-true rules.\n const key = toFormKey(name);\n runtime.snapshot[key] = readInputValue(target);\n\n if (runtime.debounceTimer) {\n clearTimeout(runtime.debounceTimer);\n }\n runtime.debounceTimer = setTimeout(() => {\n runtime.debounceTimer = null;\n this.#reEvaluateRealtime();\n }, REALTIME_CONDITION_DEBOUNCE_MS);\n }\n\n #reEvaluateRealtime(): void {\n const runtime = this.#rtRuntime;\n if (!runtime.root) return;\n\n let next: Record<string, string>;\n try {\n next = effectiveActions(\n evaluateAll(runtime.conditions, runtime.snapshot),\n runtime.serverBaseline,\n runtime.touchedIds,\n );\n } catch (e) {\n this.logger.error(\n `${LOG_PREFIX} failed to evaluate real-time rules — keeping the previous state`,\n (e as Error)?.message,\n );\n return;\n }\n\n const prevApplied = runtime.applied;\n if (shallowEqualStringMap(prevApplied, next)) return;\n\n this.logger.debug(\n `${LOG_PREFIX} form changed — updating components: was ${JSON.stringify(\n prevApplied,\n )}, now ${JSON.stringify(next)}`,\n );\n runtime.applied = apply(runtime.root, prevApplied, next);\n }\n\n // Clean up listeners and timers when the host leaves the DOM. Reaches\n // us only if BaseDescopeWc calls `super.disconnectedCallback?.()`;\n // otherwise teardown happens lazily on the next initRealtimeConditions.\n disconnectedCallback() {\n // disconnectedCallback isn't on HTMLElement in the lib types, but it\n // exists at runtime — forward into super in case the chain uses it.\n super.disconnectedCallback?.();\n this.#teardownRealtimeRuntime();\n }\n\n #teardownRealtimeRuntime(): void {\n const r = this.#rtRuntime;\n if (r.debounceTimer) {\n clearTimeout(r.debounceTimer);\n }\n if (r.unsubscribePauseListener) {\n r.unsubscribePauseListener();\n }\n if (r.root) {\n // Deliberately NOT undoing what we applied. `r.root` is the host's\n // content root, which is built once in the constructor and never\n // replaced. Only its children are. By the time we get here the caller\n // has already swapped in the next screen, so looking our component\n // ids up in `r.root` finds the NEW screen's elements and would strip\n // the state the server just painted on them. Nothing needs undoing\n // anyway, because the elements we touched went with the old screen.\n REALTIME_CONDITION_EVENTS.forEach((ev) => {\n r.root!.removeEventListener(ev, r.inputHandler, true);\n });\n }\n this.#rtRuntime = emptyRuntime();\n }\n };\n },\n);\n"],"names":["LOG_PREFIX","readInputValue","el","HTMLInputElement","type","checked","value","shallowEqualStringMap","a","b","keysA","Object","keys","keysB","length","every","k","emptyRuntime","conditions","touchedIds","Set","snapshot","applied","serverBaseline","debounceTimer","paused","unsubscribePauseListener","inputHandler","root","effectiveActions","realtimeVerdict","out","forEach","id","componentConditionsMixin","createSingletonMixin","superclass","BaseClass","compose","loggerMixin","_a","constructor","_ComponentConditionsMixin_rtRuntime","set","this","applyComponentsState","componentsState","entries","action","COMPONENT_ACTIONS","includes","logger","error","map","join","apply","initRealtimeConditions","rootElement","screenState","__classPrivateFieldGet","_ComponentConditionsMixin_instances","_ComponentConditionsMixin_teardownRealtimeRuntime","call","_b","realtimeComponentsConditions","debug","info","initialSnapshot","_c","form","v","collectReferencedFormKeys","formKey","bare","startsWith","slice","querySelector","escapeSelector","findInputForFormKey","undefined","collectTouchedComponentIds","initialApplied","_d","has","_e","serverOnlyComponentsState","runtime","reconciled","evaluateAll","e","REALTIME_CONDITION_EVENTS","ev","addEventListener","pauseState","nextRequestStatus","subscribe","handler","isLoading","clearTimeout","token","unsubscribe","__classPrivateFieldSet","disconnectedCallback","super","target","hasAttribute","DESCOPE_ATTRIBUTE_EXCLUDE_FIELD","name","getAttribute","key","toFormKey","setTimeout","_ComponentConditionsMixin_reEvaluateRealtime","REALTIME_CONDITION_DEBOUNCE_MS","next","message","prevApplied","JSON","stringify","r","removeEventListener"],"mappings":"6nBAqBA,MAAMA,EAAa,wBAgEnB,SAASC,EAAeC,GACtB,OAAIA,aAAcC,iBACG,aAAZD,EAAGE,KAAsBF,EAAGG,QAAUH,EAAGI,MAE9C,YAAaJ,EACPA,EAAuCG,QAE7C,UAAWH,EACLA,EAAqCI,WAD/C,CAIF,CAEA,SAASC,EACPC,EACAC,GAEA,MAAMC,EAAQC,OAAOC,KAAKJ,GACpBK,EAAQF,OAAOC,KAAKH,GAC1B,OAAIC,EAAMI,SAAWD,EAAMC,QACpBJ,EAAMK,OAAOC,GAAMR,EAAEQ,KAAOP,EAAEO,IACvC,CAEA,SAASC,IACP,MAAO,CACLC,WAAY,GACZC,WAAY,IAAIC,IAChBC,SAAU,CAAE,EACZC,QAAS,CAAE,EACXC,eAAgB,CAAE,EAClBC,cAAe,KACfC,QAAQ,EACRC,yBAA0B,KAC1BC,aAAc,OACdC,KAAM,KAEV,CAMA,SAASC,EACPC,EACAP,EACAJ,GAEA,MAAMY,EAA8B,CAAA,EAQpC,OAPAZ,EAAWa,SAASC,IACdH,EAAgBG,GAClBF,EAAIE,GAAMH,EAAgBG,GACjBV,EAAeU,KACxBF,EAAIE,GAAMV,EAAeU,GAC1B,IAEIF,CACT,OAEaG,EAA2BC,GACDC,oBAGnC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