UNPKG

@kameleoon/javascript-sdk

Version:
1 lines 174 kB
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).KameleoonSDK={})}(this,function(e){"use strict";var t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function i(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function a(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 n,o,r,s={},u={},l=(o||(o=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Err=e.Ok=void 0;var t=function(){if(n)return u;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 a(e){return this.ok&&e(this.data),this}return n=1,Object.defineProperty(u,"__esModule",{value:!0}),u.Err=u.Ok=void 0,u.Ok=function(n){return{ok:!0,data:n,throw:e,else:t,or:i,and:a}},u.Err=function(n){return{ok:!1,error:n,throw:e,else:t,or:i,and:a}},u}();Object.defineProperty(e,"Ok",{enumerable:!0,get:function(){return t.Ok}}),Object.defineProperty(e,"Err",{enumerable:!0,get:function(){return t.Err}})}(s)),s);function d(e,t,i,a){return new(i||(i=Promise))(function(t,n){function o(e){try{s(a.next(e))}catch(e){n(e)}}function r(e){try{s(a.throw(e))}catch(e){n(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,r)}s((a=a.apply(e,[])).next())})}"function"==typeof SuppressedError&&SuppressedError,e.KameleoonException=void 0,(r=e.KameleoonException||(e.KameleoonException={})).Credentials="Credentials",r.EventSourceInitialization="EventSourceInitialization",r.FeatureFlagConfigurationNotFound="FeatureFlagConfigurationNotFound",r.FeatureFlagVariableNotFound="FeatureFlagVariableNotFound",r.FeatureFlagVariationNotFound="FeatureFlagVariationNotFound",r.FeatureFlagExperimentNotFound="FeatureFlagExperimentNotFound",r.FeatureFlagEnvironmentDisabled="FeatureFlagEnvironmentDisabled",r.VisitAmount="VisitAmount",r.VisitorCodeMaxLength="VisitorCodeMaxLength",r.VisitorCodeEmpty="VisitorCodeEmpty",r.StorageInitialization="StorageInitialization",r.StorageWrite="StorageWrite",r.StorageRead="StorageRead",r.StorageParse="StorageParse",r.StorageEmpty="StorageEmpty",r.ClientConfiguration="ClientConfiguration",r.TargetingCondition="TargetingCondition",r.AmongValuesCheck="AmongValuesCheck",r.RangeCheck="RangeCheck",r.Initialization="Initialization",r.JSONParse="JSONParse",r.NumberParse="NumberParse",r.VersionParse="VersionParse",r.CookieParse="CookieParse",r.SemanticVersionParse="SemanticVersionParse",r.RemoteData="RemoteData",r.MaximumRetriesReached="MaximumRetriesReached";const c={[e.KameleoonException.CookieParse]:e=>`Couldn't parse cookie string: ${e}`,[e.KameleoonException.JSONParse]:e=>`Couldn't parse JSON variable: ${e}`,[e.KameleoonException.NumberParse]:e=>`It's not possible to parse value ${e} to Number`,[e.KameleoonException.VersionParse]:e=>`It's not possible to parse a version value ${e} to Number, version should be in format x.x`,[e.KameleoonException.SemanticVersionParse]:e=>`It's not possible to parse a version value ${e} to Number, version should be in format x.x.x`,[e.KameleoonException.Initialization]:()=>"It seems that the client wasn't properly initialized, make sure to run `initialize` method before invoking other methods",[e.KameleoonException.Credentials]:()=>"KameleoonClient can not be created without credentials",[e.KameleoonException.StorageInitialization]:()=>"There was an error while initializing React Native SDK storage, it seems that the storage library dependency wasn't installed",[e.KameleoonException.EventSourceInitialization]:()=>"There was an error while initializing Real Time Update service, it seems that the event source library dependency wasn't installed",[e.KameleoonException.FeatureFlagConfigurationNotFound]:e=>`No feature flag with key ${e} was found.`,[e.KameleoonException.FeatureFlagEnvironmentDisabled]:(e,t)=>`Feature flag with key ${e} is disabled in ${t} environment.`,[e.KameleoonException.FeatureFlagVariableNotFound]:(e,t)=>`No feature flag variable with key ${e} was found for ${t} visitorCode.`,[e.KameleoonException.FeatureFlagVariationNotFound]:(e,t)=>`No feature flag variation with key ${e} was found for ${t} visitorCode.`,[e.KameleoonException.FeatureFlagExperimentNotFound]:(e,t)=>`No feature flag experiment with id ${e} was found for ${t} visitorCode.`,[e.KameleoonException.VisitAmount]:()=>"Visit amount must be a number between 1 and 25",[e.KameleoonException.VisitorCodeMaxLength]:()=>"Visitor code can not be more than 255 characters long",[e.KameleoonException.VisitorCodeEmpty]:()=>"Visitor code can not be empty",[e.KameleoonException.StorageWrite]:e=>`Couldn't update storage for kameleoonClient: ${e}`,[e.KameleoonException.StorageRead]:e=>`No data found in storage under ${e} key`,[e.KameleoonException.StorageEmpty]:()=>"No data found in storage",[e.KameleoonException.StorageParse]:(e,t)=>`Couldn't parse ${t} storage data, the data may be corrupted. Error: ${e}`,[e.KameleoonException.ClientConfiguration]:e=>`Couldn't retrieve client configuration from Kameleoon Api. Error: ${e}`,[e.KameleoonException.TargetingCondition]:e=>`${e} targeting condition is not yet supported.`,[e.KameleoonException.AmongValuesCheck]:(e,t)=>`Couldn't parse value "${t}": ${e}`,[e.KameleoonException.RangeCheck]:e=>`Couldn't parse value "${e}" as a range, value should be in format [x: number, y: number]`,[e.KameleoonException.RemoteData]:e=>`Couldn't retrieve data from Kameleoon server. Error: ${e}`,[e.KameleoonException.MaximumRetriesReached]:e=>`Maximum retries reached, request failed. Reason: ${e}`};function g(e){throw new Error(`Reaching an impossible state because of ${e}`)}class h extends Error{constructor(t,i,a){switch(super(`Error: ${t}`),this.name="KameleoonError",this.errorType=t,t){case e.KameleoonException.Initialization:case e.KameleoonException.Credentials:case e.KameleoonException.VisitorCodeMaxLength:case e.KameleoonException.VisitorCodeEmpty:case e.KameleoonException.StorageInitialization:case e.KameleoonException.VisitAmount:case e.KameleoonException.EventSourceInitialization:case e.KameleoonException.StorageEmpty:this.message=c[t]();break;case e.KameleoonException.CookieParse:case e.KameleoonException.FeatureFlagConfigurationNotFound:case e.KameleoonException.NumberParse:case e.KameleoonException.ClientConfiguration:case e.KameleoonException.MaximumRetriesReached:case e.KameleoonException.RemoteData:case e.KameleoonException.VersionParse:case e.KameleoonException.SemanticVersionParse:this.message=c[t](i);break;case e.KameleoonException.FeatureFlagExperimentNotFound:case e.KameleoonException.FeatureFlagVariationNotFound:case e.KameleoonException.FeatureFlagVariableNotFound:this.message=c[t](i,a);break;case e.KameleoonException.FeatureFlagEnvironmentDisabled:this.message=void 0!==a?c[t](i,a):i;break;case e.KameleoonException.StorageWrite:case e.KameleoonException.JSONParse:case e.KameleoonException.StorageRead:this.message=c[t](i);break;case e.KameleoonException.StorageParse:this.message=c[t](i,a);break;case e.KameleoonException.TargetingCondition:this.message=c[t](i);break;case e.KameleoonException.AmongValuesCheck:this.message=c[t](i,a);break;case e.KameleoonException.RangeCheck:this.message=c[t](i);break;default:g(t)}}get type(){return this.errorType}}var p,v,m,f,C;!function(e){e.DataApi="dataApi",e.Events="events",e.ClientConfiguration="clientConfiguration"}(p||(p={})),e.HttpMethod=void 0,(v=e.HttpMethod||(e.HttpMethod={})).Get="GET",v.Post="POST",function(e){e[e.VisitEvent=0]="VisitEvent",e[e.VisitData=1]="VisitData",e[e.DataMap=2]="DataMap"}(m||(m={})),e.RequestType=void 0,(f=e.RequestType||(e.RequestType={})).Configuration="configuration",f.Tracking="tracking",f.RemoteData="remoteData",e.Header=void 0,(C=e.Header||(e.Header={})).UserAgent="User-Agent",C.ContentType="Content-Type",C.SdkVersion="X-Kameleoon-SDK-Version",C.SdkType="X-Kameleoon-SDK-Type",C.Authorization="Authorization",C.AcceptEncoding="Accept-Encoding",C.IfModifiedSince="If-Modified-Since",C.LastModified="Last-Modified";const y="eventType=staticData",D="&browserIndex=",E="&browserVersion=",T="&deviceType=",I="&visitorCode=",k="&nonce=",S="&id=",V="&maxNumberPreviousVisits=",w="&os=",R="&osIndex=",b="&browser=",K="&mappingValue=",A="visit/",x={[p.DataApi]:"data.kameleoon.io",[p.Events]:"events.kameleoon.eu",[p.ClientConfiguration]:"sdk-config.kameleoon.eu"};var O;e.LogLevel=void 0,(O=e.LogLevel||(e.LogLevel={}))[O.NONE=0]="NONE",O[O.ERROR=1]="ERROR",O[O.WARNING=2]="WARNING",O[O.INFO=3]="INFO",O[O.DEBUG=4]="DEBUG";const $={[e.LogLevel.NONE]:"NONE",[e.LogLevel.ERROR]:"ERROR",[e.LogLevel.WARNING]:"WARNING",[e.LogLevel.INFO]:"INFO",[e.LogLevel.DEBUG]:"DEBUG"},N=(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 n=t[a];if("object"==typeof n)try{i+=e[a]+JSON.stringify(n,N)}catch(t){i+=e[a]+"{object}"}else i+="string"==typeof n?e[a]+"'"+n+"'":e[a]+n}return i+=e[e.length-1],i}(t,i);M.writeMessage(e,a)}static info(t,...i){M.log({level:e.LogLevel.INFO,strings:t,keys:i})}static error(t,...i){M.log({level:e.LogLevel.ERROR,strings:t,keys:i})}static warning(t,...i){M.log({level:e.LogLevel.WARNING,strings:t,keys:i})}static debug(t,...i){M.log({level:e.LogLevel.DEBUG,strings:t,keys:i})}static checkLevel(t){return t<=M.logLevel&&t!==e.LogLevel.NONE}static writeMessage(e,t){M.logger.log(e,`Kameleoon [${$[e]}]: ${t}`)}}M.logger=new class{log(t,i){switch(t){case e.LogLevel.DEBUG:console.debug(i);break;case e.LogLevel.INFO:console.info(i);break;case e.LogLevel.WARNING:console.warn(i);break;case e.LogLevel.ERROR:console.error(i)}}},M.logLevel=e.LogLevel.WARNING;let F=class{constructor({urlProvider:e,packageInfo:t,externalRequester:i,requestTimeout:a,trackRetryDelay:n,useAbortController:o}){M.debug`CALL: new Requester(urlProvider, packageInfo: ${t}, externalRequester, requestTimeout: ${a}, trackRetryDelay: ${n}, useAbortController: ${o})`,this.urlProvider=e,this.useAbortController=o,this.externalRequester=i,this.trackRetryDelay=n,this.packageInfo=t,this.timeout=a,M.debug`RETURN: new Requester(urlProvider, packageInfo: ${t}, externalRequester, requestTimeout: ${a}, trackRetryDelay: ${n}, useAbortController: ${o})`}getClientConfiguration(t,i){return d(this,0,void 0,function*(){const a=this.urlProvider.getClientConfigurationUrl(t);let n=Object.assign({[e.Header.SdkType]:this.packageInfo.type.toLowerCase(),[e.Header.SdkVersion]:this.packageInfo.version},i&&{[e.Header.IfModifiedSince]:i});try{let t={message:""};M.debug`Running configuration request Method: ${e.HttpMethod.Get}, Url: ${a}, Headers: ${n}, with retry limit ${2}`;for(let i=0;i<2;i++){const o=yield this.sendRequest({url:a,requestType:e.RequestType.Configuration,retryCount:i,parameters:{method:e.HttpMethod.Get,headers:n}});if(o.ok){const e=yield o.json();this.logReceivedConfigurationResponse(o.status,a,n);const t=this.getLastModifiedHeader(o),i=e;return l.Ok({configuration:i,lastModified:t})}if(304===o.status)return this.logReceivedConfigurationResponse(o.status,a,n),l.Ok({});if(1===i){if(o.text){const e=yield o.text();t=JSON.parse(e)}M.error`Failed to get configuration response ${{status:o.status,message:t.message}} for request Method: ${e.HttpMethod.Get}, Url: ${a}, Headers: ${n}`}else yield this.logRequestError({logLevel:e.LogLevel.WARNING,message:"Failed to get configuration response",response:o,method:e.HttpMethod.Get,url:a})}return l.Err(new h(e.KameleoonException.MaximumRetriesReached,t.message))}catch(t){return yield this.logRequestError({logLevel:e.LogLevel.ERROR,message:"Failed to get configuration response",error:t,method:e.HttpMethod.Get,url:a,headers:n}),l.Err(new h(e.KameleoonException.ClientConfiguration,t))}})}getRemoteData(t){var i;return d(this,0,void 0,function*(){const a=this.urlProvider.getRemoteDataUrl(t);M.debug`Running remote data request Method: ${e.HttpMethod.Get}, Url: ${a}`;try{const t=yield this.sendRequest({url:a,requestType:e.RequestType.RemoteData,retryCount:0,parameters:{method:e.HttpMethod.Get}});if(!t.ok){if(yield this.logRequestError({logLevel:e.LogLevel.ERROR,message:"Failed to get remote data response",response:t,method:e.HttpMethod.Get,url:a}),t.text){const a=yield t.text(),n=null===(i=JSON.parse(a))||void 0===i?void 0:i.message;return l.Err(new h(e.KameleoonException.RemoteData,n))}return l.Err(new h(e.KameleoonException.RemoteData,"Unknown Reason - no `text()` was found for a response"))}const n=yield t.json();return M.debug`Received remote data response: ${{status:t.status}} for request Method: ${e.HttpMethod.Get}, Url: ${a}`,l.Ok(n)}catch(t){return yield this.logRequestError({logLevel:e.LogLevel.ERROR,message:"Failed to get remote data response",error:t,method:e.HttpMethod.Get,url:a}),l.Err(new h(e.KameleoonException.RemoteData,t))}})}getVisitorData({visitorCode:t,filters:i,isMappingIdentifier:a}){var n;return d(this,0,void 0,function*(){const o=this.urlProvider.getVisitorDataUrl({visitorCode:t,filters:i,isMappingIdentifier:a});M.debug`Running visitor data request Method: ${e.HttpMethod.Get}, Url: ${o}`;try{const t=yield this.sendRequest({url:o,requestType:e.RequestType.RemoteData,retryCount:0,parameters:{method:e.HttpMethod.Get}});if(!t.ok){if(yield this.logRequestError({logLevel:e.LogLevel.ERROR,message:"Failed to get visitor data response",response:t,method:e.HttpMethod.Get,url:o}),"function"==typeof t.text){const i=yield t.text();if(i){const t=null===(n=JSON.parse(i))||void 0===n?void 0:n.message;return l.Err(new h(e.KameleoonException.RemoteData,t))}}return t.status?l.Err(new h(e.KameleoonException.RemoteData,`No error message. Error status: ${t.status}`)):l.Err(new h(e.KameleoonException.RemoteData,"Unknown Reason - no text message or error status was found for a response"))}const i=yield t.json();return M.debug`Received visitor data response: ${{status:t.status}} for request Method: ${e.HttpMethod.Get}, Url: ${o}`,l.Ok(i)}catch(t){return yield this.logRequestError({logLevel:e.LogLevel.ERROR,message:"Failed to get visitor data response",error:t,method:e.HttpMethod.Get,url:o}),l.Err(new h(e.KameleoonException.RemoteData,t))}})}track(t,i){return d(this,0,void 0,function*(){const a=this.urlProvider.getTrackingUrl(i);M.debug`Running tracking request Method: ${e.HttpMethod.Post}, Url: ${a}, Body: ${t}, with retry limit ${2}, retry delay ${this.trackRetryDelay} ms`;for(let i=0;i<2;i++){let n;try{if(n=yield this.sendRequest({url:a,retryCount:i,requestType:e.RequestType.Tracking,parameters:{body:t,method:e.HttpMethod.Post,headers:{[e.Header.ContentType]:"*/*"}}}),n.ok)return M.debug`Received tracking response: ${{status:n.status}} for request Method: ${e.HttpMethod.Post}, Url: ${a}, Body: ${t}`,l.Ok();yield this.logRequestError({logLevel:1==i?e.LogLevel.ERROR:e.LogLevel.WARNING,message:"Failed to get tracking response",response:n,method:e.HttpMethod.Post,url:a})}catch(t){yield this.logRequestError({logLevel:1==i?e.LogLevel.ERROR:e.LogLevel.WARNING,message:"Failed to get tracking response",error:t,method:e.HttpMethod.Post,url:a})}i<2&&(yield new Promise(e=>setTimeout(e,this.trackRetryDelay)))}return l.Err()})}sendRequest({url:e,requestType:t,retryCount:i,parameters:a}){return d(this,0,void 0,function*(){let n;if(this.useAbortController){const o=new AbortController,r=setTimeout(()=>o.abort(),this.timeout);n=yield this.externalRequester.sendRequest({url:e,retryCount:i,requestType:t,parameters:Object.assign(Object.assign({},a),{signal:o.signal})}),clearTimeout(r)}else n=yield this.externalRequester.sendRequest({url:e,retryCount:i,requestType:t,parameters:a});return n})}logRequestError({logLevel:e,message:t,error:i,method:a,url:n,response:o,headers:r}){return d(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: ${n}`})}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: '${n}'`+(r?`, Headers: ${r}`:"")})}})}parseResponse(e){return d(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(t){if(t.headers){const i=e.Header.LastModified.toLowerCase();for(const[e,a]of t.headers)if(e.toLowerCase()===i)return a}}logReceivedConfigurationResponse(t,i,a){M.debug`Received configuration response: ${{status:t}} for request Method: ${e.HttpMethod.Get}, Url: ${i}, Headers: ${a}`}};var L,_,U,P,B,G,z,j,q,H,W,Y;e.Environment=void 0,(L=e.Environment||(e.Environment={})).Production="production",L.Staging="staging",L.Development="development";class J{constructor(){this.ready=!1,this.isCustomDomain=!1,this.domains=x}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[p.DataApi]=e);const t=e.split(".")[0],i=this.domains[p.DataApi];this.domains[p.DataApi]=i.replace(/^[^.]+/,t)}get dataApiDomain(){return this.domains[p.DataApi]}getClientConfigurationUrl(t){this.isInitialized();const i=`https://${this.domains[p.ClientConfiguration]}/v3/`,a=this.environment===e.Environment.Production?"":"?environment="+encodeURIComponent(this.environment);let n="";return t&&(n=a?"&ts="+t:"?ts="+t),i+this.siteCode+a+n}getEventSourceUrl(){return this.isInitialized(),`https://${this.domains[p.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:n,currentVisit:o,conversions:r,geolocation:s,experiments:u,pageViews:l,device:d,browser:c,operatingSystem:g,kcs:h,personalization:p,visitorCode:v,cbs:f}=t,C=i?K:I,y=a||v?"&customData="+!0:"",D=r?"&conversion="+!0:"",E=s?"&geolocation="+!0:"",T=u?"&experiment="+!0:"",k=l?"&page="+!0:"",S="&staticData="+!0,w=o?"&currentVisit="+!0:"",R=h?"&kcs="+!0:"",b=p?"&personalization="+!0:"",A="number"!=typeof n?V+1:V+n,x=f?"&cbs="+!0:"";return this.getDataApiUrl(m.VisitData)+this.siteCode+C+e+A+y+D+E+T+k+S+w+R+b+x}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[p.DataApi])throw new Error("Data API domain is not set");const t=`https://${this.domains[p.DataApi]}`;switch(e){case m.VisitEvent:return`${t}/${A+"events?siteCode="}`;case m.VisitData:return`${t}/${A+"visitor?siteCode="}`;case m.DataMap:return`${t}/map/map?siteCode=`}}setDomains(e){e&&(this.isCustomDomain=!0,this.domains[p.DataApi]="data."+e,this.domains[p.Events]="events."+e,this.domains[p.ClientConfiguration]="sdk-config."+e)}}e.VariableType=void 0,(_=e.VariableType||(e.VariableType={})).BOOLEAN="BOOLEAN",_.NUMBER="NUMBER",_.STRING="STRING",_.JSON="JSON",_.JS="JS",_.CSS="CSS",e.TrackingStatus=void 0,(U=e.TrackingStatus||(e.TrackingStatus={})).Sent="sent",U.Unsent="unsent",U.Pending="pending",e.Milliseconds=void 0,(P=e.Milliseconds||(e.Milliseconds={}))[P.Second=1e3]="Second",P[P.Minute=6e4]="Minute",P[P.Hour=36e5]="Hour",P[P.Day=864e5]="Day",P[P.Week=6048e5]="Week",P[P.Month=2592e6]="Month";class X{constructor(t){this.cacheMap=new Map,this.intervalId=null,this.cleanupTimeout=t*e.Milliseconds.Second}add({key:t,data:i,lifetime:a}){M.debug`CALL: CacheManager.add(key: ${t}, data: ${i}, lifetime: ${a})`,null===this.intervalId&&this.activate();const n=a*e.Milliseconds.Second,o={data:i,expirationTime:Date.now()+n};this.cacheMap.set(t,o),M.debug`RETURN: CacheManager.add(key: ${t}, data: ${i}, lifetime: ${a})`}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"}(B||(B={})),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"}(z||(z={})),function(e){e.ACTIVATED="ACTIVATED",e.DEACTIVATED="DEACTIVATED",e.SCHEDULED="SCHEDULED"}(j||(j={})),e.CustomDataScope=void 0,(q=e.CustomDataScope||(e.CustomDataScope={})).Visit="VISIT",q.Visitor="VISITOR",q.Page="Page",function(e){e.Required="REQUIRED",e.NotRequired="NOT_REQUIRED"}(H||(H={})),function(e){e.PartiallyBlocked="PARTIALLY_BLOCK",e.CompletelyBlocked="FULLY_BLOCK"}(W||(W={}));class Q{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)}}e.EventType=void 0,(Y=e.EventType||(e.EventType={})).Evaluation="evaluation",Y.ConfigurationUpdate="configurationUpdate";const Z={customData:[],featureFlags:[],configuration:{realTimeUpdate:!1,consentType:H.NotRequired,dataApiDomain:"data.kameleoon.io",consentOptOutBehavior:W.PartiallyBlocked}};class ee{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 te{constructor({updateInterval:t,urlProvider:i,storage:a,requester:n,dataManager:o,eventSource:r,externalVisitorCodeManager:s,eventManager:u,externalPackageInfo:l,defaultDataFile:d}){this.updateConfigurationIntervalId=null,this.updateType=B.Polling,this.configurationData=Z,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.blockingBehaviourMode=W.PartiallyBlocked,this.CACHE_REVALIDATE_PERIOD=90*e.Milliseconds.Minute,this.urlProvider=i,this.requester=n,this.updateInterval=t,this.lastUpdate=new Date,this.storage=a,this.dataManager=o,this.eventManager=u,this.visitorCodeManager=s,this.eventSource=r,this.externalPackageInfo=l,this.defaultDataFile=d}initialize(){return d(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()"),l.Ok()}return this.updateType!==B.RealTime||this.eventSource.isOpen?(this.updateType===B.Polling&&this.handlePollingUpdates(),M.debug("RETURN: ClientConfiguration.initialize()"),l.Ok()):(this.handleRealTimeUpdates(),M.debug("RETURN: ClientConfiguration.initialize()"),l.Ok())})}cleanupHandlers(){this.eventSource.isOpen&&this.eventSource.close(),this.updateConfigurationIntervalId&&clearInterval(this.updateConfigurationIntervalId)}handleRealTimeUpdates(){this.cleanupHandlers(),this.eventSource.open(t=>{this.updateClientConfiguration(t).then(i=>{i.ok&&this.eventManager.fireEvent(e.EventType.ConfigurationUpdate,{timestamp:t})})}),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=B.Polling,this.handlePollingUpdates()})}handlePollingUpdates(){this.cleanupHandlers();try{const e=this.lastUpdate.getTime(),t=Date.now(),i=Math.max(this.updateInterval-(t-e),0);setTimeout(()=>d(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:n,variationByExposition:o}=i,r=new Map;o.forEach(({variationKey:e,variationId:t})=>{"number"==typeof t&&r.set(e,t)}),t.set(a,{featureId:e.id,experimentId:n,variations:r})}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,n=new Map;a.forEach(({variationKey:e,variationId:t})=>{"number"==typeof t&&n.set(e,t)}),t.set(e,{type:i.type,variations:n})}return this.mappedExperiments=t,t}get holdout(){return this.holdoutData}get meGroups(){return this.meGroupsData}get isConsentRequired(){return this.configuration.consentType===H.Required}get consentBlockingBehaviour(){return this.blockingBehaviourMode}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?B.RealTime:B.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:n,lastUpdate:o,lastModified:r,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=n.dateModified)&&void 0!==e?e:s)&&void 0!==t?t:-1,r=null!==(i=a.dateModified)&&void 0!==i?i:0;(!s||r>o)&&(n=a,u=!0)}catch(e){M.error`Error parsing default data file: ${String(e)}`}this.updateConfigurationData(n,u),this.lastUpdate=this.usedDefaultDataFile?new Date(0):new Date(Date.parse(o)),this.lastModified=r,this.requestTime=s}M.debug`RETURN: ClientConfiguration.readStorageData() -> (result: ${a.ok})`}updateClientConfiguration(e){return d(this,0,void 0,function*(){const t=Date.now();if(this.usedDefaultDataFile)return this.updateClientConfigurationInBackground(),l.Ok(!1);if(this.requestTime&&!e&&!this.externalPackageInfo.isServer){if(t-this.requestTime<=this.CACHE_REVALIDATE_PERIOD)return this.updateClientConfigurationInBackground(),l.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(()=>d(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 d(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."),l.Ok(!0)):e;if(void 0===e.data.configuration)return this.updateStorageData(),l.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 n=this.updateStorageData();if(!n.ok)return n;const o=a.configuration.realTimeUpdate?B.RealTime:B.Polling,r=o!==this.updateType;return r&&(this.updateType=o,M.info`Configuration update type was toggled to ${B[o]}`,yield this.initialize()),this.blockingBehaviourMode=this.consentBlockingBehaviourFromStr(a.configuration.consentOptOutBehavior),l.Ok(r)})}updateConfigurationData(e,t=!0){const{configuration:i,featureFlags:a,customData:n,holdout:o,segments:r,dateModified:s}=e;let u=r?new Map(r.map(e=>[e.id.toString(),e])):null,l=null;if(t&&(null==n?void 0:n.length)){l=new Map;for(let e of n){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==n?void 0:n.length)&&(this.dataManager.customDataIndexes=n),this.meGroupsData=this.makeMEGroups(a),this.holdoutData=null!=o?o:null,this.configurationData={configuration:i,customData:n,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 ee(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}consentBlockingBehaviourFromStr(e){return e===W.PartiallyBlocked||e===W.CompletelyBlocked?e:(M.error(`Unexpected consent blocking type '${e}'`),W.PartiallyBlocked)}}function ie(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e]))}var ae,ne,oe,re;e.KameleoonData=void 0,(ae=e.KameleoonData||(e.KameleoonData={})).UniqueIdentifier="uniqueIdentifier",ae.CustomData="customData",ae.PageView="pageView",ae.GeolocationData="geolocation",ae.Browser="browser",ae.Conversion="conversion",ae.Cookie="cookie",ae.Device="device",ae.OperatingSystem="operatingSystem",ae.UserAgent="userAgent",ae.ApplicationVersion="applicationVersion",ae.VisitsData="visitsData",ae.KameleoonConversionScore="kameleoonConversionScore",ae.Personalization="personalization",ae.CBScores="cbScores",ae.TargetedSegment="targetedSegment",e.DeviceType=void 0,(ne=e.DeviceType||(e.DeviceType={})).Phone="PHONE",ne.Tablet="TABLET",ne.Desktop="DESKTOP",e.OperatingSystemType=void 0,(oe=e.OperatingSystemType||(e.OperatingSystemType={})).WindowsPhone="WINDOWS_PHONE",oe.Windows="WINDOWS",oe.Android="ANDROID",oe.Linux="LINUX",oe.Mac="MAC",oe.IOS="IOS",e.BrowserType=void 0,(re=e.BrowserType||(e.BrowserType={})).Chrome="CHROME",re.InternetExplorer="IE",re.Firefox="FIREFOX",re.Safari="SAFARI",re.Opera="OPERA",re.Other="OTHER";const se={[e.OperatingSystemType.Windows]:0,[e.OperatingSystemType.Mac]:1,[e.OperatingSystemType.IOS]:2,[e.OperatingSystemType.Linux]:3,[e.OperatingSystemType.Android]:4,[e.OperatingSystemType.WindowsPhone]:5},ue=ie(se),le={[e.BrowserType.Chrome]:0,[e.BrowserType.InternetExplorer]:1,[e.BrowserType.Firefox]:2,[e.BrowserType.Safari]:3,[e.BrowserType.Opera]:4,[e.BrowserType.Other]:5},de=ie(le),ce="off",ge="warehouseAudiences";var he;e.SdkLanguageType=void 0,(he=e.SdkLanguageType||(e.SdkLanguageType={})).ANDROID="ANDROID",he.IOS="IOS",he.JAVA="JAVA",he.CSHARP="CSHARP",he.NODEJS="NODEJS",he.PHP="PHP",he.RUBY="RUBY",he.GO="GO",he.FLUTTER="FLUTTER",he.REACT="REACT",he.PYTHON="PYTHON",he.JAVASCRIPT="JAVASCRIPT",he.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 ve,me,fe,Ce,ye,De,Ee,Te,Ie,ke,Se,Ve;!function(e){e.And="AND",e.Or="OR"}(ve||(ve={})),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"}(me||(me={})),function(e){e.NEW="NEW",e.RETURNING="RETURNING"}(fe||(fe={})),function(e){e.ANY="ANY",e.EXACT="EXACT"}(Ce||(Ce={})),function(e){e.ALL="ALL",e.TEST="TEST",e.PERSO="PERSO"}(ye||(ye={})),function(e){e.Experiment="EXPERIMENT",e.Personalization="PERSONALIZATION",e.Any="ANY"}(De||(De={})),function(e){e.EXACT="EXACT",e.CONTAINS="CONTAINS",e.REGULAR_EXPRESSION="REGULAR_EXPRESSION",e.GREATER="GREATER",e.EQUAL="EQUAL",e.LOWER="LOWER"}(Ee||(Ee={})),function(e){e.GREATER="GREATER",e.EQUAL="EQUAL",e.LOWER="LOWER"}(Te||(Te={})),function(e){e.EXACT="EXACT",e.CONTAINS="CONTAINS",e.REGULAR_EXPRESSION="REGULAR_EXPRESSION",e.OPTIONAL="OPTIONAL"}(Ie||(Ie={})),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"}(ke||(ke={})),function(e){e.Minute="MINUTE",e.Hour="HOUR",e.Day="DAY",e.Week="WEEK",e.Month="MONTH"}(Se||(Se={})),function(e){e.Ascending="asc",e.Descending="desc"}(Ve||(Ve={}));const we="localhost",Re=/^(\.?(([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 be{static validateVersion(t){const i=t.split(".").map(e=>parseInt(e,10));for(;i.length<3;)i.push(0);return i.some(e=>isNaN(e))?l.Err(new h(e.KameleoonException.SemanticVersionParse,t)):l.Ok(i.slice(0,3))}static validateDomain(e){return e?(e=be.checkAndTrimProtocol(e.toLowerCase()),Re.test(e)||e===we||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.`,l.Ok(e)):l.Err()}static validateNetworkDomain(e){return e?(e=(e=be.checkAndTrimProtocol(e.toLowerCase())).replace(/^\.+|\.+$/g,""),Re.test(e)||e===we?l.Ok(e):(M.error`The network domain ${e} is invalid.`,l.Err())):l.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 Ke{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:t,visitorCode:i,targetingData:a,experimentId:n,variationConfiguration:o,clientConfiguration:r,packageInfo:s,dataManager:u}){if(M.debug`CALL: checkTargeting(segment, visitorCode: ${i}, targetingData: ${a}, experimentId: ${n}, variationConfiguration, clientConfiguration, packageInfo, dataManager)`,!t||!t.conditionsData.firstLevel.length){const e=l.Ok(!0);return M.debug`RETURN checkTargeting(segment, visitorCode: ${i}, targetingData: ${a}, experimentId: ${n}, variationConfiguration, clientConfiguration, packageInfo, dataManager) -> (result: ${e})`,e}if(!o){const t=l.Err(new h(e.KameleoonException.Initialization));return M.debug`RETURN checkTargeting(segment, visitorCode: ${i}, targetingData: ${a}, experimentId: ${n}, variationConfiguration, clientConfiguration, packageInfo, dataManager) -> (result: ${t})`,t}let d={};const c=o.getStoredVariations(i);c.ok&&(d=c.data);const g=u.getTree(t);let p,v,m;g.hasTargetingType(ke.SEGMENT)&&(p=u.trees,m=r.segments),g.hasTargetingType(ke.TARGET_FEATURE_FLAG)&&(v=r.ruleMap);const f=g.evaluate({variationData:d,sdkInfo:s,segments:m,ruleMap:v,trees:p,targetingData:a,experimentId:n,visitorCode:i});return M.debug`RETURN checkTargeting(segment, visitorCode: ${i}, targetingData: ${a}, experimentId: ${n}, variationConfiguration, clientConfiguration, packageInfo, dataManager) -> (result: ${f})`,f}static convertTimeUnit(t,i){return t/{[Se.Minute]:e.Milliseconds.Minute,[Se.Hour]:e.Milliseconds.Hour,[Se.Day]:e.Milliseconds.Day,[Se.Week]:e.Milliseconds.Week,[Se.Month]:e.Milliseconds.Month}[i]}static isCustomData(t){return t.data.type===e.KameleoonData.CustomData}static updateCache({hasJsCssVariables:t,cacheManager:i,visitorCode:a,experimentId:n,variationId:o}){const r=i.getAliveItem(a),s=r?Object.assign({},r):{};s[n]={variationId:o,hasJsCssVariables:t,expirationTime:Date.now()+5*e.Milliseconds.Second},i.add({key:a,data:s,lifetime:5})}static getTrackingCode(e,t){let i="window.kameleoonQueue=window.kameleoonQueue||[];";const a=e.getAliveItem(t);if(!a)return i;const n={};return Object.entries(a).forEach(([e,{variationId:t,expirationTime:a,hasJsCssVariables:o}])=>{const r=!o;a>Date.now()&&(i+=`window.kameleoonQueue.push(['Experiments.assignVariation',${e},${t},true]);`,i+=`window.kameleoonQueue.push(['Experiments.trigger',${e},${r}]);`,n[Number(e)]={variationId:t,expirationTime:a,hasJsCssVariables:o})}),e.add({key:t,data:n,lifetime:5}),i}static compareSemVer({version:e,compareVersion:t,operator:i}){const a=be.validateVersion(e),n=be.validateVersion(t);if(!a.ok)return l.Err(a.error);if(!n.ok)return l.Err(n.error);const[o,r,s]=a.data,[u,d,c]=n.data,[h,p,v]=[o===u,r===d,s===c];switch(i){case Te.EQUAL:return l.Ok(h&&p&&v);case Te.GREATER:return l.Ok(o>u||h&&r>d||h&&p&&s>c);case Te.LOWER:return l.Ok(o<u||h&&r<d||h&&p&&s<c);default:M.error`Unknown version match type: ${i}`,g(i)}}static getVariationByHash(e,t){let i=0;for(const a of e)if(i+=a.exposition,i>=t)return a;return null}}class Ae{static insertInOrderedListMutably({list:e,element:t,order:i}){if(e.includes(t))return;const a=e.findIndex(e=>i===Ve.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 xe{constructor({urlAddress:t,title:i,referrers:a}){this.urlAddress=t,this.title=i,this.referrers=a,this.timestamps=[{time:Date.now(),status:e.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{[e.TrackingStatus.Sent]:t,[e.TrackingStatus.Unsent]:i,[e.TrackingStatus.Pending]:a}=this.timestamps.reduce((e,{status:t})=>(e[t]=!0,e),{[e.TrackingStatus.Sent]:!1,[e.TrackingStatus.Unsent]:!1,[e.TrackingStatus.Pending]:!1});return!t||i||a?a&&!i?e.TrackingStatus.Pending:e.TrackingStatus.Unsent:e.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:e.KameleoonData.PageView,timestamps:this.timestamps,status:this.status,nonce:this.nonce}}static _fromRaw(e){const{urlAddress:t,title:i,referrers:a,timestamps:n,nonce:o}=e,r=new xe({urlAddress:t,title:i,referrers:a});return r.timestamps=n,o&&(r._nonce=o),r}static _updateFromVisit(t,i){const a=t.pageEvents;if(a)for(const t of a){let a=[];const{time:n}=t,{href:o,title:r,referrersIndices:s}=t.data;let u;if("number"==typeof s[0]&&(a=s),i.has(o)){const t=i.get(o).timestamps;u=new xe({urlAddress:o,title:r,referrers:a}),u.timestamps=[...t,{time:n,status:e.TrackingStatus.Sent}]}else u=new xe({urlAddress:o,title:r,referrers:a}),u.timestamps=[{time:n,status:e.TrackingStatus.Sent}];i.set(o,u)}}}let Oe=class t{constructor(i,a,...n){this._status=e.TrackingStatus.Unsent,this.isIdentifier=!1;const o="boolean"==typeof a;"number"==typeof i?this._index=i:(this._name=i,this._index=t.UNDEFINED_INDEX),this.overwrite=!o||a,this.value=o?n:[a,...n].filter(e=>null!=e)}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(this.overwrite)+i}get data(){return Object.assign(Object.assign({index:this._index},void 0!==this._name?{name:this._name}:{}),{value:this.value,type:e.KameleoonData.CustomData,isIdentifier:this.isIdentifier,status:this.status,overwrite:this.overwrite})}get status(){return this._isMappingIdentifier?e.TrackingStatus.Unsent:this._status}static _fromRaw(e){const{index:i,value:a,status:n,isIdentifier:o,name:r,overwrite:s}=e;let u;return r?(u=new t(r,null==s||s,...a),u.index=i):u=new t(i,null==s||s,...a),u.status=n,u._isMappingIdentifier=o,u}set _isMappingIdentifier(e){this.isIdentifier=e}set status(e){this._status=e}static _updateFromVisit(e,i){var a;if(null===(a=e.customDataEvents)||void 0===a?void 0:a.length)for(let a=e.customDataEvents.length-1;a>=0;a--){const{index:n,valuesCountMap:o}=e.customDataEvents[a].data;i.has(n)||i.set(n,new t(n,...Object.keys(o)))}}set index(e){this._index=e}get index(){return this._index}get name(){return this._name}get values(){return this.value}};Oe.UNDEFINED_INDEX=-1;let $e=class t{constructor({goalId:t,revenue:i=0,negative:a=!1,metadata:n}){this.goalId=t,this.revenue=i,this.negative=a,this.status=e.TrackingStatus.Unsent,this.id=Math.floor(1e6*Math.random()),this._metadata=n}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 _metadata(){return this.metadata}set _metadata(e){this.metadata=e}get data(){var t;return{goalId:this.goalId,nonce:this.nonce,revenue:this.revenue,negative:this.negative,type:e.KameleoonData.Conversion,status:this.status,id:this.id,metadata:(null===(t=this.metadata)||void 0===t?void 0:t.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(e){const{goalId:i,revenue:a,negative:n,status:o,id:r,nonce:s,metadata:u}=e,l=new t({goalId:i,revenue:a,negative:n,metadata:t.parseMetadata(u)});return l._id=r,l.status=o,s&&(l._nonce=s),l}static parseMetadata(e){return(null==e?void 0:e.map(e=>Oe._fromRaw(e)))||void 0}static _listFromVisit(i){var a,n;const o=[];if(!(null===(a=i.conversionEvents)||void 0===a?void 0:a.length))return[];if(null===(n=i.conversionEvents)||void 0===n?void 0:n.length)for(const a of i.conversionEvents){const{goalId:i,revenue:n,negative:r}=a.data,s=new t({goalId:i,revenue:n,negative:r});s.status=e.TrackingStatus.Sent,o.push(s)}return o}static _updateFromVisit(i,a){var n;if(null===(n=i.conversionEvents)||void 0===n?void 0:n.length)for(const n of i.conversionEvents){const{goalId:i}=n.data;if(!a.has(i)){const n=new t({goalId:i});n.status=e.TrackingStatus.Sent,a.set(i,n)}}}},Ne=class t{constructor(t,i){this.browser=t,this.version=i,this.status=e.TrackingStatus.Unsent}get url(){if(!this.browser)return"";const e=this.version?E+this.version:"";return y+b+this.browser+D+le[this.browser]+e}get data(){return{browser:this.browser,type:e.KameleoonData.Browser,version:this.version,status:this.status}}static _fromRaw(e){const{browser:i,version:a,status:n}=e,o=new t(i,a);return o.status=n,o}static _fromVisit(e){if(!e.staticDataEvent)return;const{browser:i,browserIndex:a,browserVersion:n}=e.staticDataEvent.data;if(i||"number"==typeof a){const e=null!=i?i:de[a];return n?new t(e,n):new t(e)}}},Me=class t{constructor(t){this.device=t,this.status=e.TrackingStatus.Unsent}get url(){return this.device?y+T+this.device:""}get data(){return{device:this.device,type:e.KameleoonData.Device,status:this.status}}static _fromRaw(e){const{device:i,status:a}=e,n=new t(i);return n.status=a,n}static _fromVisit(e){var i;if(null===(i=e.staticDataEvent)||void 0===i?void 0:i.data.deviceType)return new t(e.staticDataEvent.data.deviceType)}},Fe=class t{constructor(t){this.operatingSystem=t,this.status=e.TrackingStatus.Unsent}get url(){return this.operatingSystem?y+w+this.operatingSystem+R+se[this.operatingSystem]:""}get data(){return{operatingSystem:this.operatingSystem,type:e.KameleoonData.OperatingSystem,status:this.status}}static _fromRaw(e){const{operatingSystem:i,status:a}=e,n=new t(i);return n.status=a,n}static _fromVisit(e){if(!e.staticDataEvent)return;const{os:i,osIndex:a}=e.staticDataEvent.data;if(i||"number"==typeof a){const e=null!=i?i:ue[a];return new t(e)}}};class Le{constructor({country:t,region:i,city:a,postalCode:n,coordinates:o}){this.country=t,this.region=i,this.city=a,this.postalCode=n,this.coordinates=o,this.status=e.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:e.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:n,coordinates:o,status:r}=e,s=new Le({country:t,region:i,city:a,postalCode:n,coordinates:o});return s.status=r,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:n,city:o}=i||{};return a?new Le(n&&o?{country:a,region:n,city:o}:n?{country:a,region:n}:{country:a}):void 0}}class _e{constructor(t){this.status=e.TrackingStatus.Sent,this.visits=t,this._visitNumber=t.length?t.length-1:0}g