!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).formbricks=t()}(this,(function(){"use strict";var e=Object.defineProperty,t=(t,n,s)=>((t,n,s)=>n in t?e(t,n,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[n]=s)(t,"symbol"!=typeof n?n+"":n,s);const n="formbricks-js",s="formbricks-js-website",r="formbricks-js-app",i="formbricks-app-container",a=class e{constructor(){t(this,"logLevel","error")}static getInstance(){return e.instance||(e.instance=new e),e.instance}configure(e){void 0!==e.logLevel&&(this.logLevel=e.logLevel)}logger(e,t){if("debug"===t&&"debug"!==this.logLevel)return;const n=`🧱 Formbricks - ${(new Date).toISOString()} [${t.toUpperCase()}] - ${e}`;"error"===t?console.error(n):console.log(n)}debug(e){this.logger(e,"debug")}error(e){this.logger(e,"error")}};t(a,"instance");let o=a;const d=e=>({ok:!0,value:e}),c=e=>({ok:!1,error:e});const l=e=>(...t)=>{try{return{ok:!0,value:e(...t)}}catch(n){return{ok:!1,error:n}}},u=o.getInstance(),g=class e{constructor(e){t(this,"handleError"),t(this,"customized",!1),e?(this.handleError=e,this.customized=!0):this.handleError=e=>{o.getInstance().error(JSON.stringify(e))}}static getInstance(){return e.instance||(e.instance=new e),e.instance}static init(t){this.initialized=!0,e.instance=new e(t)}printStatus(){u.debug("Custom error handler: "+(this.customized?"yes":"no"))}handle(e){console.warn("🧱 Formbricks - Global error: ",e),this.handleError(e)}};t(g,"instance"),t(g,"initialized",!1);let p=g;const h=class e{constructor(){t(this,"config",null);const e=this.loadFromLocalStorage();e.ok&&(this.config=e.value)}static getInstance(){return e.instance||(e.instance=new e),e.instance}update(e){var t,n;this.config={...this.config,...e,status:{value:(null==(t=e.status)?void 0:t.value)??"success",expiresAt:(null==(n=e.status)?void 0:n.expiresAt)??null}},this.saveToStorage()}get(){if(!this.config)throw new Error("config is null, maybe the init function was not called?");return this.config}loadFromLocalStorage(){var e;if("undefined"!=typeof window){const t=localStorage.getItem(n);if(t){const n=JSON.parse(t);return new Date(null==(e=n.environmentState)?void 0:e.expiresAt)<=new Date?c(new Error("Config in local storage has expired")):d(n)}}return c(new Error("No or invalid config in local storage"))}saveToStorage(){return l((()=>{localStorage.setItem(n,JSON.stringify(this.config))}))()}resetConfig(){return this.config=null,l((()=>{localStorage.removeItem(n)}))()}};t(h,"instance");let v=h;var f=Object.defineProperty,m=(e,t,n)=>((e,t,n)=>t in e?f(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n)(e,"symbol"!=typeof t?t+"":t,n);const y=e=>({ok:!1,error:e}),w=async(e,t,n,s)=>{const r=new URL(e+t),i=s?JSON.stringify(s):void 0,a=await(o=fetch,async(...e)=>{try{return{ok:!0,data:await o(...e)}}catch(t){return{ok:!1,error:t}}})(r.toString(),{method:n,headers:{"Content-Type":"application/json"},body:i});var o;if(!a.ok)return y(a.error);const d=a.data,c=await d.json();if(!d.ok){const e=c;return y({code:"forbidden"===e.code?"forbidden":"network_error",status:d.status,message:e.message||"Something went wrong",url:r,...Object.keys(e.details??{}).length>0&&{details:e.details}})}return(e=>({ok:!0,data:e}))(c.data)};class I{constructor(e,t){m(this,"apiHost"),m(this,"environmentId"),this.apiHost=e,this.environmentId=t}async update(e){const t={};for(const n in e.attributes)t[n]=String(e.attributes[n]);return w(this.apiHost,`/api/v1/client/${this.environmentId}/contacts/${e.userId}/attributes`,"PUT",{attributes:t})}}class S{constructor(e,t){m(this,"apiHost"),m(this,"environmentId"),this.apiHost=e,this.environmentId=t}async create(e){return w(this.apiHost,`/api/v1/client/${this.environmentId}/displays`,"POST",e)}}class b{constructor(e,t){m(this,"apiHost"),m(this,"environmentId"),this.apiHost=e,this.environmentId=t}async create(e){return w(this.apiHost,`/api/v1/client/${this.environmentId}/responses`,"POST",e)}async update({responseId:e,finished:t,endingId:n,data:s,ttc:r,variables:i,language:a}){return w(this.apiHost,`/api/v1/client/${this.environmentId}/responses/${e}`,"PUT",{finished:t,endingId:n,data:s,ttc:r,variables:i,language:a})}}class k{constructor(e,t){m(this,"apiHost"),m(this,"environmentId"),this.apiHost=e,this.environmentId=t}async uploadFile(e,{allowedFileExtensions:t,surveyId:n}={}){if(!e.name||!e.type||!e.base64)throw new Error("Invalid file object");const s={fileName:e.name,fileType:e.type,allowedFileExtensions:t,surveyId:n},r=await fetch(`${this.apiHost}/api/v1/client/${this.environmentId}/storage`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!r.ok)throw new Error(`Upload failed with status: ${String(r.status)}`);const i=await r.json(),{data:a}=i,{signedUrl:o,fileUrl:d,signingData:c,presignedFields:l,updatedFileName:u}=a;let g={};if(c){const{signature:t,timestamp:s,uuid:r}=c;g={fileType:e.type,fileName:encodeURIComponent(u),surveyId:n??"",signature:t,timestamp:String(s),uuid:r}}const p={},h=new FormData;if(l){Object.entries(l).forEach((([e,t])=>{h.append(e,t)}));try{const t=atob(e.base64.split(",")[1]),n=Uint8Array.from([...t].map((e=>e.charCodeAt(0)))),s=new Blob([n],{type:e.type});h.append("file",s)}catch(m){throw console.error(m),new Error("Error uploading file")}}p.fileBase64String=e.base64;let v={};const f=o.replace("http://localhost:3000",this.apiHost);try{v=await fetch(f,{method:"POST",body:l?h:JSON.stringify({...p,...g})})}catch(m){console.error("Error uploading file",m)}if(!v.ok){if(c){const e=await v.json(),t=new Error(e.message);throw t.name="FileTooLargeError",t}const e=await v.text();if(l&&e.includes("EntityTooLarge")){const e=new Error("File size exceeds the size limit for your plan");throw e.name="FileTooLargeError",e}throw new Error(`Upload failed with status: ${String(v.status)}`)}return d}}class C{constructor(e){m(this,"response"),m(this,"display"),m(this,"storage"),m(this,"attribute");const{apiHost:t,environmentId:n}=e;this.response=new b(t,n),this.display=new S(t,n),this.attribute=new I(t,n),this.storage=new k(t,n)}}class E{constructor(e){m(this,"client"),this.client=new C(e)}}const H=e=>new Promise((t=>setTimeout(t,e)));class ${constructor(e,n){t(this,"queue",[]),t(this,"config"),t(this,"surveyState"),t(this,"isRequestInProgress",!1),t(this,"api"),this.config=e,this.surveyState=n,this.api=new E({apiHost:e.apiHost,environmentId:e.environmentId})}add(e){this.surveyState.accumulateResponse(e),this.config.setSurveyState&&this.config.setSurveyState(this.surveyState),this.queue.push(e),this.processQueue()}async processQueue(){if(this.isRequestInProgress)return;if(0===this.queue.length)return;this.isRequestInProgress=!0;const e=this.queue[0];let t=0;for(;t<this.config.retryAttempts;){if(await this.sendResponse(e)){this.queue.shift();break}console.error(`Formbricks: Failed to send response. Retrying... ${t}`),await H(1e3),t++}t>=this.config.retryAttempts?(console.error("Failed to send response after 2 attempts."),this.config.onResponseSendingFailed&&this.config.onResponseSendingFailed(e),this.isRequestInProgress=!1):(e.finished&&this.config.onResponseSendingFinished&&this.config.onResponseSendingFinished(),this.isRequestInProgress=!1,this.processQueue())}async sendResponse(e){try{if(null!==this.surveyState.responseId)await this.api.client.response.update({...e,responseId:this.surveyState.responseId});else{const t=await this.api.client.response.create({...e,surveyId:this.surveyState.surveyId,userId:this.surveyState.userId||null,singleUseId:this.surveyState.singleUseId||null,data:{...e.data,...e.hiddenFields},displayId:this.surveyState.displayId});if(!t.ok)throw new Error("Could not create response");this.surveyState.updateResponseId(t.data.id),this.config.setSurveyState&&this.config.setSurveyState(this.surveyState)}return!0}catch(t){return console.error(t),!1}}updateSurveyState(e){this.surveyState=e}}class F{constructor(e,n,s,r){t(this,"responseId",null),t(this,"displayId",null),t(this,"userId",null),t(this,"surveyId"),t(this,"responseAcc",{finished:!1,data:{},ttc:{},variables:{}}),t(this,"singleUseId"),this.surveyId=e,this.userId=r??null,this.singleUseId=n??null,this.responseId=s??null}setSurveyId(e){this.surveyId=e,this.clear()}copy(){const e=new F(this.surveyId,this.singleUseId??void 0,this.responseId??void 0,this.userId??void 0);return e.responseId=this.responseId,e.responseAcc=this.responseAcc,e}updateResponseId(e){this.responseId=e}updateDisplayId(e){this.displayId=e}updateUserId(e){this.userId=e}accumulateResponse(e){this.responseAcc={finished:e.finished,ttc:e.ttc,data:{...this.responseAcc.data,...e.data},variables:e.variables,displayId:e.displayId}}isResponseFinished(){return this.responseAcc.finished}clear(){this.responseId=null,this.responseAcc={finished:!1,data:{},ttc:{},variables:{}}}}const A=(e,t)=>{var n;return e.styling.allowStyleOverwrite&&e.styling.allowStyleOverwrite&&(null==(n=t.styling)?void 0:n.overwriteThemeStyling)?t.styling:e.styling},D=class e{constructor(){t(this,"timeouts",[])}static getInstance(){return e.instance||(e.instance=new e),e.instance}add(e,t){this.timeouts.push({event:e,timeoutId:t})}remove(e){clearTimeout(e),this.timeouts=this.timeouts.filter((t=>t.timeoutId!==e))}clear(){for(const e of this.timeouts)clearTimeout(e.timeoutId);this.timeouts=[]}getTimeouts(){return this.timeouts}};t(D,"instance",null);let O=D;const L=(e,t)=>{const n=Math.abs(t.getTime()-e.getTime());return Math.floor(n/864e5)},P=o.getInstance(),R=e=>{if(0===e.length)return!0;const t=window.location.href;return e.some((e=>((e,t,n)=>{switch(n){case"exactMatch":return e===t;case"contains":return e.includes(t);case"startsWith":return e.startsWith(t);case"endsWith":return e.endsWith(t);case"notMatch":return e!==t;case"notContains":return!e.includes(t);default:return!1}})(t,e.value,e.rule)))},x=e=>{const t=e.languages.find((e=>e.default));if(t)return t.language.code},T=()=>window.location.search.includes("formbricksDebug=true"),j=(e,t)=>{const{project:n,surveys:s}=e.data,{displays:r,responses:i,lastDisplayAt:a,segments:o,userId:d}=t.data;let c=s.filter((e=>{switch(e.displayOption){case"respondMultiple":return!0;case"displayOnce":return 0===r.filter((t=>t.surveyId===e.id)).length;case"displayMultiple":return 0===i.filter((t=>t===e.id)).length;case"displaySome":return null===e.displayLimit||!i.filter((t=>t===e.id)).length&&r.filter((t=>t.surveyId===e.id)).length<e.displayLimit;default:throw Error("Invalid displayOption")}}));return c=c.filter((e=>!a||(null!==e.recontactDays?L(new Date,new Date(a))>=e.recontactDays:!n.recontactDays||L(new Date,new Date(a))>=n.recontactDays))),d?o.length?c.filter((e=>{var t;return(null==(t=e.segment)?void 0:t.id)&&o.includes(e.segment.id)})):[]:c},N=v.getInstance(),U=o.getInstance(),z=O.getInstance();let M=!1,q=e=>{},J=e=>{};const _=e=>{M=e},B=async(e,t,n)=>{if(e.displayPercentage){if(!(s=e.displayPercentage,Math.floor(1e4*Math.random())/100<=s))return void U.debug(`Survey display of "${e.name}" skipped based on displayPercentage.`)}var s;const r=((e,t)=>{const{enabled:n,fieldIds:s}=e;let r={};if(n){if(s&&t){const e=[];r=Object.keys(t).reduce(((n,r)=>(s.includes(r)?n[r]=t[r]:e.push(r),n)),{}),e.length>0&&P.error(`Unknown hidden fields: ${e.join(", ")}. Please add them to the survey hidden fields.`)}}else P.error("Hidden fields are not enabled for this survey");return r})(e.hiddenFields,null==n?void 0:n.hiddenFields);await Q(e,t,r)},Q=async(e,t,n={})=>{if(M)return void U.debug("A survey is already running. Skipping.");_(!0),e.delay&&U.debug(`Delaying survey "${e.name}" by ${e.delay.toString()} seconds.`);const{project:s}=N.get().environmentState.data,{attributes:r}=N.get(),i=e.languages.length>1;let a="default";if(i){const t=((e,t)=>{const n=t.language,s=e.languages.map((e=>e.language.code));if(!n)return"default";const r=e.languages.find((e=>{var t;return e.language.code===n.toLowerCase()||(null==(t=e.language.alias)?void 0:t.toLowerCase())===n.toLowerCase()}));return(null==r?void 0:r.default)?"default":r&&r.enabled&&s.includes(r.language.code)?r.language.code:void 0})(e,r);if(!t)return U.debug(`Survey "${e.name}" is not available in specified language.`),void _(!0);a=t}const o=new F(e.id,null,null,N.get().personState.data.userId),d=new $({apiHost:N.get().apiHost,environmentId:N.get().environmentId,retryAttempts:2,onResponseSendingFailed:()=>{q(!0)},onResponseSendingFinished:()=>{J(!0)}},o),c=e.projectOverwrites??{},l=c.clickOutsideClose??s.clickOutsideClose,u=c.darkOverlay??s.darkOverlay,g=c.placement??s.placement,p=s.inAppSurveyBranding,h=await V(),v=setTimeout((()=>{h.renderSurveyModal({survey:e,isBrandingEnabled:p,clickOutside:l,darkOverlay:u,languageCode:a,placement:g,styling:A(s,e),getSetIsError:e=>{q=e},getSetIsResponseSendingFinished:e=>{J=e},onDisplay:async()=>{const{userId:t}=N.get().personState.data,n=new E({apiHost:N.get().apiHost,environmentId:N.get().environmentId}),s=await n.client.display.create({surveyId:e.id,...t&&{userId:t}});if(!s.ok)throw new Error("Could not create display");const{id:r}=s.data;o.updateDisplayId(r),d.updateSurveyState(o);const i=N.get().personState.data.displays,a={surveyId:e.id,createdAt:new Date},c=i.length?[...i,a]:[a],l=N.get(),u={...l.personState,data:{...l.personState.data,displays:c,lastDisplayAt:new Date}},g=j(l.environmentState,u);N.update({...l,environmentState:l.environmentState,personState:u,filteredSurveys:g})},onResponse:s=>{const{userId:r}=N.get().personState.data,i=null===o.responseId;if(r&&o.updateUserId(r),d.updateSurveyState(o),d.add({data:s.data,ttc:s.ttc,finished:s.finished,language:"default"===s.language?x(e):s.language,meta:{url:window.location.href,action:t},variables:s.variables,hiddenFields:n,displayId:o.displayId}),i){const e=N.get().personState.data.responses,t={...N.get().personState,data:{...N.get().personState.data,responses:e.length?[...e,o.surveyId]:[o.surveyId]}},n=j(N.get().environmentState,t);N.update({...N.get(),environmentState:N.get().environmentState,personState:t,filteredSurveys:n})}},onClose:W,onFileUpload:async(e,t)=>{const n=new E({apiHost:N.get().apiHost,environmentId:N.get().environmentId});return await n.client.storage.uploadFile({type:e.type,name:e.name,base64:e.base64},t)},onRetry:()=>{q(!1),d.processQueue()},hiddenFieldsRecord:n})}),1e3*e.delay);t&&z.add(t,v)},W=()=>{G(),Y();const{environmentState:e,personState:t}=N.get(),n=j(e,t);N.update({...N.get(),environmentState:e,personState:t,filteredSurveys:n}),_(!1)},Y=()=>{const e=document.createElement("div");e.id=i,document.body.appendChild(e)},G=()=>{var e;null==(e=document.getElementById(i))||e.remove()},V=()=>new Promise(((e,t)=>{if(window.formbricksSurveys)e(window.formbricksSurveys);else{const n=document.createElement("script");n.src=`${N.get().apiHost}/js/surveys.umd.cjs`,n.async=!0,n.onload=()=>{e(window.formbricksSurveys)},n.onerror=e=>{console.error("Failed to load Formbricks Surveys library:",e),t(new Error(`Failed to load Formbricks Surveys library: ${e}`))},document.head.appendChild(n)}})),K=o.getInstance(),X=v.getInstance(),Z=async(e,t,n)=>{const s=t??e;K.debug(`Formbricks: Action "${s}" tracked`);const r=X.get().filteredSurveys;if(Boolean(r)&&r.length>0)for(const i of r)for(const t of i.triggers)t.actionClass.name===e&&await B(i,e,n);else K.debug("No active surveys to display");return{ok:!0,value:void 0}},ee=(e,t)=>{const n=X.get().environmentState.data.actionClasses.filter((e=>"code"===e.type)).find((t=>t.key===e));return n?Z(n.name,e,t):c({code:"invalid_code",message:`${e} action unknown. Please add this action in Formbricks first in order to use it in your code.`})},te=e=>Z(e),ne=v.getInstance(),se=o.getInstance();let re=null;const ie={expiresAt:null,data:{userId:null,segments:[],displays:[],responses:[],lastDisplayAt:null}},ae=async({apiHost:e,environmentId:t,userId:n},s=!1)=>{const r={};(s||T())&&(r.cache="no-cache",se.debug("No cache option set for sync"));const i=`${e}/api/v1/client/${t}/identify/contacts/${n}`,a=await fetch(i,r);if(!a.ok){const e=await a.json(),t=c({code:"forbidden"===e.code?"forbidden":"network_error",status:a.status,message:"Error syncing with backend",url:new URL(i),responseMessage:e.message});throw new Error(t.error.message)}const o=await a.json(),{data:d}=o,l={expiresAt:new Date((new Date).getTime()+18e5),data:{userId:n,segments:[],displays:[],responses:[],lastDisplayAt:null}};return Object.keys(d).length?{data:{...d},expiresAt:new Date((new Date).getTime()+18e5)}:l},oe=()=>{re&&(clearInterval(re),re=null)},de=v.getInstance(),ce=o.getInstance(),le=async(e,t)=>{if("userId"===e)return ce.error("Setting userId is no longer supported. Please set the userId in the init call instead."),{ok:!0,value:void 0};const n=de.get().personState.data.userId;if(ce.debug(`Setting attribute: ${e} to value: ${t}`),!n)return ce.error("UserId not provided, please provide a userId in the init method before setting attributes."),{ok:!0,value:void 0};const s=await(async(e,t)=>{var n;const{apiHost:s,environmentId:r}=de.get(),i=de.get().personState.data.userId;if(!i)return c({code:"network_error",status:500,message:"Missing userId",url:new URL(`${s}/api/v1/client/${r}/contacts/${i??""}/attributes`),responseMessage:"Missing userId"});const a=new E({apiHost:s,environmentId:r}),o=await a.client.attribute.update({userId:i,attributes:{[e]:t}});if(!o.ok){const e=o.error;return(null==(n=e.details)?void 0:n.ignore)?(ce.error(e.message),{ok:!0,value:{changed:!1,message:o.error.message}}):c({code:o.error.code,status:o.error.status,message:`Error updating person with userId ${i}`,url:new URL(`${s}/api/v1/client/${r}/contacts/${i}/attributes`),responseMessage:o.error.message})}return o.data.details&&Object.entries(o.data.details).forEach((([e,t])=>{ce.error(`${e}: ${t}`)})),o.data.changed?(ce.debug("Attribute updated in Formbricks"),{ok:!0,value:{changed:!0,message:"Attribute updated in Formbricks",...o.data.details&&{details:o.data.details}}}):{ok:!0,value:{changed:!1,message:"Attribute not updated in Formbricks",...o.data.details&&{details:o.data.details}}}})(e,t.toString());if(s.ok){if(s.value.changed){const s=await ae({apiHost:de.get().apiHost,environmentId:de.get().environmentId,userId:n},!0),r=j(de.get().environmentState,s);de.update({...de.get(),personState:s,filteredSurveys:r,attributes:{...de.get().attributes,[e]:t.toString()}})}return{ok:!0,value:void 0}}const r=s.error;return"forbidden"===r.code&&ce.error(`Authorization error: ${r.responseMessage??""}`),c(s.error)},ue=e=>async(...t)=>{try{return{ok:!0,data:await e(...t)}}catch(n){return{ok:!1,error:n}}},ge=v.getInstance(),pe=o.getInstance();let he=null;const ve=async({apiHost:e,environmentId:t},n=!1)=>{const s={};(n||T())&&(s.cache="no-cache",pe.debug("No cache option set for sync"));const r=`${e}/api/v1/client/${t}/environment`,i=await fetch(r,s);if(!i.ok){const e=await i.json();throw c({code:"network_error",status:i.status,message:"Error syncing with backend",url:new URL(r),responseMessage:e.message}).error}const a=await i.json(),{data:o}=a;return{data:{...o},expiresAt:new Date((new Date).getTime()+18e5)}},fe=()=>{he&&(clearInterval(he),he=null)},me=v.getInstance(),ye=o.getInstance(),we=p.getInstance(),Ie=O.getInstance(),Se=["hashchange","popstate","pushstate","replacestate","load"];let be=!1,ke=!1;const Ce=async()=>{var e;ye.debug(`Checking page url: ${window.location.href}`);const t=me.get().environmentState.data.actionClasses.filter((e=>{var t;return"noCode"===e.type&&"pageView"===(null==(t=e.noCodeConfig)?void 0:t.type)}));for(const n of t){const t=(null==(e=n.noCodeConfig)?void 0:e.urlFilters)??[];if(R(t)){const e=await te(n.name);if(!e.ok)return c(e.error)}else{const e=Ie.getTimeouts().find((e=>e.event===n.name));e&&(Ie.remove(e.timeoutId),_(!1))}}return{ok:!0,value:void 0}},Ee=()=>Ce(),He=()=>{if("undefined"!=typeof window&&!be){if(!ke){const e=history.pushState;history.pushState=function(...t){e.apply(this,t);const n=new Event("pushstate");window.dispatchEvent(n)},ke=!0}Se.forEach((e=>{window.addEventListener(e,Ee)})),be=!0}},$e=()=>{"undefined"!=typeof window&&be&&(Se.forEach((e=>{window.removeEventListener(e,Ee)})),be=!1)};let Fe=!1;const Ae=e=>{const{environmentState:t}=me.get(),{actionClasses:n=[]}=t.data,s=n.filter((e=>{var t;return"noCode"===e.type&&"click"===(null==(t=e.noCodeConfig)?void 0:t.type)})),r=e.target;s.forEach((e=>{((e,t)=>{var n;if("click"!==(null==(n=t.noCodeConfig)?void 0:n.type))return!1;const s=t.noCodeConfig.elementSelector.innerHtml,r=t.noCodeConfig.elementSelector.cssSelector,i=t.noCodeConfig.urlFilters;if(!s&&!r)return!1;if(s&&e.innerHTML!==s)return!1;if(r){const t=r.split(/\s*(?=[.#])/);for(const n of t)if(!e.matches(n))return!1}return!!R(i)})(r,e)&&te(e.name).then((e=>{var t,n,s;n=e=>{},s=e=>{we.handle(e)},(t=e).ok?n(t.value):s(t.error)})).catch((e=>{we.handle(e)}))}))},De=e=>{Ae(e)},Oe=()=>{Fe&&(document.removeEventListener("click",De),Fe=!1)};let Le=!1;const Pe=e=>(async e=>{var t;const{environmentState:n}=me.get(),{actionClasses:s=[]}=n.data,r=s.filter((e=>{var t;return"noCode"===e.type&&"exitIntent"===(null==(t=e.noCodeConfig)?void 0:t.type)}));if(e.clientY<=0&&r.length>0)for(const i of r){const e=(null==(t=i.noCodeConfig)?void 0:t.urlFilters)??[];if(!R(e))continue;const n=await te(i.name);if(!n.ok)return c(n.error)}})(e),Re=()=>{Le&&(document.removeEventListener("mouseleave",Pe),Le=!1)};let xe=!1,Te=!1;const je=()=>(async()=>{var e;const t=window.scrollY,n=window.innerHeight,s=document.documentElement.scrollHeight;if(0===t&&(Te=!1),!Te&&t/(s-n)>=.5){Te=!0;const{environmentState:t}=me.get(),{actionClasses:n=[]}=t.data,s=n.filter((e=>{var t;return"noCode"===e.type&&"fiftyPercentScroll"===(null==(t=e.noCodeConfig)?void 0:t.type)}));for(const r of s){const t=(null==(e=r.noCodeConfig)?void 0:e.urlFilters)??[];if(!R(t))continue;const n=await te(r.name);if(!n.ok)return c(n.error)}}return{ok:!0,value:void 0}})(),Ne=()=>{xe&&(window.removeEventListener("scroll",je),xe=!1)};let Ue=!1;const ze=()=>{var e;(()=>{if("undefined"!=typeof window&&null===he){const e=async()=>{const e=ge.get().environmentState.expiresAt;try{if(new Date(e)>=new Date)return;pe.debug("Environment State has expired. Starting sync.");const t=ge.get().personState,n=await ve({apiHost:ge.get().apiHost,environmentId:ge.get().environmentId},!0),s=j(n,t);ge.update({...ge.get(),environmentState:n,filteredSurveys:s})}catch(t){pe.error(`Error during expiry check: ${t}`),pe.debug("Extending config and try again later.");const e=ge.get();ge.update(e)}};he=window.setInterval((()=>{e()}),6e4)}})(),(()=>{if("undefined"!=typeof window&&null===re){const e=()=>{ne.get().personState.data.userId&&ne.update({...ne.get(),personState:{...ne.get().personState,expiresAt:new Date((new Date).getTime()+18e5)}})};re=window.setInterval(e,6e4)}})(),He(),"undefined"==typeof window||Fe||(document.addEventListener("click",De),Fe=!0),"undefined"==typeof document||Le||(null==(e=document.querySelector("body"))||e.addEventListener("mouseleave",Pe),Le=!0),"undefined"==typeof window||xe||("complete"===document.readyState?window.addEventListener("scroll",je):window.addEventListener("load",(()=>{window.addEventListener("scroll",je)})),xe=!0)},Me=()=>{fe(),oe(),$e(),Oe(),Re(),Ne(),Ue&&(window.removeEventListener("beforeunload",(()=>{fe(),oe(),$e(),Oe(),Re(),Ne()})),Ue=!1)},qe=o.getInstance();let Je=!1;const _e=e=>{Je=e},Be=async e=>{const t=T();t&&qe.configure({logLevel:"debug"});let i=v.getInstance();const{changed:a,newState:o}=(()=>{const e=localStorage.getItem(s),t=localStorage.getItem(r);if(e){localStorage.removeItem(s);const t=JSON.parse(e);if(t.environmentId&&t.apiHost&&t.environmentState&&t.personState&&t.filteredSurveys)return{changed:!0,newState:{...t}}}if(t){localStorage.removeItem(r);const e=JSON.parse(t);if(e.environmentId&&e.apiHost&&e.environmentState&&e.personState&&e.filteredSurveys)return{changed:!0}}return{changed:!1}})();a&&(i.resetConfig(),i=v.getInstance(),!e.userId&&o&&i.update(o));const{changed:l,newState:u}=(()=>{var e,t;const s=localStorage.getItem(n);if(s){const n=JSON.parse(s);if(null==(t=null==(e=n.environmentState)?void 0:e.data)?void 0:t.product){const{environmentState:e,filteredSurveys:t,...s}=n,r=t.map((e=>{const{productOverwrites:t,...n}=e;return{...n,projectOverwrites:t}})),{product:i,...a}=n.environmentState.data;return{changed:!0,newState:{...s,environmentState:{...n.environmentState,data:{...a,project:i}},filteredSurveys:r}}}}return{changed:!1}})();if(l&&(i.resetConfig(),i=v.getInstance(),u&&i.update(u)),Je)return qe.debug("Already initialized, skipping initialization."),{ok:!0,value:void 0};let g;try{g=i.get(),qe.debug("Found existing configuration.")}catch{qe.debug("No existing configuration found.")}if("error"===(null==g?void 0:g.status.value)){if(t)return qe.debug("Formbricks is in error state, but debug mode is active. Resetting config and continuing."),i.resetConfig(),{ok:!0,value:void 0};console.error("🧱 Formbricks - Formbricks was set to an error state.");const e=g.status.expiresAt;if(e&&new Date(e)>new Date)return console.error("🧱 Formbricks - Error state is not expired, skipping initialization"),{ok:!0,value:void 0};console.error("🧱 Formbricks - Error state is expired. Continuing with initialization.")}if(p.getInstance().printStatus(),qe.debug("Start initialize"),!e.environmentId)return qe.debug("No environmentId provided"),c({code:"missing_field",field:"environmentId"});if(!e.apiHost)return qe.debug("No apiHost provided"),c({code:"missing_field",field:"apiHost"});if(qe.debug("Adding widget container to DOM"),Y(),(null==g?void 0:g.environmentState)&&g.environmentId===e.environmentId&&g.apiHost===e.apiHost){qe.debug("Configuration fits init parameters.");let t=!1,n=!1;new Date(g.environmentState.expiresAt)<new Date&&(qe.debug("Environment state expired. Syncing."),t=!0),e.userId&&(null===g.personState||g.personState.expiresAt&&new Date(g.personState.expiresAt)<new Date)&&(qe.debug("Person state needs syncing - either null or expired"),n=!0);try{const s=t?await ve({apiHost:e.apiHost,environmentId:e.environmentId}):g.environmentState;let{personState:r}=g;n&&(r=e.userId?await ae({apiHost:e.apiHost,environmentId:e.environmentId,userId:e.userId}):ie);const a=j(s,r);i.update({...g,environmentState:s,personState:r,filteredSurveys:a,attributes:e.attributes??{}});const o=a.map((e=>e.name));qe.debug(`Fetched ${o.length.toString()} surveys during sync: ${o.join(", ")}`)}catch{Ye(i)}}else{qe.debug("No valid configuration found. Resetting config and creating new one."),i.resetConfig(),qe.debug("Syncing.");try{const t=await ve({apiHost:e.apiHost,environmentId:e.environmentId},!1),n=e.userId?await ae({apiHost:e.apiHost,environmentId:e.environmentId,userId:e.userId},!1):ie,s=j(t,n);let r=null;if(e.attributes)if(e.userId){const t=await(async(e,t,n,s)=>{var r;const i={...s};if(0===Object.keys(i).length)return ce.debug("No attributes to update. Skipping update."),d(i);ce.debug(`Updating attributes: ${JSON.stringify(i)}`);const a=new E({apiHost:e,environmentId:t}),o=await a.client.attribute.update({userId:n,attributes:i});if(o.ok)return o.data.details&&Object.entries(o.data.details).forEach((([e,t])=>{ce.debug(`${e}: ${t}`)})),d(i);const l=o.error;return(null==(r=l.details)?void 0:r.ignore)?(ce.error(l.message),d(i)):c({code:l.code,status:l.status,message:`Error updating person with userId ${n}`,url:new URL(`${e}/api/v1/client/${t}/people/${n}/attributes`),responseMessage:l.responseMessage})})(e.apiHost,e.environmentId,e.userId,e.attributes);if(!t.ok)return"forbidden"===t.error.code&&qe.error(`Authorization error: ${t.error.responseMessage??""}`),c(t.error);r=t.value}else r={...e.attributes};i.update({apiHost:e.apiHost,environmentId:e.environmentId,personState:n,environmentState:t,filteredSurveys:s,attributes:r??{}})}catch(h){Qe(h)}await te("New Session")}return qe.debug("Adding event listeners"),ze(),Ue||(window.addEventListener("beforeunload",(()=>{fe(),oe(),$e(),Oe(),Re(),Ne()})),Ue=!0),_e(!0),qe.debug("Initialized"),Ce(),{ok:!0,value:void 0}},Qe=e=>{const t=e;if("forbidden"===t.code&&qe.error(`Authorization error: ${t.responseMessage??""}`),T())return void qe.debug("Not putting formbricks in error state because debug mode is active (no error state)");const s={status:{value:"error",expiresAt:new Date((new Date).getTime()+6e5)}};throw l((()=>{localStorage.setItem(n,JSON.stringify(s))}))(),new Error("Could not initialize formbricks")},We=()=>{qe.debug("Deinitializing"),G(),_(!1),Me(),_e(!1)},Ye=e=>{T()?qe.debug("Not putting formbricks in error state because debug mode is active (no error state)"):(qe.debug("Putting formbricks in error state"),e.update({...e.get(),status:{value:"error",expiresAt:new Date((new Date).getTime()+6e5)}}),We())};const Ge=v.getInstance(),Ve=o.getInstance(),Ke=async()=>{We(),Ge.resetConfig()},Xe=async()=>{Ve.debug("Resetting state & getting new state from backend"),W();const e=Ge.get().personState.data.userId,t={environmentId:Ge.get().environmentId,apiHost:Ge.get().apiHost,...e&&{userId:e},attributes:Ge.get().attributes};await Ke(),ke=!1;try{return await Be(t),{ok:!0,value:void 0}}catch(n){return c(n)}};o.getInstance().debug("Create command queue");const Ze=new class{constructor(){t(this,"queue",[]),t(this,"running",!1),t(this,"resolvePromise",null),t(this,"commandPromise",null)}add(e,t,...n){this.queue.push({command:t,checkInitialized:e,commandArgs:n}),this.running||(this.commandPromise=new Promise((e=>{this.resolvePromise=e,this.run()})))}async wait(){this.running&&await this.commandPromise}async run(){for(this.running=!0;this.queue.length>0;){const e=p.getInstance(),t=this.queue.shift();if(!t)continue;if(t.checkInitialized){const t=(qe.debug("Check if initialized"),Je&&p.initialized?{ok:!0,value:void 0}:c({code:"not_initialized",message:"Formbricks not initialized. Call initialize() first."}));if(!t.ok){e.handle(t.error);continue}}const n=async()=>await t.command.apply(null,t.commandArgs),s=await ue(n)();s.ok&&(s.data.ok||e.handle(s.data.error)),s.ok||e.handle(s.error)}this.running=!1,this.resolvePromise&&(this.resolvePromise(),this.resolvePromise=null,this.commandPromise=null)}},et=async(e,t)=>{Ze.add(!0,le,e,t),await Ze.wait()};return{init:async e=>{p.init(e.errorHandler),Ze.add(!1,Be,e),await Ze.wait()},setEmail:async e=>{await et("email",e),await Ze.wait()},setAttribute:et,track:async(e,t)=>{Ze.add(!0,ee,e,t),await Ze.wait()},logout:async()=>{Ze.add(!0,Ke),await Ze.wait()},reset:async()=>{Ze.add(!0,Xe),await Ze.wait()},registerRouteChange:async()=>{Ze.add(!0,Ce),await Ze.wait()},getApi:()=>{const e=v.getInstance(),{environmentId:t,apiHost:n}=e.get();if(!t||!n)throw new Error("formbricks.init() must be called before getApi()");return new E({apiHost:n,environmentId:t})}}}));
//# sourceMappingURL=index.umd.cjs.map