UNPKG

@kameleoon/javascript-sdk

Version:
1 lines 173 kB
"use strict";var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function t(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function i(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if("function"==typeof t){var i=function e(){var i=!1;try{i=this instanceof e}catch{}return i?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};i.prototype=t.prototype}else i={};return Object.defineProperty(i,"__esModule",{value:!0}),Object.keys(e).forEach(function(t){var a=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(i,t,a.get?a:{enumerable:!0,get:function(){return e[t]}})}),i}var a,r,o,n={},s={},u=(r||(r=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Err=e.Ok=void 0;var t=function(){if(a)return s;function e(e){if(!this.ok){if("string"==typeof this.error||void 0===this.error)throw new Error(e||this.error||"There was an error! No specific error message was provided.");throw e&&(this.error.message=e),this.error}return this.data}function t(e){return this.ok?this.data:e(this.error)}function i(e){return this.ok?this.data:e}function r(e){return this.ok&&e(this.data),this}return a=1,Object.defineProperty(s,"__esModule",{value:!0}),s.Err=s.Ok=void 0,s.Ok=function(a){return{ok:!0,data:a,throw:e,else:t,or:i,and:r}},s.Err=function(a){return{ok:!1,error:a,throw:e,else:t,or:i,and:r}},s}();Object.defineProperty(e,"Ok",{enumerable:!0,get:function(){return t.Ok}}),Object.defineProperty(e,"Err",{enumerable:!0,get:function(){return t.Err}})}(n)),n);function l(e,t,i,a){return new(i||(i=Promise))(function(t,r){function o(e){try{s(a.next(e))}catch(e){r(e)}}function n(e){try{s(a.throw(e))}catch(e){r(e)}}function s(e){var a;e.done?t(e.value):(a=e.value,a instanceof i?a:new i(function(e){e(a)})).then(o,n)}s((a=a.apply(e,[])).next())})}"function"==typeof SuppressedError&&SuppressedError,exports.KameleoonException=void 0,(o=exports.KameleoonException||(exports.KameleoonException={})).Credentials="Credentials",o.EventSourceInitialization="EventSourceInitialization",o.FeatureFlagConfigurationNotFound="FeatureFlagConfigurationNotFound",o.FeatureFlagVariableNotFound="FeatureFlagVariableNotFound",o.FeatureFlagVariationNotFound="FeatureFlagVariationNotFound",o.FeatureFlagExperimentNotFound="FeatureFlagExperimentNotFound",o.FeatureFlagEnvironmentDisabled="FeatureFlagEnvironmentDisabled",o.VisitAmount="VisitAmount",o.VisitorCodeMaxLength="VisitorCodeMaxLength",o.VisitorCodeEmpty="VisitorCodeEmpty",o.StorageInitialization="StorageInitialization",o.StorageWrite="StorageWrite",o.StorageRead="StorageRead",o.StorageParse="StorageParse",o.StorageEmpty="StorageEmpty",o.ClientConfiguration="ClientConfiguration",o.TargetingCondition="TargetingCondition",o.AmongValuesCheck="AmongValuesCheck",o.RangeCheck="RangeCheck",o.Initialization="Initialization",o.JSONParse="JSONParse",o.NumberParse="NumberParse",o.VersionParse="VersionParse",o.CookieParse="CookieParse",o.SemanticVersionParse="SemanticVersionParse",o.RemoteData="RemoteData",o.MaximumRetriesReached="MaximumRetriesReached";const d={[exports.KameleoonException.CookieParse]:e=>`Couldn't parse cookie string: ${e}`,[exports.KameleoonException.JSONParse]:e=>`Couldn't parse JSON variable: ${e}`,[exports.KameleoonException.NumberParse]:e=>`It's not possible to parse value ${e} to Number`,[exports.KameleoonException.VersionParse]:e=>`It's not possible to parse a version value ${e} to Number, version should be in format x.x`,[exports.KameleoonException.SemanticVersionParse]:e=>`It's not possible to parse a version value ${e} to Number, version should be in format x.x.x`,[exports.KameleoonException.Initialization]:()=>"It seems that the client wasn't properly initialized, make sure to run `initialize` method before invoking other methods",[exports.KameleoonException.Credentials]:()=>"KameleoonClient can not be created without credentials",[exports.KameleoonException.StorageInitialization]:()=>"There was an error while initializing React Native SDK storage, it seems that the storage library dependency wasn't installed",[exports.KameleoonException.EventSourceInitialization]:()=>"There was an error while initializing Real Time Update service, it seems that the event source library dependency wasn't installed",[exports.KameleoonException.FeatureFlagConfigurationNotFound]:e=>`No feature flag with key ${e} was found.`,[exports.KameleoonException.FeatureFlagEnvironmentDisabled]:(e,t)=>`Feature flag with key ${e} is disabled in ${t} environment.`,[exports.KameleoonException.FeatureFlagVariableNotFound]:(e,t)=>`No feature flag variable with key ${e} was found for ${t} visitorCode.`,[exports.KameleoonException.FeatureFlagVariationNotFound]:(e,t)=>`No feature flag variation with key ${e} was found for ${t} visitorCode.`,[exports.KameleoonException.FeatureFlagExperimentNotFound]:(e,t)=>`No feature flag experiment with id ${e} was found for ${t} visitorCode.`,[exports.KameleoonException.VisitAmount]:()=>"Visit amount must be a number between 1 and 25",[exports.KameleoonException.VisitorCodeMaxLength]:()=>"Visitor code can not be more than 255 characters long",[exports.KameleoonException.VisitorCodeEmpty]:()=>"Visitor code can not be empty",[exports.KameleoonException.StorageWrite]:e=>`Couldn't update storage for kameleoonClient: ${e}`,[exports.KameleoonException.StorageRead]:e=>`No data found in storage under ${e} key`,[exports.KameleoonException.StorageEmpty]:()=>"No data found in storage",[exports.KameleoonException.StorageParse]:(e,t)=>`Couldn't parse ${t} storage data, the data may be corrupted. Error: ${e}`,[exports.KameleoonException.ClientConfiguration]:e=>`Couldn't retrieve client configuration from Kameleoon Api. Error: ${e}`,[exports.KameleoonException.TargetingCondition]:e=>`${e} targeting condition is not yet supported.`,[exports.KameleoonException.AmongValuesCheck]:(e,t)=>`Couldn't parse value "${t}": ${e}`,[exports.KameleoonException.RangeCheck]:e=>`Couldn't parse value "${e}" as a range, value should be in format [x: number, y: number]`,[exports.KameleoonException.RemoteData]:e=>`Couldn't retrieve data from Kameleoon server. Error: ${e}`,[exports.KameleoonException.MaximumRetriesReached]:e=>`Maximum retries reached, request failed. Reason: ${e}`};function c(e){throw new Error(`Reaching an impossible state because of ${e}`)}class p extends Error{constructor(e,t,i){switch(super(`Error: ${e}`),this.name="KameleoonError",this.errorType=e,e){case exports.KameleoonException.Initialization:case exports.KameleoonException.Credentials:case exports.KameleoonException.VisitorCodeMaxLength:case exports.KameleoonException.VisitorCodeEmpty:case exports.KameleoonException.StorageInitialization:case exports.KameleoonException.VisitAmount:case exports.KameleoonException.EventSourceInitialization:case exports.KameleoonException.StorageEmpty:this.message=d[e]();break;case exports.KameleoonException.CookieParse:case exports.KameleoonException.FeatureFlagConfigurationNotFound:case exports.KameleoonException.NumberParse:case exports.KameleoonException.ClientConfiguration:case exports.KameleoonException.MaximumRetriesReached:case exports.KameleoonException.RemoteData:case exports.KameleoonException.VersionParse:case exports.KameleoonException.SemanticVersionParse:this.message=d[e](t);break;case exports.KameleoonException.FeatureFlagExperimentNotFound:case exports.KameleoonException.FeatureFlagVariationNotFound:case exports.KameleoonException.FeatureFlagEnvironmentDisabled:case exports.KameleoonException.FeatureFlagVariableNotFound:this.message=d[e](t,i);break;case exports.KameleoonException.StorageWrite:case exports.KameleoonException.JSONParse:case exports.KameleoonException.StorageRead:this.message=d[e](t);break;case exports.KameleoonException.StorageParse:this.message=d[e](t,i);break;case exports.KameleoonException.TargetingCondition:this.message=d[e](t);break;case exports.KameleoonException.AmongValuesCheck:this.message=d[e](t,i);break;case exports.KameleoonException.RangeCheck:this.message=d[e](t);break;default:c(e)}}get type(){return this.errorType}}var g,h,m,v,f;!function(e){e.DataApi="dataApi",e.Events="events",e.ClientConfiguration="clientConfiguration"}(g||(g={})),exports.HttpMethod=void 0,(h=exports.HttpMethod||(exports.HttpMethod={})).Get="GET",h.Post="POST",function(e){e[e.VisitEvent=0]="VisitEvent",e[e.VisitData=1]="VisitData",e[e.DataMap=2]="DataMap"}(m||(m={})),exports.RequestType=void 0,(v=exports.RequestType||(exports.RequestType={})).Configuration="configuration",v.Tracking="tracking",v.RemoteData="remoteData",exports.Header=void 0,(f=exports.Header||(exports.Header={})).UserAgent="User-Agent",f.ContentType="Content-Type",f.SdkVersion="X-Kameleoon-SDK-Version",f.SdkType="X-Kameleoon-SDK-Type",f.Authorization="Authorization",f.AcceptEncoding="Accept-Encoding",f.IfModifiedSince="If-Modified-Since",f.LastModified="Last-Modified";const C="eventType=staticData",y="&browserIndex=",x="&browserVersion=",D="&deviceType=",E="&visitorCode=",T="&nonce=",I="&id=",S="&maxNumberPreviousVisits=",k="&os=",V="&osIndex=",R="&browser=",w="&mappingValue=",b="visit/",A={[g.DataApi]:"data.kameleoon.io",[g.Events]:"events.kameleoon.eu",[g.ClientConfiguration]:"sdk-config.kameleoon.eu"};var K;exports.LogLevel=void 0,(K=exports.LogLevel||(exports.LogLevel={}))[K.NONE=0]="NONE",K[K.ERROR=1]="ERROR",K[K.WARNING=2]="WARNING",K[K.INFO=3]="INFO",K[K.DEBUG=4]="DEBUG";const O={[exports.LogLevel.NONE]:"NONE",[exports.LogLevel.ERROR]:"ERROR",[exports.LogLevel.WARNING]:"WARNING",[exports.LogLevel.INFO]:"INFO",[exports.LogLevel.DEBUG]:"DEBUG"},$=(e,t)=>"credentials"===e?{clientId:"****",clientSecret:"****"}:t instanceof Map?Array.from(t.entries()):t;class M{static setLogger(e){M.logger=e}static setLogLevel(e){M.logLevel=e}static log({level:e,strings:t,keys:i}){if(!M.checkLevel(e))return;let a;if("string"==typeof t)a=t;else if("function"==typeof t)try{a=t()}catch(e){a="Failed to log message"}else a=function(e,t){let i="";if(t)for(let a=0;a<t.length;a++){let r=t[a];if("object"==typeof r)try{i+=e[a]+JSON.stringify(r,$)}catch(t){i+=e[a]+"{object}"}else i+="string"==typeof r?e[a]+"'"+r+"'":e[a]+r}return i+=e[e.length-1],i}(t,i);M.writeMessage(e,a)}static info(e,...t){M.log({level:exports.LogLevel.INFO,strings:e,keys:t})}static error(e,...t){M.log({level:exports.LogLevel.ERROR,strings:e,keys:t})}static warning(e,...t){M.log({level:exports.LogLevel.WARNING,strings:e,keys:t})}static debug(e,...t){M.log({level:exports.LogLevel.DEBUG,strings:e,keys:t})}static checkLevel(e){return e<=M.logLevel&&e!==exports.LogLevel.NONE}static writeMessage(e,t){M.logger.log(e,`Kameleoon [${O[e]}]: ${t}`)}}M.logger=new class{log(e,t){switch(e){case exports.LogLevel.DEBUG:console.debug(t);break;case exports.LogLevel.INFO:console.info(t);break;case exports.LogLevel.WARNING:console.warn(t);break;case exports.LogLevel.ERROR:console.error(t)}}},M.logLevel=exports.LogLevel.WARNING;let F=class{constructor({urlProvider:e,packageInfo:t,externalRequester:i,requestTimeout:a,trackRetryDelay:r,useAbortController:o}){M.debug`CALL: new Requester(urlProvider, packageInfo: ${t}, externalRequester, requestTimeout: ${a}, trackRetryDelay: ${r}, useAbortController: ${o})`,this.urlProvider=e,this.useAbortController=o,this.externalRequester=i,this.trackRetryDelay=r,this.packageInfo=t,this.timeout=a,M.debug`RETURN: new Requester(urlProvider, packageInfo: ${t}, externalRequester, requestTimeout: ${a}, trackRetryDelay: ${r}, useAbortController: ${o})`}getClientConfiguration(e,t){return l(this,0,void 0,function*(){const i=this.urlProvider.getClientConfigurationUrl(e);let a=Object.assign({[exports.Header.SdkType]:this.packageInfo.type.toLowerCase(),[exports.Header.SdkVersion]:this.packageInfo.version},t&&{[exports.Header.IfModifiedSince]:t});try{let e={message:""};M.debug`Running configuration request Method: ${exports.HttpMethod.Get}, Url: ${i}, Headers: ${a}, with retry limit ${3}`;for(let t=0;t<3;t++){const r=yield this.sendRequest({url:i,requestType:exports.RequestType.Configuration,retryCount:t,parameters:{method:exports.HttpMethod.Get,headers:a}});if(r.ok){const e=yield r.json();this.logReceivedConfigurationResponse(r.status,i,a);const t=this.getLastModifiedHeader(r),o=e;return u.Ok({configuration:o,lastModified:t})}if(304===r.status)return this.logReceivedConfigurationResponse(r.status,i,a),u.Ok({});if(2===t){if(r.text){const t=yield r.text();e=JSON.parse(t)}M.error`Failed to get configuration response ${{status:r.status,message:e.message}} for request Method: ${exports.HttpMethod.Get}, Url: ${i}, Headers: ${a}`}else yield this.logRequestError({logLevel:exports.LogLevel.WARNING,message:"Failed to get configuration response",response:r,method:exports.HttpMethod.Get,url:i})}return u.Err(new p(exports.KameleoonException.MaximumRetriesReached,e.message))}catch(e){return yield this.logRequestError({logLevel:exports.LogLevel.ERROR,message:"Failed to get configuration response",error:e,method:exports.HttpMethod.Get,url:i,headers:a}),u.Err(new p(exports.KameleoonException.ClientConfiguration,e))}})}getRemoteData(e){var t;return l(this,0,void 0,function*(){const i=this.urlProvider.getRemoteDataUrl(e);M.debug`Running remote data request Method: ${exports.HttpMethod.Get}, Url: ${i}`;try{const e=yield this.sendRequest({url:i,requestType:exports.RequestType.RemoteData,retryCount:0,parameters:{method:exports.HttpMethod.Get}});if(!e.ok){if(yield this.logRequestError({logLevel:exports.LogLevel.ERROR,message:"Failed to get remote data response",response:e,method:exports.HttpMethod.Get,url:i}),e.text){const i=yield e.text(),a=null===(t=JSON.parse(i))||void 0===t?void 0:t.message;return u.Err(new p(exports.KameleoonException.RemoteData,a))}return u.Err(new p(exports.KameleoonException.RemoteData,"Unknown Reason - no `text()` was found for a response"))}const a=yield e.json();return M.debug`Received remote data response: ${{status:e.status}} for request Method: ${exports.HttpMethod.Get}, Url: ${i}`,u.Ok(a)}catch(e){return yield this.logRequestError({logLevel:exports.LogLevel.ERROR,message:"Failed to get remote data response",error:e,method:exports.HttpMethod.Get,url:i}),u.Err(new p(exports.KameleoonException.RemoteData,e))}})}getVisitorData({visitorCode:e,filters:t,isMappingIdentifier:i}){var a;return l(this,0,void 0,function*(){const r=this.urlProvider.getVisitorDataUrl({visitorCode:e,filters:t,isMappingIdentifier:i});M.debug`Running visitor data request Method: ${exports.HttpMethod.Get}, Url: ${r}`;try{const e=yield this.sendRequest({url:r,requestType:exports.RequestType.RemoteData,retryCount:0,parameters:{method:exports.HttpMethod.Get}});if(!e.ok){if(yield this.logRequestError({logLevel:exports.LogLevel.ERROR,message:"Failed to get visitor data response",response:e,method:exports.HttpMethod.Get,url:r}),"function"==typeof e.text){const t=yield e.text();if(t){const e=null===(a=JSON.parse(t))||void 0===a?void 0:a.message;return u.Err(new p(exports.KameleoonException.RemoteData,e))}}return e.status?u.Err(new p(exports.KameleoonException.RemoteData,`No error message. Error status: ${e.status}`)):u.Err(new p(exports.KameleoonException.RemoteData,"Unknown Reason - no text message or error status was found for a response"))}const t=yield e.json();return M.debug`Received visitor data response: ${{status:e.status}} for request Method: ${exports.HttpMethod.Get}, Url: ${r}`,u.Ok(t)}catch(e){return yield this.logRequestError({logLevel:exports.LogLevel.ERROR,message:"Failed to get visitor data response",error:e,method:exports.HttpMethod.Get,url:r}),u.Err(new p(exports.KameleoonException.RemoteData,e))}})}track(e,t){return l(this,0,void 0,function*(){const i=this.urlProvider.getTrackingUrl(t);M.debug`Running tracking request Method: ${exports.HttpMethod.Post}, Url: ${i}, Body: ${e}, with retry limit ${3}, retry delay ${this.trackRetryDelay} ms`;for(let t=0;t<3;t++){let a;try{if(a=yield this.sendRequest({url:i,retryCount:t,requestType:exports.RequestType.Tracking,parameters:{body:e,method:exports.HttpMethod.Post,headers:{[exports.Header.ContentType]:"*/*"}}}),a.ok)return M.debug`Received tracking response: ${{status:a.status}} for request Method: ${exports.HttpMethod.Post}, Url: ${i}, Body: ${e}`,u.Ok();yield this.logRequestError({logLevel:2==t?exports.LogLevel.ERROR:exports.LogLevel.WARNING,message:"Failed to get tracking response",response:a,method:exports.HttpMethod.Post,url:i})}catch(e){yield this.logRequestError({logLevel:2==t?exports.LogLevel.ERROR:exports.LogLevel.WARNING,message:"Failed to get tracking response",error:e,method:exports.HttpMethod.Post,url:i})}t<3&&(yield new Promise(e=>setTimeout(e,this.trackRetryDelay)))}return u.Err()})}sendRequest({url:e,requestType:t,retryCount:i,parameters:a}){return l(this,0,void 0,function*(){let r;if(this.useAbortController){const o=new AbortController,n=setTimeout(()=>o.abort(),this.timeout);r=yield this.externalRequester.sendRequest({url:e,retryCount:i,requestType:t,parameters:Object.assign(Object.assign({},a),{signal:o.signal})}),clearTimeout(n)}else r=yield this.externalRequester.sendRequest({url:e,retryCount:i,requestType:t,parameters:a});return r})}logRequestError({logLevel:e,message:t,error:i,method:a,url:r,response:o,headers:n}){return l(this,0,void 0,function*(){if(i){let o="Unknown error";i instanceof Error&&(o=i.message),M.log({level:e,strings:()=>`${t} with error: ${o} for request Method: ${a}, Url: ${r}`})}else if(o&&M.checkLevel(e)){const i=yield this.parseResponse(o);M.log({level:e,strings:()=>`${t} response: Status: '${i.status}' Message: '${i.message}' for request Method: ${a}, Url: '${r}'`+(n?`, Headers: ${n}`:"")})}})}parseResponse(e){return l(this,0,void 0,function*(){let t="";try{if("function"==typeof e.text){const i=yield e.text();i&&(t=i)}}catch(e){}return{status:e.status,message:t}})}getLastModifiedHeader(e){if(e.headers){const t=exports.Header.LastModified.toLowerCase();for(const[i,a]of e.headers)if(i.toLowerCase()===t)return a}}logReceivedConfigurationResponse(e,t,i){M.debug`Received configuration response: ${{status:e}} for request Method: ${exports.HttpMethod.Get}, Url: ${t}, Headers: ${i}`}};var N,L,U,_,P,G,B,z,q,j,H;exports.Environment=void 0,(N=exports.Environment||(exports.Environment={})).Production="production",N.Staging="staging",N.Development="development";class W{constructor(){this.ready=!1,this.isCustomDomain=!1,this.domains=A}initialize({domain:e,siteCode:t,packageInfo:i,environment:a}){this.siteCode=t,this.environment=a,this.packageInfo=i,this.ready=!0,this.setDomains(e)}set dataApiDomain(e){if(!this.isCustomDomain)return void(this.domains[g.DataApi]=e);const t=e.split(".")[0],i=this.domains[g.DataApi];this.domains[g.DataApi]=i.replace(/^[^.]+/,t)}getClientConfigurationUrl(e){this.isInitialized();const t=`https://${this.domains[g.ClientConfiguration]}/v3/`,i=this.environment===exports.Environment.Production?"":"?environment="+encodeURIComponent(this.environment);let a="";return e&&(a=i?"&ts="+e:"?ts="+e),t+this.siteCode+i+a}getEventSourceUrl(){return this.isInitialized(),`https://${this.domains[g.Events]}:8110/sse?siteCode=${this.siteCode}`}getRemoteDataUrl(e){return this.isInitialized(),this.getDataApiUrl(m.DataMap)+this.siteCode+"&key="+encodeURI(e)}getVisitorDataUrl({visitorCode:e,filters:t,isMappingIdentifier:i}){this.isInitialized();const{customData:a,previousVisitAmount:r,currentVisit:o,conversions:n,geolocation:s,experiments:u,pageViews:l,device:d,browser:c,operatingSystem:p,kcs:g,personalization:h,visitorCode:v,cbs:f}=t,C=i?w:E,y=a||v?"&customData="+!0:"",x=n?"&conversion="+!0:"",D=s?"&geolocation="+!0:"",T=u?"&experiment="+!0:"",I=l?"&page="+!0:"",k="&staticData="+!0,V=o?"&currentVisit="+!0:"",R=g?"&kcs="+!0:"",b=h?"&personalization="+!0:"",A="number"!=typeof r?S+1:S+r,K=f?"&cbs="+!0:"";return this.getDataApiUrl(m.VisitData)+this.siteCode+C+e+A+y+x+D+T+I+k+V+R+b+K}getTrackingUrl(e){this.isInitialized();const{type:t,version:i}=this.packageInfo;let a=this.getDataApiUrl(m.VisitEvent)+this.siteCode+"&sdkName="+t.toLowerCase()+"&sdkVersion="+i;return e&&(a+="&bodyUa="+!0),a}isInitialized(){if(!this.ready)throw new Error("UrlProvider is not initialized")}getDataApiUrl(e){if(!this.domains[g.DataApi])throw new Error("Data API domain is not set");const t=`https://${this.domains[g.DataApi]}`;switch(e){case m.VisitEvent:return`${t}/${b+"events?siteCode="}`;case m.VisitData:return`${t}/${b+"visitor?siteCode="}`;case m.DataMap:return`${t}/map/map?siteCode=`}}setDomains(e){e&&(this.isCustomDomain=!0,this.domains[g.DataApi]="data."+e,this.domains[g.Events]="events."+e,this.domains[g.ClientConfiguration]="sdk-config."+e)}}exports.VariableType=void 0,(L=exports.VariableType||(exports.VariableType={})).BOOLEAN="BOOLEAN",L.NUMBER="NUMBER",L.STRING="STRING",L.JSON="JSON",L.JS="JS",L.CSS="CSS",exports.TrackingStatus=void 0,(U=exports.TrackingStatus||(exports.TrackingStatus={})).Sent="sent",U.Unsent="unsent",U.Pending="pending",exports.Milliseconds=void 0,(_=exports.Milliseconds||(exports.Milliseconds={}))[_.Second=1e3]="Second",_[_.Minute=6e4]="Minute",_[_.Hour=36e5]="Hour",_[_.Day=864e5]="Day",_[_.Week=6048e5]="Week",_[_.Month=2592e6]="Month";class J{constructor(e){this.cacheMap=new Map,this.intervalId=null,this.cleanupTimeout=e*exports.Milliseconds.Second}add({key:e,data:t,lifetime:i}){M.debug`CALL: CacheManager.add(key: ${e}, data: ${t}, lifetime: ${i})`,null===this.intervalId&&this.activate();const a=i*exports.Milliseconds.Second,r={data:t,expirationTime:Date.now()+a};this.cacheMap.set(e,r),M.debug`RETURN: CacheManager.add(key: ${e}, data: ${t}, lifetime: ${i})`}getAliveItem(e){M.debug`CALL: CacheManager.getAliveItem(key: ${e})`;const t=this.cacheMap.get(e);if(t&&t.expirationTime>=Date.now()){const i=t.data;return M.debug`RETURN: CacheManager.getAliveItem(key: ${e}) -> (item: ${i})`,i}return t&&this.cacheMap.delete(e),M.debug`RETURN: CacheManager.getAliveItem(key: ${e}) -> (item: null)`,null}activate(){this.intervalId=setInterval(()=>{const e=Date.now();for(const[t,i]of this.cacheMap)i.expirationTime<e&&this.cacheMap.delete(t);this.cacheMap.size||this.cleanupInterval()},this.cleanupTimeout)}cleanupInterval(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null)}}!function(e){e[e.Polling=0]="Polling",e[e.RealTime=1]="RealTime"}(P||(P={})),function(e){e.TARGETED_DELIVERY="TARGETED_DELIVERY",e.EXPERIMENTATION="EXPERIMENTATION"}(G||(G={})),function(e){e.ANDROID="ANDROID",e.SWIFT="SWIFT",e.JAVA="JAVA",e.CSHARP="CSHARP",e.NODEJS="NODEJS",e.PHP="PHP",e.RUBY="RUBY",e.GO="GO",e.FLUTTER="FLUTTER",e.REACTJS="REACTJS"}(B||(B={})),function(e){e.ACTIVATED="ACTIVATED",e.DEACTIVATED="DEACTIVATED",e.SCHEDULED="SCHEDULED"}(z||(z={})),exports.CustomDataScope=void 0,(q=exports.CustomDataScope||(exports.CustomDataScope={})).Visit="VISIT",q.Visitor="VISITOR",q.Page="Page",function(e){e.Required="REQUIRED",e.NotRequired="NOT_REQUIRED"}(j||(j={}));class Y{addEventHandler(e,t){this.eventHandlers||(this.eventHandlers=new Map),this.eventHandlers.set(e,t)}fireEvent(e,t){var i;const a=null===(i=this.eventHandlers)||void 0===i?void 0:i.get(e);a&&t&&a(t)}}exports.EventType=void 0,(H=exports.EventType||(exports.EventType={})).Evaluation="evaluation",H.ConfigurationUpdate="configurationUpdate",j.NotRequired;const X={customData:[],featureFlags:[],configuration:{realTimeUpdate:!1,consentType:j.NotRequired,dataApiDomain:"data.kameleoon.io"}};class Q{constructor(e){this._featureFlags=e.slice().sort((e,t)=>e.id-t.id)}getFeatureFlagByHash(e){let t=Math.floor(e*this._featureFlags.length);return t=Math.min(t,this._featureFlags.length-1),this._featureFlags[t]}get featureFlags(){return this._featureFlags}}class Z{constructor({updateInterval:e,urlProvider:t,storage:i,requester:a,dataManager:r,eventSource:o,externalVisitorCodeManager:n,eventManager:s,externalPackageInfo:u,defaultDataFile:l}){this.updateConfigurationIntervalId=null,this.updateType=P.Polling,this.configurationData=X,this.featureFlagsData=new Map,this.isTargetedDeliveryRule=null,this.segmentsData=null,this.holdoutData=null,this.meGroupsData=new Map,this.mappedRules=null,this.mappedExperiments=null,this.usedDefaultDataFile=!1,this.CACHE_REVALIDATE_PERIOD=90*exports.Milliseconds.Minute,this.urlProvider=t,this.requester=a,this.updateInterval=e,this.lastUpdate=new Date,this.storage=i,this.dataManager=r,this.eventManager=s,this.visitorCodeManager=n,this.eventSource=o,this.externalPackageInfo=u,this.defaultDataFile=l}initialize(){return l(this,0,void 0,function*(){if(M.debug("CALL: ClientConfiguration.initialize()"),this.readStorageData(),this.checkShouldUpdate()){const e=yield this.updateClientConfiguration();if(!e.ok)return M.error("Error occurred during client configuration update"),e;if(e.data)return M.debug("RETURN: ClientConfiguration.initialize()"),u.Ok()}return this.updateType!==P.RealTime||this.eventSource.isOpen?(this.updateType===P.Polling&&this.handlePollingUpdates(),M.debug("RETURN: ClientConfiguration.initialize()"),u.Ok()):(this.handleRealTimeUpdates(),M.debug("RETURN: ClientConfiguration.initialize()"),u.Ok())})}cleanupHandlers(){this.eventSource.isOpen&&this.eventSource.close(),this.updateConfigurationIntervalId&&clearInterval(this.updateConfigurationIntervalId)}handleRealTimeUpdates(){this.cleanupHandlers(),this.eventSource.open(e=>{this.updateClientConfiguration(e).then(t=>{t.ok&&this.eventManager.fireEvent(exports.EventType.ConfigurationUpdate,{timestamp:e})})}),this.eventSource.onError(e=>{M.error`Error occurred during real-time update: ${e}. Switching to polling updates while the connection is not restored.`,this.updateType=P.Polling,this.handlePollingUpdates()})}handlePollingUpdates(){this.cleanupHandlers();try{const e=this.lastUpdate.getTime(),t=Date.now(),i=Math.max(this.updateInterval-(t-e),0);setTimeout(()=>l(this,0,void 0,function*(){yield this.updateClientConfiguration(),this.updateConfigurationIntervalId=setInterval(this.updateClientConfiguration.bind(this),this.updateInterval)}),i)}catch(e){throw this.updateConfigurationIntervalId&&clearInterval(this.updateConfigurationIntervalId),e}}get featureFlags(){return this.featureFlagsData}get configuration(){return this.configurationData.configuration}get segments(){if(this.segmentsData)return this.segmentsData;const e=new Map;return this.featureFlagsData.forEach(t=>{t.rules.forEach(t=>{t.segment&&!e.has(t.segment.id.toString())&&e.set(t.segment.id.toString(),t.segment)})}),this.segmentsData=e,e}get ruleMap(){var e;if(null===(e=this.mappedRules)||void 0===e?void 0:e.size)return this.mappedRules;const t=new Map;for(const e of this.featureFlags.values())for(const i of e.rules){const{id:a,experimentId:r,variationByExposition:o}=i,n=new Map;o.forEach(({variationKey:e,variationId:t})=>{"number"==typeof t&&n.set(e,t)}),t.set(a,{featureId:e.id,experimentId:r,variations:n})}return this.mappedRules=t,t}get experimentMap(){var e;if(null===(e=this.mappedExperiments)||void 0===e?void 0:e.size)return this.mappedExperiments;const t=new Map;for(const e of this.featureFlags.values())for(const i of e.rules){const{experimentId:e,variationByExposition:a}=i,r=new Map;a.forEach(({variationKey:e,variationId:t})=>{"number"==typeof t&&r.set(e,t)}),t.set(e,{type:i.type,variations:r})}return this.mappedExperiments=t,t}get holdout(){return this.holdoutData}get meGroups(){return this.meGroupsData}get isConsentRequired(){return this.configuration.consentType===j.Required}get hasAnyTargetedDeliveryRule(){if(null!==this.isTargetedDeliveryRule)return this.isTargetedDeliveryRule;for(const e of this.featureFlags.values())if(e.environmentEnabled&&e.rules.some(e=>e.type===G.TARGETED_DELIVERY))return!0;return!1}checkShouldUpdate(){const{configuration:e}=this.configurationData;return this.updateType=e.realTimeUpdate?P.RealTime:P.Polling,!this.featureFlags.size||this.lastUpdate.getTime()<Date.now()-this.updateInterval}readStorageData(){var e,t,i;M.debug("CALL: ClientConfiguration.readStorageData()");const a=this.storage.read();if(a.ok){let{data:r,lastUpdate:o,lastModified:n,requestTime:s}=a.data,u=!1;if(this.defaultDataFile)try{const a=JSON.parse(this.defaultDataFile);this.defaultDataFile=void 0,this.usedDefaultDataFile=!0;const o=null!==(t=null!==(e=r.dateModified)&&void 0!==e?e:s)&&void 0!==t?t:-1,n=null!==(i=a.dateModified)&&void 0!==i?i:0;(!s||n>o)&&(r=a,u=!0)}catch(e){M.error`Error parsing default data file: ${String(e)}`}this.updateConfigurationData(r,u),this.lastUpdate=this.usedDefaultDataFile?new Date(0):new Date(Date.parse(o)),this.lastModified=n,this.requestTime=s}M.debug`RETURN: ClientConfiguration.readStorageData() -> (result: ${a.ok})`}updateClientConfiguration(e){return l(this,0,void 0,function*(){const t=Date.now();if(this.usedDefaultDataFile)return this.updateClientConfigurationInBackground(),u.Ok(!1);if(this.requestTime&&!e&&!this.externalPackageInfo.isServer){if(t-this.requestTime<=this.CACHE_REVALIDATE_PERIOD)return this.updateClientConfigurationInBackground(),u.Ok(!1);M.debug`Cached configuration data has expired. Fetching fresh data.`}const i=yield this.requester.getClientConfiguration(e,this.lastModified);return this.applyNewConfigurationDataFromResponse(i)})}updateClientConfigurationInBackground(){setTimeout(()=>l(this,0,void 0,function*(){const e=yield this.requester.getClientConfiguration(void 0,this.lastModified);yield this.applyNewConfigurationDataFromResponse(e)}),0)}applyNewConfigurationDataFromResponse(e){var t,i;return l(this,0,void 0,function*(){if(this.requestTime=Date.now(),!e.ok)return this.featureFlags.size?(M.error("Error occurred while updating configuration. Existing configuration will be used as a fallback."),u.Ok(!0)):e;if(void 0===e.data.configuration)return this.updateStorageData(),u.Ok(!1);const a=e.data.configuration;this.updateConfigurationData(a,!0),this.dataManager.clearTrees(),null===(t=this.mappedRules)||void 0===t||t.clear(),null===(i=this.experimentMap)||void 0===i||i.clear(),this.isTargetedDeliveryRule=null,e.data.lastModified&&(this.lastModified=e.data.lastModified);const r=this.updateStorageData();if(!r.ok)return r;const o=a.configuration.realTimeUpdate?P.RealTime:P.Polling,n=o!==this.updateType;return n&&(this.updateType=o,M.info`Configuration update type was toggled to ${P[o]}`,yield this.initialize()),u.Ok(n)})}updateConfigurationData(e,t=!0){const{configuration:i,featureFlags:a,customData:r,holdout:o,segments:n,dateModified:s}=e;let u=n?new Map(n.map(e=>[e.id.toString(),e])):null,l=null;if(t&&(null==r?void 0:r.length)){l=new Map;for(let e of r){if(void 0===e.id){l=null;break}l.set(e.id,e.index)}}const d=new Map;for(const e of a)d.set(e.featureKey,e),t&&(this.updateFeatureFlagSegments(e,u),this.updateFeatureFlagBucketingCustomDataId(e,l));this.featureFlagsData=d,(null==r?void 0:r.length)&&(this.dataManager.customDataIndexes=r),this.meGroupsData=this.makeMEGroups(a),this.holdoutData=null!=o?o:null,this.configurationData={configuration:i,customData:r,holdout:o,dateModified:s},this.urlProvider.dataApiDomain=e.configuration.dataApiDomain,this.updateConsentRequired(),this.segmentsData=u}updateFeatureFlagSegments(e,t){null!==t&&e.rules.forEach(e=>{var i;const a=e.segmentId;e.segment=null!=a&&null!==(i=t.get(a.toString()))&&void 0!==i?i:null})}updateFeatureFlagBucketingCustomDataId(e,t){const i=e.bucketingCustomDataId;null!=i&&t&&(e.bucketingCustomDataIndex=t.get(i))}makeMEGroups(e){const t=new Map;e.forEach(e=>{const i=e.mutuallyExclusiveGroup;if(i){let a=t.get(i);a?a.push(e):t.set(i,[e])}});const i=new Map;return t.forEach((e,t)=>{i.set(t,new Q(e))}),i}updateStorageData(){this.lastUpdate=new Date;const e={data:Object.assign(Object.assign({},this.configurationData),{featureFlags:Array.from(this.featureFlags.values()),segments:this.segmentsData?Array.from(this.segmentsData.values()):void 0}),lastUpdate:this.lastUpdate.toString(),lastModified:this.lastModified,requestTime:this.requestTime};return this.storage.write(e)}updateConsentRequired(){this.visitorCodeManager.consentRequired=this.isConsentRequired&&!this.hasAnyTargetedDeliveryRule}}function ee(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e]))}var te,ie,ae,re;exports.KameleoonData=void 0,(te=exports.KameleoonData||(exports.KameleoonData={})).UniqueIdentifier="uniqueIdentifier",te.CustomData="customData",te.PageView="pageView",te.GeolocationData="geolocation",te.Browser="browser",te.Conversion="conversion",te.Cookie="cookie",te.Device="device",te.OperatingSystem="operatingSystem",te.UserAgent="userAgent",te.ApplicationVersion="applicationVersion",te.VisitsData="visitsData",te.KameleoonConversionScore="kameleoonConversionScore",te.Personalization="personalization",te.CBScores="cbScores",te.TargetedSegment="targetedSegment",exports.DeviceType=void 0,(ie=exports.DeviceType||(exports.DeviceType={})).Phone="PHONE",ie.Tablet="TABLET",ie.Desktop="DESKTOP",exports.OperatingSystemType=void 0,(ae=exports.OperatingSystemType||(exports.OperatingSystemType={})).WindowsPhone="WINDOWS_PHONE",ae.Windows="WINDOWS",ae.Android="ANDROID",ae.Linux="LINUX",ae.Mac="MAC",ae.IOS="IOS",exports.BrowserType=void 0,(re=exports.BrowserType||(exports.BrowserType={})).Chrome="CHROME",re.InternetExplorer="IE",re.Firefox="FIREFOX",re.Safari="SAFARI",re.Opera="OPERA",re.Other="OTHER";const oe={[exports.OperatingSystemType.Windows]:0,[exports.OperatingSystemType.Mac]:1,[exports.OperatingSystemType.IOS]:2,[exports.OperatingSystemType.Linux]:3,[exports.OperatingSystemType.Android]:4,[exports.OperatingSystemType.WindowsPhone]:5},ne=ee(oe),se={[exports.BrowserType.Chrome]:0,[exports.BrowserType.InternetExplorer]:1,[exports.BrowserType.Firefox]:2,[exports.BrowserType.Safari]:3,[exports.BrowserType.Opera]:4,[exports.BrowserType.Other]:5},ue=ee(se),le="off",de="warehouseAudiences";var ce;exports.SdkLanguageType=void 0,(ce=exports.SdkLanguageType||(exports.SdkLanguageType={})).ANDROID="ANDROID",ce.IOS="IOS",ce.JAVA="JAVA",ce.CSHARP="CSHARP",ce.NODEJS="NODEJS",ce.PHP="PHP",ce.RUBY="RUBY",ce.GO="GO",ce.FLUTTER="FLUTTER",ce.REACT="REACT",ce.PYTHON="PYTHON",ce.JAVASCRIPT="JAVASCRIPT",ce.RUST="RUST";const pe={previousVisitAmount:1,currentVisit:!0,customData:!0,pageViews:!1,geolocation:!1,device:!1,browser:!1,operatingSystem:!1,conversions:!1,experiments:!1,kcs:!1,visitorCode:!0,personalization:!1};var ge,he,me,ve,fe,Ce,ye,xe,De,Ee,Te,Ie;!function(e){e.And="AND",e.Or="OR"}(ge||(ge={})),function(e){e.TRUE="TRUE",e.FALSE="FALSE",e.EXACT="EXACT",e.CONTAINS="CONTAINS",e.REGULAR_EXPRESSION="REGULAR_EXPRESSION",e.EQUAL="EQUAL",e.LOWER="LOWER",e.GREATER="GREATER",e.UNDEFINED="UNDEFINED",e.AMONG_VALUES="AMONG_VALUES",e.RANGE="RANGE"}(he||(he={})),function(e){e.NEW="NEW",e.RETURNING="RETURNING"}(me||(me={})),function(e){e.ANY="ANY",e.EXACT="EXACT"}(ve||(ve={})),function(e){e.ALL="ALL",e.TEST="TEST",e.PERSO="PERSO"}(fe||(fe={})),function(e){e.Experiment="EXPERIMENT",e.Personalization="PERSONALIZATION",e.Any="ANY"}(Ce||(Ce={})),function(e){e.EXACT="EXACT",e.CONTAINS="CONTAINS",e.REGULAR_EXPRESSION="REGULAR_EXPRESSION",e.GREATER="GREATER",e.EQUAL="EQUAL",e.LOWER="LOWER"}(ye||(ye={})),function(e){e.GREATER="GREATER",e.EQUAL="EQUAL",e.LOWER="LOWER"}(xe||(xe={})),function(e){e.EXACT="EXACT",e.CONTAINS="CONTAINS",e.REGULAR_EXPRESSION="REGULAR_EXPRESSION",e.OPTIONAL="OPTIONAL"}(De||(De={})),function(e){e.PAGE_URL="PAGE_URL",e.PAGE_TITLE="PAGE_TITLE",e.LANDING_PAGE="LANDING_PAGE",e.ORIGIN="ORIGIN",e.ORIGIN_TYPE="ORIGIN_TYPE",e.REFERRERS="REFERRERS",e.NEW_VISITORS="NEW_VISITORS",e.INTERESTS="INTERESTS",e.BROWSER_LANGUAGE="BROWSER_LANGUAGE",e.GEOLOCATION="GEOLOCATION",e.DEVICE_TYPE="DEVICE_TYPE",e.SCREEN_DIMENSION="SCREEN_DIMENSION",e.VISITOR_IP="VISITOR_IP",e.AD_BLOCKER="AD_BLOCKER",e.PREVIOUS_PAGE="PREVIOUS_PAGE",e.KEY_PAGES="KEY_PAGES",e.PAGE_VIEWS="PAGE_VIEWS",e.FIRST_VISIT="FIRST_VISIT",e.LAST_VISIT="LAST_VISIT",e.ACTIVE_SESSION="ACTIVE_SESSION",e.TIME_SINCE_PAGE_LOAD="TIME_SINCE_PAGE_LOAD",e.SAME_DAY_VISITS="SAME_DAY_VISITS",e.VISITS="VISITS",e.VISITS_BY_PAGE="VISITS_BY_PAGE",e.VISITOR_CODE="VISITOR_CODE",e.SDK_LANGUAGE="SDK_LANGUAGE",e.INTERNAL_SEARCH_KEYWORDS="INTERNAL_SEARCH_KEYWORDS",e.TABS_ON_SITE="TABS_ON_SITE",e.CONVERSION_PROBABILITY="CONVERSION_PROBABILITY",e.HEAT_SLICE="HEAT_SLICE",e.SKY_STATUS="SKY_STATUS",e.TEMPERATURE="TEMPERATURE",e.DAY_NIGHT="DAY_NIGHT",e.FORECAST_SKY_STATUS="FORECAST_SKY_STATUS",e.FORECAST_TEMPERATURE="FORECAST_TEMPERATURE",e.DAY_OF_WEEK="DAY_OF_WEEK",e.TIME_RANGE="TIME_RANGE",e.HOUR_MINUTE_RANGE="HOUR_MINUTE_RANGE",e.JS_CODE="JS_CODE",e.COOKIE="COOKIE",e.EVENT="EVENT",e.BROWSER="BROWSER",e.OPERATING_SYSTEM="OPERATING_SYSTEM",e.DOM_ELEMENT="DOM_ELEMENT",e.MOUSE_OUT="MOUSE_OUT",e.TARGET_EXPERIMENT="TARGET_EXPERIMENT",e.TARGET_FEATURE_FLAG="TARGET_FEATURE_FLAG",e.TARGET_PERSONALIZATION="TARGET_PERSONALIZATION",e.EXCLUSIVE_EXPERIMENT="EXCLUSIVE_EXPERIMENT",e.CONVERSIONS="CONVERSIONS",e.CUSTOM_DATUM="CUSTOM_DATUM",e.YSANCE_SEGMENT="YSANCE_SEGMENT",e.SEGMENT="SEGMENT",e.YSANCE_ATTRIBUT="YSANCE_ATTRIBUT",e.TEALIUM_BADGE="TEALIUM_BADGE",e.TEALIUM_AUDIENCE="TEALIUM_AUDIENCE",e.PRICE_OF_DISPLAYED_PAGE="PRICE_OF_DISPLAYED_PAGE",e.NUMBER_OF_VISITED_PAGES="NUMBER_OF_VISITED_PAGES",e.VISITED_PAGES="VISITED_PAGES",e.CUSTOM="CUSTOM",e.EXPLICIT_TRIGGER="EXPLICIT_TRIGGER",e.APPLICATION_VERSION="APPLICATION_VERSION"}(Ee||(Ee={})),function(e){e.Minute="MINUTE",e.Hour="HOUR",e.Day="DAY",e.Week="WEEK",e.Month="MONTH"}(Te||(Te={})),function(e){e.Ascending="asc",e.Descending="desc"}(Ie||(Ie={}));const Se="localhost",ke=/^(\.?(([a-zA-Z\d][a-zA-Z\d-]*[a-zA-Z\d])|[a-zA-Z\d]))(\.(([a-zA-Z\d][a-zA-Z\d-]*[a-zA-Z\d])|[a-zA-Z\d])){1,126}$/;class Ve{static validateVersion(e){const t=e.split(".").map(e=>parseInt(e,10));for(;t.length<3;)t.push(0);return t.some(e=>isNaN(e))?u.Err(new p(exports.KameleoonException.SemanticVersionParse,e)):u.Ok(t.slice(0,3))}static validateDomain(e){return e?(e=Ve.checkAndTrimProtocol(e.toLowerCase()),ke.test(e)||e===Se||M.error`The top-level domain ${e} is invalid. The value has been set as provided, but it does not meet the required format for proper SDK functionality. Please check the domain for correctness.`,u.Ok(e)):u.Err()}static validateNetworkDomain(e){return e?(e=(e=Ve.checkAndTrimProtocol(e.toLowerCase())).replace(/^\.+|\.+$/g,""),ke.test(e)||e===Se?u.Ok(e):(M.error`The network domain ${e} is invalid.`,u.Err())):u.Err()}static checkAndTrimProtocol(e){const t=["http://","https://"];for(const i of t)if(e.startsWith(i)){e=e.substring(i.length),M.warning`The domain contains ${i}. Domain after protocol trimming: ${e}`;break}return e}}class Re{static getNonce(e){let t="";for(let i=0;i<16;i++){const i=e.getRandomNumber(),a=Math.floor(16*i);t+="0123456789ABCDEF".charAt(a)}return t}static checkTargeting({segment:e,visitorCode:t,targetingData:i,experimentId:a,variationConfiguration:r,clientConfiguration:o,packageInfo:n,dataManager:s}){if(M.debug`CALL: checkTargeting(segment, visitorCode: ${t}, targetingData: ${i}, experimentId: ${a}, variationConfiguration, clientConfiguration, packageInfo, dataManager)`,!e||!e.conditionsData.firstLevel.length){const e=u.Ok(!0);return M.debug`RETURN checkTargeting(segment, visitorCode: ${t}, targetingData: ${i}, experimentId: ${a}, variationConfiguration, clientConfiguration, packageInfo, dataManager) -> (result: ${e})`,e}if(!r){const e=u.Err(new p(exports.KameleoonException.Initialization));return M.debug`RETURN checkTargeting(segment, visitorCode: ${t}, targetingData: ${i}, experimentId: ${a}, variationConfiguration, clientConfiguration, packageInfo, dataManager) -> (result: ${e})`,e}let l={};const d=r.getStoredVariations(t);d.ok&&(l=d.data);const c=s.getTree(e);let g,h,m;c.hasTargetingType(Ee.SEGMENT)&&(g=s.trees,m=o.segments),c.hasTargetingType(Ee.TARGET_FEATURE_FLAG)&&(h=o.ruleMap);const v=c.evaluate({variationData:l,sdkInfo:n,segments:m,ruleMap:h,trees:g,targetingData:i,experimentId:a,visitorCode:t});return M.debug`RETURN checkTargeting(segment, visitorCode: ${t}, targetingData: ${i}, experimentId: ${a}, variationConfiguration, clientConfiguration, packageInfo, dataManager) -> (result: ${v})`,v}static convertTimeUnit(e,t){return e/{[Te.Minute]:exports.Milliseconds.Minute,[Te.Hour]:exports.Milliseconds.Hour,[Te.Day]:exports.Milliseconds.Day,[Te.Week]:exports.Milliseconds.Week,[Te.Month]:exports.Milliseconds.Month}[t]}static isCustomData(e){return e.data.type===exports.KameleoonData.CustomData}static updateCache({hasJsCssVariables:e,cacheManager:t,visitorCode:i,experimentId:a,variationId:r}){const o=t.getAliveItem(i),n=o?Object.assign({},o):{};n[a]={variationId:r,hasJsCssVariables:e,expirationTime:Date.now()+5*exports.Milliseconds.Second},t.add({key:i,data:n,lifetime:5})}static getTrackingCode(e,t){let i="window.kameleoonQueue=window.kameleoonQueue||[];";const a=e.getAliveItem(t);if(!a)return i;const r={};return Object.entries(a).forEach(([e,{variationId:t,expirationTime:a,hasJsCssVariables:o}])=>{const n=!o;a>Date.now()&&(i+=`window.kameleoonQueue.push(['Experiments.assignVariation',${e},${t},true]);`,i+=`window.kameleoonQueue.push(['Experiments.trigger',${e},${n}]);`,r[Number(e)]={variationId:t,expirationTime:a,hasJsCssVariables:o})}),e.add({key:t,data:r,lifetime:5}),i}static compareSemVer({version:e,compareVersion:t,operator:i}){const a=Ve.validateVersion(e),r=Ve.validateVersion(t);if(!a.ok)return u.Err(a.error);if(!r.ok)return u.Err(r.error);const[o,n,s]=a.data,[l,d,p]=r.data,[g,h,m]=[o===l,n===d,s===p];switch(i){case xe.EQUAL:return u.Ok(g&&h&&m);case xe.GREATER:return u.Ok(o>l||g&&n>d||g&&h&&s>p);case xe.LOWER:return u.Ok(o<l||g&&n<d||g&&h&&s<p);default:M.error`Unknown version match type: ${i}`,c(i)}}static getVariationByHash(e,t){let i=0;for(const a of e)if(i+=a.exposition,i>=t)return a;return null}}class we{static insertInOrderedListMutably({list:e,element:t,order:i}){if(e.includes(t))return;const a=e.findIndex(e=>i===Ie.Ascending?e>=t:e<=t);-1===a?e.push(t):e.splice(a,0,t)}static insertVisitInOrderedListMutably({list:e,visit:t}){if(e.find(e=>"number"==typeof e?e===t.timeStarted:e.timeStarted===t.timeStarted))return;const i=e.findIndex(e=>"number"==typeof e?e>=t.timeStarted:e.timeStarted>=t.timeStarted);-1===i?e.push(t):e.splice(i,0,t),e.length>26&&e.splice(0,e.length-26)}}class be{constructor({urlAddress:e,title:t,referrers:i}){this.urlAddress=e,this.title=t,this.referrers=i,this.timestamps=[{time:Date.now(),status:exports.TrackingStatus.Unsent}]}get url(){var e;if(!this.urlAddress)return"";const t=this.title?"&title="+encodeURIComponent(this.title):"",i=(null===(e=this.referrers)||void 0===e?void 0:e.length)?"&referrersIndices="+JSON.stringify(this.referrers):"";return"eventType=page&href="+encodeURIComponent(this.urlAddress)+t+i}get status(){const{[exports.TrackingStatus.Sent]:e,[exports.TrackingStatus.Unsent]:t,[exports.TrackingStatus.Pending]:i}=this.timestamps.reduce((e,{status:t})=>(e[t]=!0,e),{[exports.TrackingStatus.Sent]:!1,[exports.TrackingStatus.Unsent]:!1,[exports.TrackingStatus.Pending]:!1});return!e||t||i?i&&!t?exports.TrackingStatus.Pending:exports.TrackingStatus.Unsent:exports.TrackingStatus.Sent}set status(e){this.timestamps=this.timestamps.map(t=>Object.assign(Object.assign({},t),{status:e}))}set _nonce(e){this.nonce=e}get data(){return{urlAddress:this.urlAddress,title:this.title,referrers:this.referrers,type:exports.KameleoonData.PageView,timestamps:this.timestamps,status:this.status,nonce:this.nonce}}static _fromRaw(e){const{urlAddress:t,title:i,referrers:a,timestamps:r,nonce:o}=e,n=new be({urlAddress:t,title:i,referrers:a});return n.timestamps=r,o&&(n._nonce=o),n}static _updateFromVisit(e,t){const i=e.pageEvents;if(i)for(const e of i){let i=[];const{time:a}=e,{href:r,title:o,referrersIndices:n}=e.data;let s;if("number"==typeof n[0]&&(i=n),t.has(r)){const e=t.get(r).timestamps;s=new be({urlAddress:r,title:o,referrers:i}),s.timestamps=[...e,{time:a,status:exports.TrackingStatus.Sent}]}else s=new be({urlAddress:r,title:o,referrers:i}),s.timestamps=[{time:a,status:exports.TrackingStatus.Sent}];t.set(r,s)}}}let Ae=class e{constructor(e,...t){this.index=e,this.value=t,this._status=exports.TrackingStatus.Unsent,this.isIdentifier=!1}get url(){if("number"!=typeof this.index)return"";const e=[...new Set(this.value)];let t={};e.forEach(e=>{t[e]=1});let i="";return this.isIdentifier&&(i="&mappingIdentifier="+String(!0)),"eventType=customData&index="+this.index+"&valuesCountMap="+encodeURIComponent(JSON.stringify(t))+"&overwrite="+String(!0)+i}get data(){return{index:this.index,value:this.value,type:exports.KameleoonData.CustomData,isIdentifier:this.isIdentifier,status:this.status}}get status(){return this._isMappingIdentifier?exports.TrackingStatus.Unsent:this._status}static _fromRaw(t){const{index:i,value:a,status:r,isIdentifier:o}=t,n=new e(i,...a);return n.status=r,n._isMappingIdentifier=o,n}set _isMappingIdentifier(e){this.isIdentifier=e}set status(e){this._status=e}static _updateFromVisit(t,i){var a;if(null===(a=t.customDataEvents)||void 0===a?void 0:a.length)for(let a=t.customDataEvents.length-1;a>=0;a--){const{index:r,valuesCountMap:o}=t.customDataEvents[a].data;i.has(r)||i.set(r,new e(r,...Object.keys(o)))}}},Ke=class e{constructor({goalId:e,revenue:t=0,negative:i=!1,metadata:a}){this.goalId=e,this.revenue=t,this.negative=i,this.status=exports.TrackingStatus.Unsent,this.id=Math.floor(1e6*Math.random()),this.metadata=a}set _id(e){this.id=e}set _nonce(e){this.nonce=e}get url(){var e;return"eventType=conversion&goalId="+String(this.goalId)+"&revenue="+String(this.revenue)+"&negative="+String(this.negative)+((null===(e=this.metadata)||void 0===e?void 0:e.length)?"&metadata="+this._encodeMetadata():"")}get data(){var e;return{goalId:this.goalId,nonce:this.nonce,revenue:this.revenue,negative:this.negative,type:exports.KameleoonData.Conversion,status:this.status,id:this.id,metadata:(null===(e=this.metadata)||void 0===e?void 0:e.map(e=>e.data))||void 0}}_encodeMetadata(){var e;if(!(null===(e=this.metadata)||void 0===e?void 0:e.length))return"";const t=new Set;return encodeURIComponent(JSON.stringify(this.metadata.reduce((e,i)=>(t.has(i.data.index)||(t.add(i.data.index),e[i.data.index]=i.data.value),e),{})))}static _fromRaw(t){const{goalId:i,revenue:a,negative:r,status:o,id:n,nonce:s,metadata:u}=t,l=new e({goalId:i,revenue:a,negative:r,metadata:e.parseMetadata(u)});return l._id=n,l.status=o,s&&(l._nonce=s),l}static parseMetadata(e){return(null==e?void 0:e.map(e=>Ae._fromRaw(e)))||void 0}static _listFromVisit(t){var i,a;const r=[];if(!(null===(i=t.conversionEvents)||void 0===i?void 0:i.length))return[];if(null===(a=t.conversionEvents)||void 0===a?void 0:a.length)for(const i of t.conversionEvents){const{goalId:t,revenue:a,negative:o}=i.data,n=new e({goalId:t,revenue:a,negative:o});n.status=exports.TrackingStatus.Sent,r.push(n)}return r}static _updateFromVisit(t,i){var a;if(null===(a=t.conversionEvents)||void 0===a?void 0:a.length)for(const a of t.conversionEvents){const{goalId:t}=a.data;if(!i.has(t)){const a=new e({goalId:t});a.status=exports.TrackingStatus.Sent,i.set(t,a)}}}},Oe=class e{constructor(e,t){this.browser=e,this.version=t,this.status=exports.TrackingStatus.Unsent}get url(){if(!this.browser)return"";const e=this.version?x+this.version:"";return C+R+this.browser+y+se[this.browser]+e}get data(){return{browser:this.browser,type:exports.KameleoonData.Browser,version:this.version,status:this.status}}static _fromRaw(t){const{browser:i,version:a,status:r}=t,o=new e(i,a);return o.status=r,o}static _fromVisit(t){if(!t.staticDataEvent)return;const{browser:i,browserIndex:a,browserVersion:r}=t.staticDataEvent.data;if(i||"number"==typeof a){const t=null!=i?i:ue[a];return r?new e(t,r):new e(t)}}},$e=class e{constructor(e){this.device=e,this.status=exports.TrackingStatus.Unsent}get url(){return this.device?C+D+this.device:""}get data(){return{device:this.device,type:exports.KameleoonData.Device,status:this.status}}static _fromRaw(t){const{device:i,status:a}=t,r=new e(i);return r.status=a,r}static _fromVisit(t){var i;if(null===(i=t.staticDataEvent)||void 0===i?void 0:i.data.deviceType)return new e(t.staticDataEvent.data.deviceType)}},Me=class e{constructor(e){this.operatingSystem=e,this.status=exports.TrackingStatus.Unsent}get url(){return this.operatingSystem?C+k+this.operatingSystem+V+oe[this.operatingSystem]:""}get data(){return{operatingSystem:this.operatingSystem,type:exports.KameleoonData.OperatingSystem,status:this.status}}static _fromRaw(t){const{operatingSystem:i,status:a}=t,r=new e(i);return r.status=a,r}static _fromVisit(t){if(!t.staticDataEvent)return;const{os:i,osIndex:a}=t.staticDataEvent.data;if(i||"number"==typeof a){const t=null!=i?i:ne[a];return new e(t)}}};class Fe{constructor({country:e,region:t,city:i,postalCode:a,coordinates:r}){this.country=e,this.region=t,this.city=i,this.postalCode=a,this.coordinates=r,this.status=exports.TrackingStatus.Unsent}get url(){const e=this.region?"&region="+encodeURIComponent(this.region):"",t=this.city?"&city="+encodeURIComponent(this.city):"",i=this.postalCode?"&postalCode="+encodeURIComponent(this.postalCode):"",a=this.coordinates?"&latitude="+this.coordinates[0]+"&longitude="+this.coordinates[1]:"";return"eventType=geolocation&country="+encodeURIComponent(this.country)+e+t+i+a}get data(){return{type:exports.KameleoonData.GeolocationData,country:this.country,region:this.region,city:this.city,postalCode:this.postalCode,coordinates:this.coordinates,status:this.status}}static _fromRaw(e){const{country:t,region:i,city:a,postalCode:r,coordinates:o,status:n}=e,s=new Fe({country:t,region:i,city:a,postalCode:r,coordinates:o});return s.status=n,s}static _fromVisit(e){var t;if(!(null===(t=e.geolocationEvents)||void 0===t?void 0:t.length))return;let i;for(const t of e.geolocationEvents){const{data:e}=t;e.country&&(i=e)}const{country:a,region:r,city:o}=i||{};return a?new Fe(r&&o?{country:a,region:r,city:o}:r?{country:a,region:r}:{country:a}):void 0}}class Ne{constructor(e){this.status=exports.TrackingStatus.Sent,this.visits=e,this.visitNumber=e.length?e.length-1:0}get url(){return""}get data(){return{visits:this.visits,