Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@kameleoon/javascript-sdk-core

Package Overview
Dependencies
Maintainers
0
Versions
67
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@kameleoon/javascript-sdk-core - npm Package Compare versions

Comparing version 4.4.0 to 4.4.1

7

CHANGELOG_INTERNAL.md
# Internal Change Log
All significant internal changes to this project will be documented in this file.
## 4.4.1 (2024-07-12)
### Patch Changes
- `deploy_bundle` CI/CD step now re-builds SDK before running script to make sure it's still cached when deploying separately from the main pipeline.
# Change Log
## 4.4.1 (2024-07-12)
### Patch Changes
- `ClientConfiguration` and `RemoteData` Kameleoon Exceptions are now more informative
- [`getEngineTrackingCode`](https://developers.kameleoon.com/feature-management-and-experimentation/web-sdks/js-sdk/#getenginetrackingcode) output code is now correctly overrides experiment variation assigned by JS Script
## 4.4.0 (2024-06-21)

@@ -4,0 +11,0 @@

2

dist/kameleoonClient.js

@@ -1,2 +0,2 @@

"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.KameleoonClient=void 0;var _tsRes=require("ts-res"),_cacheManager=require("./cacheManager"),_clientConfiguration=require("./clientConfiguration"),_clientSettings=require("./clientSettings"),_constants=require("./constants"),_kameleoonData=require("./kameleoonData"),_kameleoonError=require("./kameleoonError"),_requester=require("./requester"),_storage=require("./storage"),_utilities=require("./utilities"),_variationConfiguration=require("./variationConfiguration"),_eventManager=require("./eventManager"),_eventSource=require("./eventSource"),_visitorCodeManager=require("./visitorCodeManager");function _defineProperty(a,b,c){return b=_toPropertyKey(b),b in a?Object.defineProperty(a,b,{value:c,enumerable:!0,configurable:!0,writable:!0}):a[b]=c,a}function _toPropertyKey(a){var b=_toPrimitive(a,"string");return"symbol"==typeof b?b:b+""}function _toPrimitive(a,b){if("object"!=typeof a||!a)return a;var c=a[Symbol.toPrimitive];if(void 0!==c){var d=c.call(a,b||"default");if("object"!=typeof d)return d;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===b?String:Number)(a)}class KameleoonClient{constructor(a){let{siteCode:b,configuration:c,internalConfiguration:d}=a;_defineProperty(this,"variationConfiguration",void 0),_defineProperty(this,"clientConfiguration",void 0),_defineProperty(this,"dataManager",void 0),_defineProperty(this,"offlineTrackingStorage",void 0),_defineProperty(this,"consentDataStorage",void 0),_defineProperty(this,"trackingCache",void 0),_defineProperty(this,"requester",void 0),_defineProperty(this,"externalPackageInfo",void 0),_defineProperty(this,"initialized",!1),_defineProperty(this,"visitorCodeManager",void 0),_defineProperty(this,"eventManager",void 0),_defineProperty(this,"environment",void 0),_defineProperty(this,"isOfflineModeOn",void 0);const{settings:e}=new _clientSettings.ClientSettings(b,c);this.environment=e.environment;const{externalStorage:f,externalEventSource:g,externalPackageInfo:h,externalVisitorCodeManager:i,externalRequester:j,externalClientConfiguration:k}=d,l=new _cacheManager.CacheManager(_constants.CACHE_CLEANUP_TIMEOUT),m=new _storage.DataStorage(f,_storage.KameleoonStorageKey.ClientData),n=new _storage.DataStorage(f,_storage.KameleoonStorageKey.TargetingData),o=new _storage.DataStorage(f,_storage.KameleoonStorageKey.VariationData),p=new _storage.DataStorage(f,_storage.KameleoonStorageKey.OfflineTracking),q=new _storage.DataStorage(f,_storage.KameleoonStorageKey.ConsentData),r=new _kameleoonData.DataManager({storage:n,cleanupInterval:e.cleanupInterval}),s=new _requester.Requester({siteCode:b,domain:e.networkDomain,environment:e.environment,packageInfo:h,externalRequester:j,requestTimeout:e.requestTimeout,trackRetryDelay:e.trackRetryDelay}),t=new _eventSource.KameleoonEventSource(e.siteCode,g),u=new _eventManager.EventManager,v=new _clientConfiguration.ClientConfiguration({storage:m,updateInterval:e.updateInterval,dataManager:r,eventManager:u,requester:s,externalClientConfiguration:k,offlineTrackingStorage:p,eventSource:t,externalVisitorCodeManager:i}),w=new _variationConfiguration.VariationConfiguration(o);this.variationConfiguration=w,this.requester=s,this.trackingCache=l,this.dataManager=r,this.clientConfiguration=v,this.externalPackageInfo=h,this.offlineTrackingStorage=p,this.consentDataStorage=q,this.visitorCodeManager=i,this.eventManager=u}async initialize(a){const b=await this.clientConfiguration.initialize();return b.throw(),this.isOfflineModeOn=a,this.initialized=!0,b.ok}addData(a){if(_utilities.Utilities.validateVisitorCode(a).throw(),!this.initialized)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization);for(var b=arguments.length,c=Array(1<b?b-1:0),d=1;d<b;d++)c[d-1]=arguments[d];this.dataManager.addData(a,...c).throw()}async getRemoteVisitorData(a){let{visitorCode:b,shouldAddData:c=!0,filters:d=_constants.DEFAULT_VISITOR_DATA_FILTERS,isUniqueIdentifier:e=!1}=a;if(!this.initialized)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization);_utilities.Utilities.validateVisitorCode(b).throw();const{previousVisitAmount:f}=d;if("number"==typeof f&&(1>f||25<f))throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.VisitAmount);const g=await this.requester.getVisitorData({visitorCode:b,filters:d,isMappingIdentifier:e}),h=g.throw(),{visitorData:i,storageVisitorData:j,visitsData:k}=_utilities.Utilities.parseVisitorData({data:h,filters:d,visitorCode:b,dataManager:this.dataManager,variationConfiguration:this.variationConfiguration});for(const d of j)(c||this.dataManager.isPersistentCustomData(d))&&this.addData(b,d);return k&&c&&this.addData(b,k),i}trackConversion(a){let{visitorCode:b,goalId:c,revenue:d,isUniqueIdentifier:e}=a;this.addData(b,new _kameleoonData.Conversion({goalId:c,revenue:d})),this.flush(b,e)}flush(a,b){if(!this.initialized)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization);if("string"==typeof a&&_utilities.Utilities.validateVisitorCode(a).throw(),a){let c=!1;if(b){const b=this.dataManager.getLinkedVisitor(a),d=this.dataManager.identifierCustomDataIndex;b||"number"!=typeof d?c=!0:this.dataManager.addData(a,new _kameleoonData.CustomData(d,a))}return void _utilities.Utilities.trackData({visitorCode:a,isMappingIdentifier:c,dataManager:this.dataManager,requester:this.requester,isOfflineModeOn:this.isOfflineModeOn,isConsentProvided:this._isConsentProvided(a),offlineTrackingStorage:this.offlineTrackingStorage})}if(!this.dataManager.unsentDataVisitors.length)return void _utilities.Utilities.sendOfflineTracking({requester:this.requester,storage:this.offlineTrackingStorage});for(const c of this.dataManager.unsentDataVisitors)_utilities.Utilities.trackData({visitorCode:c,dataManager:this.dataManager,requester:this.requester,isOfflineModeOn:this.isOfflineModeOn,isConsentProvided:this._isConsentProvided(c),offlineTrackingStorage:this.offlineTrackingStorage})}getFeatureFlags(){if(!this.initialized)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization);const a=this.clientConfiguration.featureFlags,b=[];return a.forEach(a=>{let{id:c,featureKey:d}=a;b.push({id:c,key:d})}),b}getVisitorFeatureFlags(a){if(!this.initialized)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization);const b=this._getActiveFeatureVariations(a),c=[];return b.forEach(a=>{let{featureFlagId:b,featureKey:d}=a;c.push({id:b,key:d})}),c}getActiveFeatureFlags(a){const b=this._getActiveFeatureVariations(a),c=new Map;return b.forEach(b=>{const{variationKey:d,featureKey:e,variationId:f,experimentId:g}=b;let h=[];null!==f&&null!==g&&(h=this._getFeatureVariables({visitorCode:a,featureKey:e,variationKey:d}));const i=h.map(a=>_utilities.Utilities.parseFeatureVariable(a).throw());c.set(b.featureKey,{key:d,id:f,experimentId:g,variables:i})}),c}getFeatureFlagVariationKey(a,b){_utilities.Utilities.validateVisitorCode(a).throw();const{variationKey:c}=this._getFeatureVariation(a,b).throw();return c}getFeatureFlagVariable(a){let{visitorCode:b,featureKey:c,variableKey:d}=a;_utilities.Utilities.validateVisitorCode(b).throw();const{variationKey:e}=this._getFeatureVariation(b,c).throw(),f=this._getFeatureVariables({visitorCode:b,featureKey:c,variationKey:e}),g=f.find(a=>a.key===d);if(!g)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.FeatureFlagVariableNotFound,d,b);const{type:h,value:i}=_utilities.Utilities.parseFeatureVariable(g).throw();return{type:h,value:i}}getFeatureFlagVariables(a,b){_utilities.Utilities.validateVisitorCode(a).throw();const{variationKey:c}=this._getFeatureVariation(a,b).throw(),d=this._getFeatureVariables({visitorCode:a,featureKey:b,variationKey:c}),e=[];for(const c of d){const a=_utilities.Utilities.parseFeatureVariable(c).throw();e.push(a)}return e}isFeatureFlagActive(a,b){try{const c=this.getFeatureFlagVariationKey(a,b);return c!==_constants.OFF_VARIATION_KEY}catch(a){if(a instanceof _kameleoonError.KameleoonError&&a.type===_kameleoonError.KameleoonException.FeatureFlagEnvironmentDisabled)return!1;throw a}}async getRemoteData(a){const b=await this.requester.getRemoteData(a);return b.throw()}async getVisitorWarehouseAudience(a){let{visitorCode:b,customDataIndex:c,warehouseKey:d}=a;_utilities.Utilities.validateVisitorCode(b).throw();const e=await this.getRemoteData(d||b);if(!e)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.RemoteData);if(!e[_constants.WAREHOUSE_AUDIENCE_KEY]||0===Object.keys(e[_constants.WAREHOUSE_AUDIENCE_KEY]).length)return null;const f=new _kameleoonData.CustomData(c,...Object.keys(e[_constants.WAREHOUSE_AUDIENCE_KEY]));return this.dataManager.addData(b,f),f}onConfigurationUpdate(a){if(!this.initialized)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization);this.eventManager.addEventHandler(_eventManager.EventType.ConfigurationUpdate,a)}onEvent(a,b){if(!this.initialized)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization);this.eventManager.addEventHandler(a,b)}getEngineTrackingCode(a){return _utilities.Utilities.validateVisitorCode(a).throw(),_utilities.Utilities.getTrackingCode(this.trackingCache,a)}isInitialized(){return this.initialized}setUserConsent(a){let{visitorCode:b,consent:c,setData:d}=a;_utilities.Utilities.validateVisitorCode(b).throw(),this.consentDataStorage.update({[b]:c}),c?d({visitorCode:b,key:_storage.KameleoonStorageKey.VisitorCode,maxAge:_visitorCodeManager.DEFAULT_MAX_AGE,path:_visitorCodeManager.PATH}):this.visitorCodeManager.consentRequired&&d({visitorCode:"",key:_storage.KameleoonStorageKey.VisitorCode,maxAge:_visitorCodeManager.ZERO_MAX_AGE,path:_visitorCodeManager.PATH})}_isConsentProvided(a){const{isConsentRequired:b}=this.clientConfiguration,c=this.consentDataStorage.read();return!b||c.ok&&c.data[a]}_getFeatureVariables(a){let{visitorCode:b,featureKey:c,variationKey:d}=a;const e=this.clientConfiguration.featureFlags,f=e.get(c);if(!f)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.FeatureFlagConfigurationNotFound,c);const g=f.variations.find(a=>a.key===d);if(!g)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.FeatureFlagVariationNotFound,d,b);return g.variables}_getActiveFeatureVariations(a){if(!this.initialized)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization);const b=this.clientConfiguration.featureFlags,c=[],d=this.dataManager.getTargetingData(a),e=this.dataManager.getVisitorIdentifier(a);for(const f of b.values()){if(!f.environmentEnabled)continue;const b=this.variationConfiguration.getVariation({visitorCode:a,visitorIdentifier:e,targetingData:d,featureFlag:f,clientConfiguration:this.clientConfiguration,dataManager:this.dataManager,packageInfo:this.externalPackageInfo}).throw();this.eventManager.fireEvent(_eventManager.EventType.Evaluation,{featureKey:f.featureKey,variation:{key:b.variationKey,experimentId:b.experimentId,id:b.variationId}}),b.variationKey!==_constants.OFF_VARIATION_KEY&&c.push(b)}return c}_getFeatureVariation(a,b){if(!this.initialized)return(0,_tsRes.Err)(new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization));const c=this.clientConfiguration.featureFlags,d=c.get(b);if(!d)return(0,_tsRes.Err)(new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.FeatureFlagConfigurationNotFound,b));if(!d.environmentEnabled)return(0,_tsRes.Err)(new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.FeatureFlagEnvironmentDisabled,d.featureKey,this.environment));const e=this.dataManager.getTargetingData(a),f=this.dataManager.getVisitorIdentifier(a),g=this.variationConfiguration.getVariation({visitorCode:a,visitorIdentifier:f,featureFlag:d,targetingData:e,withAssignment:!0,clientConfiguration:this.clientConfiguration,dataManager:this.dataManager,packageInfo:this.externalPackageInfo}).throw();this.eventManager.fireEvent(_eventManager.EventType.Evaluation,{featureKey:b,variation:{key:g.variationKey,experimentId:g.experimentId,id:g.variationId}});const{experimentId:h,variationId:i}=g;return"number"==typeof i&&"number"==typeof h&&_utilities.Utilities.updateCache({cacheManager:this.trackingCache,visitorCode:a,experimentId:h,variationId:i}),_utilities.Utilities.trackFeatureExperiment({visitorCode:a,requester:this.requester,featureFlagVariation:g,dataManager:this.dataManager,isOfflineModeOn:this.isOfflineModeOn,isConsentProvided:this._isConsentProvided(a),offlineTrackingStorage:this.offlineTrackingStorage,variationConfiguration:this.variationConfiguration}),(0,_tsRes.Ok)(g)}}exports.KameleoonClient=KameleoonClient;
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.KameleoonClient=void 0;var _tsRes=require("ts-res"),_cacheManager=require("./cacheManager"),_clientConfiguration=require("./clientConfiguration"),_clientSettings=require("./clientSettings"),_constants=require("./constants"),_kameleoonData=require("./kameleoonData"),_kameleoonError=require("./kameleoonError"),_requester=require("./requester"),_storage=require("./storage"),_utilities=require("./utilities"),_variationConfiguration=require("./variationConfiguration"),_eventManager=require("./eventManager"),_eventSource=require("./eventSource"),_visitorCodeManager=require("./visitorCodeManager");function _defineProperty(a,b,c){return b=_toPropertyKey(b),b in a?Object.defineProperty(a,b,{value:c,enumerable:!0,configurable:!0,writable:!0}):a[b]=c,a}function _toPropertyKey(a){var b=_toPrimitive(a,"string");return"symbol"==typeof b?b:b+""}function _toPrimitive(a,b){if("object"!=typeof a||!a)return a;var c=a[Symbol.toPrimitive];if(void 0!==c){var d=c.call(a,b||"default");if("object"!=typeof d)return d;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===b?String:Number)(a)}class KameleoonClient{constructor(a){let{siteCode:b,configuration:c,internalConfiguration:d}=a;_defineProperty(this,"variationConfiguration",void 0),_defineProperty(this,"clientConfiguration",void 0),_defineProperty(this,"dataManager",void 0),_defineProperty(this,"offlineTrackingStorage",void 0),_defineProperty(this,"consentDataStorage",void 0),_defineProperty(this,"trackingCache",void 0),_defineProperty(this,"requester",void 0),_defineProperty(this,"externalPackageInfo",void 0),_defineProperty(this,"initialized",!1),_defineProperty(this,"visitorCodeManager",void 0),_defineProperty(this,"eventManager",void 0),_defineProperty(this,"environment",void 0),_defineProperty(this,"isOfflineModeOn",void 0);const{settings:e}=new _clientSettings.ClientSettings(b,c);this.environment=e.environment;const{externalStorage:f,externalEventSource:g,externalPackageInfo:h,externalVisitorCodeManager:i,externalRequester:j,externalClientConfiguration:k}=d,l=new _cacheManager.CacheManager(_constants.CACHE_CLEANUP_TIMEOUT),m=new _storage.DataStorage(f,_storage.KameleoonStorageKey.ClientData),n=new _storage.DataStorage(f,_storage.KameleoonStorageKey.TargetingData),o=new _storage.DataStorage(f,_storage.KameleoonStorageKey.VariationData),p=new _storage.DataStorage(f,_storage.KameleoonStorageKey.OfflineTracking),q=new _storage.DataStorage(f,_storage.KameleoonStorageKey.ConsentData),r=new _kameleoonData.DataManager({storage:n,cleanupInterval:e.cleanupInterval}),s=new _requester.Requester({siteCode:b,domain:e.networkDomain,environment:e.environment,packageInfo:h,externalRequester:j,requestTimeout:e.requestTimeout,trackRetryDelay:e.trackRetryDelay}),t=new _eventSource.KameleoonEventSource(e.siteCode,g),u=new _eventManager.EventManager,v=new _clientConfiguration.ClientConfiguration({storage:m,updateInterval:e.updateInterval,dataManager:r,eventManager:u,requester:s,externalClientConfiguration:k,offlineTrackingStorage:p,eventSource:t,externalVisitorCodeManager:i}),w=new _variationConfiguration.VariationConfiguration(o);this.variationConfiguration=w,this.requester=s,this.trackingCache=l,this.dataManager=r,this.clientConfiguration=v,this.externalPackageInfo=h,this.offlineTrackingStorage=p,this.consentDataStorage=q,this.visitorCodeManager=i,this.eventManager=u}async initialize(a){const b=await this.clientConfiguration.initialize();return b.throw(),this.isOfflineModeOn=a,this.initialized=!0,b.ok}addData(a){if(_utilities.Utilities.validateVisitorCode(a).throw(),!this.initialized)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization);for(var b=arguments.length,c=Array(1<b?b-1:0),d=1;d<b;d++)c[d-1]=arguments[d];this.dataManager.addData(a,...c).throw()}async getRemoteVisitorData(a){let{visitorCode:b,shouldAddData:c=!0,filters:d=_constants.DEFAULT_VISITOR_DATA_FILTERS,isUniqueIdentifier:e=!1}=a;if(!this.initialized)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization);_utilities.Utilities.validateVisitorCode(b).throw();const{previousVisitAmount:f}=d;if("number"==typeof f&&(1>f||25<f))throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.VisitAmount);const g=await this.requester.getVisitorData({visitorCode:b,filters:d,isMappingIdentifier:e}),h=g.throw(),{visitorData:i,storageVisitorData:j,visitsData:k}=_utilities.Utilities.parseVisitorData({data:h,filters:d,visitorCode:b,dataManager:this.dataManager,variationConfiguration:this.variationConfiguration});for(const d of j)(c||this.dataManager.isPersistentCustomData(d))&&this.addData(b,d);return k&&c&&this.addData(b,k),i}trackConversion(a){let{visitorCode:b,goalId:c,revenue:d,isUniqueIdentifier:e}=a;this.addData(b,new _kameleoonData.Conversion({goalId:c,revenue:d})),this.flush(b,e)}flush(a,b){if(!this.initialized)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization);if("string"==typeof a&&_utilities.Utilities.validateVisitorCode(a).throw(),a){let c=!1;if(b){const b=this.dataManager.getLinkedVisitor(a),d=this.dataManager.identifierCustomDataIndex;b||"number"!=typeof d?c=!0:this.dataManager.addData(a,new _kameleoonData.CustomData(d,a))}return void _utilities.Utilities.trackData({visitorCode:a,isMappingIdentifier:c,dataManager:this.dataManager,requester:this.requester,isOfflineModeOn:this.isOfflineModeOn,isConsentProvided:this._isConsentProvided(a),offlineTrackingStorage:this.offlineTrackingStorage})}if(!this.dataManager.unsentDataVisitors.length)return void _utilities.Utilities.sendOfflineTracking({requester:this.requester,storage:this.offlineTrackingStorage});for(const c of this.dataManager.unsentDataVisitors)_utilities.Utilities.trackData({visitorCode:c,dataManager:this.dataManager,requester:this.requester,isOfflineModeOn:this.isOfflineModeOn,isConsentProvided:this._isConsentProvided(c),offlineTrackingStorage:this.offlineTrackingStorage})}getFeatureFlags(){if(!this.initialized)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization);const a=this.clientConfiguration.featureFlags,b=[];return a.forEach(a=>{let{id:c,featureKey:d}=a;b.push({id:c,key:d})}),b}getVisitorFeatureFlags(a){if(!this.initialized)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization);const b=this._getActiveFeatureVariations(a),c=[];return b.forEach(a=>{let{featureFlagId:b,featureKey:d}=a;c.push({id:b,key:d})}),c}getActiveFeatureFlags(a){const b=this._getActiveFeatureVariations(a),c=new Map;return b.forEach(b=>{const{variationKey:d,featureKey:e,variationId:f,experimentId:g}=b;let h=[];null!==f&&null!==g&&(h=this._getFeatureVariables({visitorCode:a,featureKey:e,variationKey:d}));const i=h.map(a=>_utilities.Utilities.parseFeatureVariable(a).throw());c.set(b.featureKey,{key:d,id:f,experimentId:g,variables:i})}),c}getFeatureFlagVariationKey(a,b){_utilities.Utilities.validateVisitorCode(a).throw();const{variationKey:c}=this._getFeatureVariation(a,b).throw();return c}getFeatureFlagVariable(a){let{visitorCode:b,featureKey:c,variableKey:d}=a;_utilities.Utilities.validateVisitorCode(b).throw();const{variationKey:e}=this._getFeatureVariation(b,c).throw(),f=this._getFeatureVariables({visitorCode:b,featureKey:c,variationKey:e}),g=f.find(a=>a.key===d);if(!g)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.FeatureFlagVariableNotFound,d,b);const{type:h,value:i}=_utilities.Utilities.parseFeatureVariable(g).throw();return{type:h,value:i}}getFeatureFlagVariables(a,b){_utilities.Utilities.validateVisitorCode(a).throw();const{variationKey:c}=this._getFeatureVariation(a,b).throw(),d=this._getFeatureVariables({visitorCode:a,featureKey:b,variationKey:c}),e=[];for(const c of d){const a=_utilities.Utilities.parseFeatureVariable(c).throw();e.push(a)}return e}isFeatureFlagActive(a,b){try{const c=this.getFeatureFlagVariationKey(a,b);return c!==_constants.OFF_VARIATION_KEY}catch(a){if(a instanceof _kameleoonError.KameleoonError&&a.type===_kameleoonError.KameleoonException.FeatureFlagEnvironmentDisabled)return!1;throw a}}async getRemoteData(a){const b=await this.requester.getRemoteData(a);return b.throw()}async getVisitorWarehouseAudience(a){let{visitorCode:b,customDataIndex:c,warehouseKey:d}=a;_utilities.Utilities.validateVisitorCode(b).throw();const e=await this.getRemoteData(d||b);if(!e)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.RemoteData,"No data found for ".concat(d||b," key"));if(!e[_constants.WAREHOUSE_AUDIENCE_KEY]||0===Object.keys(e[_constants.WAREHOUSE_AUDIENCE_KEY]).length)return null;const f=new _kameleoonData.CustomData(c,...Object.keys(e[_constants.WAREHOUSE_AUDIENCE_KEY]));return this.dataManager.addData(b,f),f}onConfigurationUpdate(a){if(!this.initialized)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization);this.eventManager.addEventHandler(_eventManager.EventType.ConfigurationUpdate,a)}onEvent(a,b){if(!this.initialized)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization);this.eventManager.addEventHandler(a,b)}getEngineTrackingCode(a){return _utilities.Utilities.validateVisitorCode(a).throw(),_utilities.Utilities.getTrackingCode(this.trackingCache,a)}isInitialized(){return this.initialized}setUserConsent(a){let{visitorCode:b,consent:c,setData:d}=a;_utilities.Utilities.validateVisitorCode(b).throw(),this.consentDataStorage.update({[b]:c}),c?d({visitorCode:b,key:_storage.KameleoonStorageKey.VisitorCode,maxAge:_visitorCodeManager.DEFAULT_MAX_AGE,path:_visitorCodeManager.PATH}):this.visitorCodeManager.consentRequired&&d({visitorCode:"",key:_storage.KameleoonStorageKey.VisitorCode,maxAge:_visitorCodeManager.ZERO_MAX_AGE,path:_visitorCodeManager.PATH})}_isConsentProvided(a){const{isConsentRequired:b}=this.clientConfiguration,c=this.consentDataStorage.read();return!b||c.ok&&c.data[a]}_getFeatureVariables(a){let{visitorCode:b,featureKey:c,variationKey:d}=a;const e=this.clientConfiguration.featureFlags,f=e.get(c);if(!f)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.FeatureFlagConfigurationNotFound,c);const g=f.variations.find(a=>a.key===d);if(!g)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.FeatureFlagVariationNotFound,d,b);return g.variables}_getActiveFeatureVariations(a){if(!this.initialized)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization);const b=this.clientConfiguration.featureFlags,c=[],d=this.dataManager.getTargetingData(a),e=this.dataManager.getVisitorIdentifier(a);for(const f of b.values()){if(!f.environmentEnabled)continue;const b=this.variationConfiguration.getVariation({visitorCode:a,visitorIdentifier:e,targetingData:d,featureFlag:f,clientConfiguration:this.clientConfiguration,dataManager:this.dataManager,packageInfo:this.externalPackageInfo}).throw();this.eventManager.fireEvent(_eventManager.EventType.Evaluation,{featureKey:f.featureKey,variation:{key:b.variationKey,experimentId:b.experimentId,id:b.variationId}}),b.variationKey!==_constants.OFF_VARIATION_KEY&&c.push(b)}return c}_getFeatureVariation(a,b){if(!this.initialized)return(0,_tsRes.Err)(new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization));const c=this.clientConfiguration.featureFlags,d=c.get(b);if(!d)return(0,_tsRes.Err)(new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.FeatureFlagConfigurationNotFound,b));if(!d.environmentEnabled)return(0,_tsRes.Err)(new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.FeatureFlagEnvironmentDisabled,d.featureKey,this.environment));const e=this.dataManager.getTargetingData(a),f=this.dataManager.getVisitorIdentifier(a),g=this.variationConfiguration.getVariation({visitorCode:a,visitorIdentifier:f,featureFlag:d,targetingData:e,withAssignment:!0,clientConfiguration:this.clientConfiguration,dataManager:this.dataManager,packageInfo:this.externalPackageInfo}).throw();this.eventManager.fireEvent(_eventManager.EventType.Evaluation,{featureKey:b,variation:{key:g.variationKey,experimentId:g.experimentId,id:g.variationId}});const{experimentId:h,variationId:i}=g;return"number"==typeof i&&"number"==typeof h&&_utilities.Utilities.updateCache({cacheManager:this.trackingCache,visitorCode:a,experimentId:h,variationId:i}),_utilities.Utilities.trackFeatureExperiment({visitorCode:a,requester:this.requester,featureFlagVariation:g,dataManager:this.dataManager,isOfflineModeOn:this.isOfflineModeOn,isConsentProvided:this._isConsentProvided(a),offlineTrackingStorage:this.offlineTrackingStorage,variationConfiguration:this.variationConfiguration}),(0,_tsRes.Ok)(g)}}exports.KameleoonClient=KameleoonClient;
//# sourceMappingURL=kameleoonClient.js.map

@@ -25,8 +25,8 @@ import { KameleoonStorageKey } from '../storage';

StorageParse: (err: unknown, key: KameleoonStorageKey) => string;
ClientConfiguration: () => string;
ClientConfiguration: (err: unknown) => string;
TargetingCondition: (targetingType: TargetingType) => string;
AmongValuesCheck: (err: unknown, value: string) => string;
RangeCheck: (value?: number[] | null) => string;
RemoteData: () => string;
MaximumRetriesReached: () => string;
RemoteData: (err: unknown) => string;
MaximumRetriesReached: (err: unknown) => string;
};

@@ -1,2 +0,2 @@

"use strict";var _types=require("./types");Object.defineProperty(exports,"__esModule",{value:!0}),exports.ERROR_MESSAGES=void 0;const ERROR_MESSAGES=exports.ERROR_MESSAGES={[_types.KameleoonException.CookieParse]:a=>"Couldn't parse cookie string: ".concat(a),[_types.KameleoonException.JSONParse]:a=>"Couldn't parse JSON variable: ".concat(a),[_types.KameleoonException.NumberParse]:a=>"It's not possible to parse value ".concat(a," to Number"),[_types.KameleoonException.VersionParse]:a=>"It's not possible to parse a version value ".concat(a," to Number, version should be in format x.x"),[_types.KameleoonException.SemanticVersionParse]:a=>"It's not possible to parse a version value ".concat(a," to Number, version should be in format x.x.x"),[_types.KameleoonException.Initialization]:()=>"It seems that the client wasn't properly initialized, make sure to run `initialize` method before invoking other methods",[_types.KameleoonException.Credentials]:()=>"KameleoonClient can not be created without credentials",[_types.KameleoonException.StorageInitialization]:()=>"There was an error while initializing React Native SDK storage, it seems that the storage library dependency wasn't installed",[_types.KameleoonException.EventSourceInitialization]:()=>"There was an error while initializing Real Time Update service, it seems that the event source library dependency wasn't installed",[_types.KameleoonException.FeatureFlagConfigurationNotFound]:a=>"No feature flag with key ".concat(a," was found."),[_types.KameleoonException.FeatureFlagEnvironmentDisabled]:(a,b)=>"Feature flag with key ".concat(a," is disabled in ").concat(b," environment."),[_types.KameleoonException.FeatureFlagVariableNotFound]:(a,b)=>"No feature flag variable with key ".concat(a," was found for ").concat(b," visitorCode."),[_types.KameleoonException.FeatureFlagVariationNotFound]:(a,b)=>"No feature flag variation with key ".concat(a," was found for ").concat(b," visitorCode."),[_types.KameleoonException.NotTargeted]:a=>"Visitor code ".concat(a," is not targeted"),[_types.KameleoonException.VisitAmount]:()=>"Visit amount must be a number between 1 and 25",[_types.KameleoonException.VisitorCodeMaxLength]:()=>"Visitor code can not be more than 255 characters long",[_types.KameleoonException.VisitorCodeEmpty]:()=>"Visitor code can not be empty",[_types.KameleoonException.StorageWrite]:a=>"Couldn't update storage for kameleoonClient: ".concat(a),[_types.KameleoonException.StorageRead]:a=>"No data found in storage under ".concat(a," key"),[_types.KameleoonException.StorageEmpty]:()=>"No data found in storage",[_types.KameleoonException.StorageParse]:(a,b)=>"Couldn't parse ".concat(b," storage data, the data may be corrupted. Error: ").concat(a),[_types.KameleoonException.ClientConfiguration]:()=>"Couldn't retrieve client configuration from Kameleoon Api",[_types.KameleoonException.TargetingCondition]:a=>"".concat(a," targeting condition is not yet supported."),[_types.KameleoonException.AmongValuesCheck]:(a,b)=>"Couldn't parse value \"".concat(b,"\": ").concat(a),[_types.KameleoonException.RangeCheck]:a=>"Couldn't parse value \"".concat(a,"\" as a range, value should be in format [x: number, y: number]"),[_types.KameleoonException.RemoteData]:()=>"Couldn't retrieve data from Kameleoon server",[_types.KameleoonException.MaximumRetriesReached]:()=>"Maximum retries reached, request failed"};
"use strict";var _types=require("./types");Object.defineProperty(exports,"__esModule",{value:!0}),exports.ERROR_MESSAGES=void 0;const ERROR_MESSAGES=exports.ERROR_MESSAGES={[_types.KameleoonException.CookieParse]:a=>"Couldn't parse cookie string: ".concat(a),[_types.KameleoonException.JSONParse]:a=>"Couldn't parse JSON variable: ".concat(a),[_types.KameleoonException.NumberParse]:a=>"It's not possible to parse value ".concat(a," to Number"),[_types.KameleoonException.VersionParse]:a=>"It's not possible to parse a version value ".concat(a," to Number, version should be in format x.x"),[_types.KameleoonException.SemanticVersionParse]:a=>"It's not possible to parse a version value ".concat(a," to Number, version should be in format x.x.x"),[_types.KameleoonException.Initialization]:()=>"It seems that the client wasn't properly initialized, make sure to run `initialize` method before invoking other methods",[_types.KameleoonException.Credentials]:()=>"KameleoonClient can not be created without credentials",[_types.KameleoonException.StorageInitialization]:()=>"There was an error while initializing React Native SDK storage, it seems that the storage library dependency wasn't installed",[_types.KameleoonException.EventSourceInitialization]:()=>"There was an error while initializing Real Time Update service, it seems that the event source library dependency wasn't installed",[_types.KameleoonException.FeatureFlagConfigurationNotFound]:a=>"No feature flag with key ".concat(a," was found."),[_types.KameleoonException.FeatureFlagEnvironmentDisabled]:(a,b)=>"Feature flag with key ".concat(a," is disabled in ").concat(b," environment."),[_types.KameleoonException.FeatureFlagVariableNotFound]:(a,b)=>"No feature flag variable with key ".concat(a," was found for ").concat(b," visitorCode."),[_types.KameleoonException.FeatureFlagVariationNotFound]:(a,b)=>"No feature flag variation with key ".concat(a," was found for ").concat(b," visitorCode."),[_types.KameleoonException.NotTargeted]:a=>"Visitor code ".concat(a," is not targeted"),[_types.KameleoonException.VisitAmount]:()=>"Visit amount must be a number between 1 and 25",[_types.KameleoonException.VisitorCodeMaxLength]:()=>"Visitor code can not be more than 255 characters long",[_types.KameleoonException.VisitorCodeEmpty]:()=>"Visitor code can not be empty",[_types.KameleoonException.StorageWrite]:a=>"Couldn't update storage for kameleoonClient: ".concat(a),[_types.KameleoonException.StorageRead]:a=>"No data found in storage under ".concat(a," key"),[_types.KameleoonException.StorageEmpty]:()=>"No data found in storage",[_types.KameleoonException.StorageParse]:(a,b)=>"Couldn't parse ".concat(b," storage data, the data may be corrupted. Error: ").concat(a),[_types.KameleoonException.ClientConfiguration]:a=>"Couldn't retrieve client configuration from Kameleoon Api. Error: ".concat(a),[_types.KameleoonException.TargetingCondition]:a=>"".concat(a," targeting condition is not yet supported."),[_types.KameleoonException.AmongValuesCheck]:(a,b)=>"Couldn't parse value \"".concat(b,"\": ").concat(a),[_types.KameleoonException.RangeCheck]:a=>"Couldn't parse value \"".concat(a,"\" as a range, value should be in format [x: number, y: number]"),[_types.KameleoonException.RemoteData]:a=>"Couldn't retrieve data from Kameleoon server. Error: ".concat(a),[_types.KameleoonException.MaximumRetriesReached]:a=>"Maximum retries reached, request failed. Reason: ".concat(a)};
//# sourceMappingURL=constants.js.map

@@ -13,3 +13,3 @@ import { KameleoonStorageKey } from '../storage';

* */
constructor(type: KameleoonException.Initialization | KameleoonException.Credentials | KameleoonException.ClientConfiguration | KameleoonException.VisitorCodeMaxLength | KameleoonException.VisitorCodeEmpty | KameleoonException.VisitAmount | KameleoonException.StorageInitialization | KameleoonException.EventSourceInitialization | KameleoonException.RemoteData | KameleoonException.MaximumRetriesReached | KameleoonException.StorageEmpty);
constructor(type: KameleoonException.Initialization | KameleoonException.Credentials | KameleoonException.VisitorCodeMaxLength | KameleoonException.VisitorCodeEmpty | KameleoonException.VisitAmount | KameleoonException.StorageInitialization | KameleoonException.EventSourceInitialization | KameleoonException.StorageEmpty);
constructor(type: KameleoonException.FeatureFlagConfigurationNotFound | KameleoonException.FeatureFlagEnvironmentDisabled, featureKey: string);

@@ -21,3 +21,3 @@ constructor(type: KameleoonException.FeatureFlagConfigurationNotFound | KameleoonException.FeatureFlagEnvironmentDisabled, featureKey: string, environment: string);

constructor(type: KameleoonException.CookieParse, message: string);
constructor(type: KameleoonException.StorageWrite | KameleoonException.JSONParse, err: unknown);
constructor(type: KameleoonException.StorageWrite | KameleoonException.JSONParse | KameleoonException.RemoteData | KameleoonException.MaximumRetriesReached | KameleoonException.ClientConfiguration, err: unknown);
constructor(type: KameleoonException.StorageRead, storageKey: string);

@@ -24,0 +24,0 @@ constructor(type: KameleoonException.StorageParse, err: unknown, key: KameleoonStorageKey);

@@ -1,2 +0,2 @@

"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.KameleoonError=void 0;var _constants=require("./constants"),_helpers=require("./helpers"),_types=require("./types");function _defineProperty(a,b,c){return b=_toPropertyKey(b),b in a?Object.defineProperty(a,b,{value:c,enumerable:!0,configurable:!0,writable:!0}):a[b]=c,a}function _toPropertyKey(a){var b=_toPrimitive(a,"string");return"symbol"==typeof b?b:b+""}function _toPrimitive(a,b){if("object"!=typeof a||!a)return a;var c=a[Symbol.toPrimitive];if(void 0!==c){var d=c.call(a,b||"default");if("object"!=typeof d)return d;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===b?String:Number)(a)}class KameleoonError extends Error{constructor(a,b,c){super("Error: ".concat(a)),_defineProperty(this,"errorType",void 0),this.name="KameleoonError",this.errorType=a;a===_types.KameleoonException.Initialization||a===_types.KameleoonException.Credentials||a===_types.KameleoonException.ClientConfiguration||a===_types.KameleoonException.VisitorCodeMaxLength||a===_types.KameleoonException.VisitorCodeEmpty||a===_types.KameleoonException.StorageInitialization||a===_types.KameleoonException.VisitAmount||a===_types.KameleoonException.EventSourceInitialization||a===_types.KameleoonException.RemoteData||a===_types.KameleoonException.MaximumRetriesReached||a===_types.KameleoonException.StorageEmpty?this.message=_constants.ERROR_MESSAGES[a]():a===_types.KameleoonException.CookieParse||a===_types.KameleoonException.NotTargeted||a===_types.KameleoonException.FeatureFlagConfigurationNotFound||a===_types.KameleoonException.NumberParse||a===_types.KameleoonException.VersionParse||a===_types.KameleoonException.SemanticVersionParse?this.message=_constants.ERROR_MESSAGES[a](b):a===_types.KameleoonException.FeatureFlagVariationNotFound||a===_types.KameleoonException.FeatureFlagEnvironmentDisabled||a===_types.KameleoonException.FeatureFlagVariableNotFound?this.message=_constants.ERROR_MESSAGES[a](b,c):a===_types.KameleoonException.StorageWrite||a===_types.KameleoonException.JSONParse?this.message=_constants.ERROR_MESSAGES[a](b):a===_types.KameleoonException.StorageRead?this.message=_constants.ERROR_MESSAGES[a](b):a===_types.KameleoonException.StorageParse?this.message=_constants.ERROR_MESSAGES[a](b,c):a===_types.KameleoonException.TargetingCondition?this.message=_constants.ERROR_MESSAGES[a](b):a===_types.KameleoonException.AmongValuesCheck?this.message=_constants.ERROR_MESSAGES[a](b,c):a===_types.KameleoonException.RangeCheck?this.message=_constants.ERROR_MESSAGES[a](b):(0,_helpers.exhaustCheck)(a)}get type(){return this.errorType}}exports.KameleoonError=KameleoonError;
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.KameleoonError=void 0;var _constants=require("./constants"),_helpers=require("./helpers"),_types=require("./types");function _defineProperty(a,b,c){return b=_toPropertyKey(b),b in a?Object.defineProperty(a,b,{value:c,enumerable:!0,configurable:!0,writable:!0}):a[b]=c,a}function _toPropertyKey(a){var b=_toPrimitive(a,"string");return"symbol"==typeof b?b:b+""}function _toPrimitive(a,b){if("object"!=typeof a||!a)return a;var c=a[Symbol.toPrimitive];if(void 0!==c){var d=c.call(a,b||"default");if("object"!=typeof d)return d;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===b?String:Number)(a)}class KameleoonError extends Error{constructor(a,b,c){super("Error: ".concat(a)),_defineProperty(this,"errorType",void 0),this.name="KameleoonError",this.errorType=a;a===_types.KameleoonException.Initialization||a===_types.KameleoonException.Credentials||a===_types.KameleoonException.VisitorCodeMaxLength||a===_types.KameleoonException.VisitorCodeEmpty||a===_types.KameleoonException.StorageInitialization||a===_types.KameleoonException.VisitAmount||a===_types.KameleoonException.EventSourceInitialization||a===_types.KameleoonException.StorageEmpty?this.message=_constants.ERROR_MESSAGES[a]():a===_types.KameleoonException.CookieParse||a===_types.KameleoonException.NotTargeted||a===_types.KameleoonException.FeatureFlagConfigurationNotFound||a===_types.KameleoonException.NumberParse||a===_types.KameleoonException.ClientConfiguration||a===_types.KameleoonException.MaximumRetriesReached||a===_types.KameleoonException.RemoteData||a===_types.KameleoonException.VersionParse||a===_types.KameleoonException.SemanticVersionParse?this.message=_constants.ERROR_MESSAGES[a](b):a===_types.KameleoonException.FeatureFlagVariationNotFound||a===_types.KameleoonException.FeatureFlagEnvironmentDisabled||a===_types.KameleoonException.FeatureFlagVariableNotFound?this.message=_constants.ERROR_MESSAGES[a](b,c):a===_types.KameleoonException.StorageWrite||a===_types.KameleoonException.JSONParse?this.message=_constants.ERROR_MESSAGES[a](b):a===_types.KameleoonException.StorageRead?this.message=_constants.ERROR_MESSAGES[a](b):a===_types.KameleoonException.StorageParse?this.message=_constants.ERROR_MESSAGES[a](b,c):a===_types.KameleoonException.TargetingCondition?this.message=_constants.ERROR_MESSAGES[a](b):a===_types.KameleoonException.AmongValuesCheck?this.message=_constants.ERROR_MESSAGES[a](b,c):a===_types.KameleoonException.RangeCheck?this.message=_constants.ERROR_MESSAGES[a](b):(0,_helpers.exhaustCheck)(a)}get type(){return this.errorType}}exports.KameleoonError=KameleoonError;
//# sourceMappingURL=kameleoonError.js.map

@@ -1,2 +0,2 @@

"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.KameleoonUtils=void 0;var _kameleoonError=require("./kameleoonError"),_requester=require("./requester");class KameleoonUtils{static getClientConfigurationUrl(a,b,c){let d="https://sdk-config.".concat(c||"kameleoon.eu","/");return b?d+a+_requester.UrlFirstParameter.Environment+b:d+a}static simulateSuccessRequest(a,b){switch(a){case _requester.RequestType.Tracking:return new Promise(a=>{a({status:204,json:()=>new Promise(a=>a(null)),ok:!0})});case _requester.RequestType.Configuration:case _requester.RequestType.RemoteData:return new Promise(a=>{a({status:200,json:()=>new Promise(a=>a(b)),ok:!0})});default:(0,_kameleoonError.exhaustCheck)(a)}}static getCookieValue(a,b){const c=a.split("; "),d=c.find(a=>{const[c,d]=a.split("=");return c===b&&""!==d});return d?d.split("=")[1]:null}}exports.KameleoonUtils=KameleoonUtils;
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.KameleoonUtils=void 0;var _kameleoonError=require("./kameleoonError"),_requester=require("./requester");class KameleoonUtils{static getClientConfigurationUrl(a,b,c){let d="https://sdk-config.".concat(c||"kameleoon.eu","/");return b?d+a+_requester.UrlFirstParameter.Environment+b:d+a}static simulateSuccessRequest(a,b){switch(a){case _requester.RequestType.Tracking:return new Promise(a=>{a({status:204,json:()=>new Promise(a=>a(null)),text:()=>new Promise(a=>a("")),ok:!0})});case _requester.RequestType.Configuration:case _requester.RequestType.RemoteData:return new Promise(a=>{a({status:200,json:()=>new Promise(a=>a(b)),text:()=>new Promise(a=>a("")),ok:!0})});default:(0,_kameleoonError.exhaustCheck)(a)}}static getCookieValue(a,b){const c=a.split("; "),d=c.find(a=>{const[c,d]=a.split("=");return c===b&&""!==d});return d?d.split("=")[1]:null}}exports.KameleoonUtils=KameleoonUtils;
//# sourceMappingURL=kameleoonUtils.js.map

@@ -1,2 +0,2 @@

"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Requester=void 0;var _tsRes=require("ts-res"),_kameleoonError=require("../kameleoonError"),_utilities=require("../utilities"),_constants=require("./constants"),_types=require("./types"),_urlProvider=require("./urlProvider");function ownKeys(a,b){var c=Object.keys(a);if(Object.getOwnPropertySymbols){var d=Object.getOwnPropertySymbols(a);b&&(d=d.filter(function(b){return Object.getOwnPropertyDescriptor(a,b).enumerable})),c.push.apply(c,d)}return c}function _objectSpread(a){for(var b,c=1;c<arguments.length;c++)b=null==arguments[c]?{}:arguments[c],c%2?ownKeys(Object(b),!0).forEach(function(c){_defineProperty(a,c,b[c])}):Object.getOwnPropertyDescriptors?Object.defineProperties(a,Object.getOwnPropertyDescriptors(b)):ownKeys(Object(b)).forEach(function(c){Object.defineProperty(a,c,Object.getOwnPropertyDescriptor(b,c))});return a}function _defineProperty(a,b,c){return b=_toPropertyKey(b),b in a?Object.defineProperty(a,b,{value:c,enumerable:!0,configurable:!0,writable:!0}):a[b]=c,a}function _toPropertyKey(a){var b=_toPrimitive(a,"string");return"symbol"==typeof b?b:b+""}function _toPrimitive(a,b){if("object"!=typeof a||!a)return a;var c=a[Symbol.toPrimitive];if(void 0!==c){var d=c.call(a,b||"default");if("object"!=typeof d)return d;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===b?String:Number)(a)}class Requester{constructor(a){let{siteCode:b,environment:c,packageInfo:d,domain:e,externalRequester:f,requestTimeout:g,trackRetryDelay:h}=a;_defineProperty(this,"externalRequester",void 0),_defineProperty(this,"packageInfo",void 0),_defineProperty(this,"trackRetryDelay",void 0),_defineProperty(this,"timeout",void 0),this.externalRequester=f,this.trackRetryDelay=h,this.packageInfo=d,this.timeout=g,_urlProvider.UrlProvider.initialize({siteCode:b,domain:e,packageInfo:d,environment:c})}async getClientConfiguration(a){const b=_urlProvider.UrlProvider.getClientConfigurationUrl(a),c={[_constants.Header.SdkType]:this.packageInfo.type.toLowerCase(),[_constants.Header.SdkVersion]:this.packageInfo.version},d=_constants.NUMBER_OF_RETRIES+1;try{for(let a=0;a<d;a++){const d=await this.sendRequest({url:b,requestType:_types.RequestType.Configuration,retryCount:a,headers:c});if(d.ok){const a=await d.json();return(0,_tsRes.Ok)(a)}}return(0,_tsRes.Err)(new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.MaximumRetriesReached))}catch(_){return(0,_tsRes.Err)(new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.ClientConfiguration))}}async getRemoteData(a){const b=_urlProvider.UrlProvider.getRemoteDataUrl(a),c=new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.RemoteData);try{const a=await this.sendRequest({url:b,requestType:_types.RequestType.RemoteData,retryCount:0});if(!a.ok)return(0,_tsRes.Err)(c);const d=await a.json();return(0,_tsRes.Ok)(d)}catch(_){return(0,_tsRes.Err)(c)}}async getVisitorData(a){let{visitorCode:b,filters:c,isMappingIdentifier:d}=a;const e=_urlProvider.UrlProvider.getVisitorDataUrl({visitorCode:b,filters:c,isMappingIdentifier:d}),f=new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.RemoteData);try{const a=await this.sendRequest({url:e,requestType:_types.RequestType.RemoteData,retryCount:0});if(!a.ok)return(0,_tsRes.Err)(f);const b=await a.json();return(0,_tsRes.Ok)(b)}catch(_){return(0,_tsRes.Err)(f)}}async trackExperiment(a){let{visitorCode:b,dataUrl:c,variationDataUrl:d,userAgent:e,isUnallocated:f}=a;const g=_urlProvider.UrlProvider.getTrackingUrl(b),h=c?"":_constants.UrlEventType.Activity+_constants.UrlParameter.Nonce+_utilities.Utilities.getNonce(),i=f?h:d,j=i?c+"\n"+i:c,k=e?{[_constants.Header.UserAgent]:e}:void 0;try{const a=await this.track({url:g,headers:k,requestType:_types.RequestType.Tracking,body:j});return(0,_tsRes.Ok)(a)}catch(_){return(0,_tsRes.Err)()}}async trackData(a){let{visitorCode:b,body:c,userAgent:d,isMappingIdentifier:e}=a;const f=_urlProvider.UrlProvider.getTrackingUrl(b,e),g=c||_constants.UrlEventType.Activity+_constants.UrlParameter.Nonce+_utilities.Utilities.getNonce(),h=d?{[_constants.Header.UserAgent]:d}:void 0;try{const a=await this.track({url:f,requestType:_types.RequestType.Tracking,headers:h,body:g});return(0,_tsRes.Ok)(a)}catch(_){return(0,_tsRes.Err)()}}async track(a){const b=_constants.NUMBER_OF_RETRIES+1;for(let c=0;c<b;c++){const b=await this.sendRequest(_objectSpread(_objectSpread({},a),{},{retryCount:c}));if(b.ok)return!0;await new Promise(a=>setTimeout(a,this.trackRetryDelay))}return!1}async sendRequest(a){let{requestType:b,url:c,retryCount:d,headers:e,body:f}=a;const g=new AbortController,h=setTimeout(()=>g.abort(),this.timeout);let i;switch(b){case _types.RequestType.RemoteData:case _types.RequestType.Configuration:i={headers:e,signal:g.signal,method:_types.HttpMethod.Get};break;case _types.RequestType.Tracking:if(!f)throw new Error("Internal Error: Tracking request should always contain body");i={method:_types.HttpMethod.Post,headers:e,signal:g.signal,body:f}}const j=_objectSpread(_objectSpread({},i),{},{headers:e,signal:g.signal}),k=await this.externalRequester.sendRequest({url:c,retryCount:d,requestType:b,parameters:j});return clearTimeout(h),k}}exports.Requester=Requester;
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Requester=void 0;var _tsRes=require("ts-res"),_kameleoonError=require("../kameleoonError"),_utilities=require("../utilities"),_constants=require("./constants"),_types=require("./types"),_urlProvider=require("./urlProvider");function ownKeys(a,b){var c=Object.keys(a);if(Object.getOwnPropertySymbols){var d=Object.getOwnPropertySymbols(a);b&&(d=d.filter(function(b){return Object.getOwnPropertyDescriptor(a,b).enumerable})),c.push.apply(c,d)}return c}function _objectSpread(a){for(var b,c=1;c<arguments.length;c++)b=null==arguments[c]?{}:arguments[c],c%2?ownKeys(Object(b),!0).forEach(function(c){_defineProperty(a,c,b[c])}):Object.getOwnPropertyDescriptors?Object.defineProperties(a,Object.getOwnPropertyDescriptors(b)):ownKeys(Object(b)).forEach(function(c){Object.defineProperty(a,c,Object.getOwnPropertyDescriptor(b,c))});return a}function _defineProperty(a,b,c){return b=_toPropertyKey(b),b in a?Object.defineProperty(a,b,{value:c,enumerable:!0,configurable:!0,writable:!0}):a[b]=c,a}function _toPropertyKey(a){var b=_toPrimitive(a,"string");return"symbol"==typeof b?b:b+""}function _toPrimitive(a,b){if("object"!=typeof a||!a)return a;var c=a[Symbol.toPrimitive];if(void 0!==c){var d=c.call(a,b||"default");if("object"!=typeof d)return d;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===b?String:Number)(a)}class Requester{constructor(a){let{siteCode:b,environment:c,packageInfo:d,domain:e,externalRequester:f,requestTimeout:g,trackRetryDelay:h}=a;_defineProperty(this,"externalRequester",void 0),_defineProperty(this,"packageInfo",void 0),_defineProperty(this,"trackRetryDelay",void 0),_defineProperty(this,"timeout",void 0),this.externalRequester=f,this.trackRetryDelay=h,this.packageInfo=d,this.timeout=g,_urlProvider.UrlProvider.initialize({siteCode:b,domain:e,packageInfo:d,environment:c})}async getClientConfiguration(a){const b=_urlProvider.UrlProvider.getClientConfigurationUrl(a),c={[_constants.Header.SdkType]:this.packageInfo.type.toLowerCase(),[_constants.Header.SdkVersion]:this.packageInfo.version},d=_constants.NUMBER_OF_RETRIES+1;try{let a={message:""};for(let e=0;e<d;e++){const d=await this.sendRequest({url:b,requestType:_types.RequestType.Configuration,retryCount:e,headers:c});if(d.ok){const a=await d.json();return(0,_tsRes.Ok)(a)}if(e===_constants.NUMBER_OF_RETRIES&&d.text){const b=await d.text();a=JSON.parse(b)}}return(0,_tsRes.Err)(new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.MaximumRetriesReached,a.message))}catch(a){return(0,_tsRes.Err)(new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.ClientConfiguration,a))}}async getRemoteData(a){const b=_urlProvider.UrlProvider.getRemoteDataUrl(a);try{const a=await this.sendRequest({url:b,requestType:_types.RequestType.RemoteData,retryCount:0});if(!a.ok){if(a.text){var c;const b=await a.text(),d=null===(c=JSON.parse(b))||void 0===c?void 0:c.message;return(0,_tsRes.Err)(new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.RemoteData,d))}return(0,_tsRes.Err)(new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.RemoteData,"Unknown Reason - no `text()` was found for a response"))}const d=await a.json();return(0,_tsRes.Ok)(d)}catch(a){return(0,_tsRes.Err)(new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.RemoteData,a))}}async getVisitorData(a){let{visitorCode:b,filters:c,isMappingIdentifier:d}=a;const e=_urlProvider.UrlProvider.getVisitorDataUrl({visitorCode:b,filters:c,isMappingIdentifier:d});try{const a=await this.sendRequest({url:e,requestType:_types.RequestType.RemoteData,retryCount:0});if(!a.ok){if(a.text){var f;const b=await a.text(),c=null===(f=JSON.parse(b))||void 0===f?void 0:f.message;return(0,_tsRes.Err)(new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.RemoteData,c))}return(0,_tsRes.Err)(new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.RemoteData,"Unknown Reason - no 'text()' was found for a response"))}const b=await a.json();return(0,_tsRes.Ok)(b)}catch(a){return(0,_tsRes.Err)(new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.RemoteData,a))}}async trackExperiment(a){let{visitorCode:b,dataUrl:c,variationDataUrl:d,userAgent:e,isUnallocated:f}=a;const g=_urlProvider.UrlProvider.getTrackingUrl(b),h=c?"":_constants.UrlEventType.Activity+_constants.UrlParameter.Nonce+_utilities.Utilities.getNonce(),i=f?h:d,j=i?c+"\n"+i:c,k=e?{[_constants.Header.UserAgent]:e}:void 0;try{const a=await this.track({url:g,headers:k,requestType:_types.RequestType.Tracking,body:j});return(0,_tsRes.Ok)(a)}catch(_){return(0,_tsRes.Err)()}}async trackData(a){let{visitorCode:b,body:c,userAgent:d,isMappingIdentifier:e}=a;const f=_urlProvider.UrlProvider.getTrackingUrl(b,e),g=c||_constants.UrlEventType.Activity+_constants.UrlParameter.Nonce+_utilities.Utilities.getNonce(),h=d?{[_constants.Header.UserAgent]:d}:void 0;try{const a=await this.track({url:f,requestType:_types.RequestType.Tracking,headers:h,body:g});return(0,_tsRes.Ok)(a)}catch(_){return(0,_tsRes.Err)()}}async track(a){const b=_constants.NUMBER_OF_RETRIES+1;for(let c=0;c<b;c++){const b=await this.sendRequest(_objectSpread(_objectSpread({},a),{},{retryCount:c}));if(b.ok)return!0;await new Promise(a=>setTimeout(a,this.trackRetryDelay))}return!1}async sendRequest(a){let{requestType:b,url:c,retryCount:d,headers:e,body:f}=a;const g=new AbortController,h=setTimeout(()=>g.abort(),this.timeout);let i;switch(b){case _types.RequestType.RemoteData:case _types.RequestType.Configuration:i={headers:e,signal:g.signal,method:_types.HttpMethod.Get};break;case _types.RequestType.Tracking:if(!f)throw new Error("Internal Error: Tracking request should always contain body");i={method:_types.HttpMethod.Post,headers:e,signal:g.signal,body:f}}const j=_objectSpread(_objectSpread({},i),{},{headers:e,signal:g.signal}),k=await this.externalRequester.sendRequest({url:c,retryCount:d,requestType:b,parameters:j});return clearTimeout(h),k}}exports.Requester=Requester;
//# sourceMappingURL=requester.js.map

@@ -245,2 +245,3 @@ import { JSONType } from '../clientConfiguration';

* @property {() => Promise<JSONType>} json - a method to parse the response to JSON
* @property {() => Promise<string>| undefined} text - a method to parse the response to text
* @property {boolean} ok - a boolean value that indicates if the response is ok

@@ -251,2 +252,3 @@ * */

json: () => Promise<JSONType>;
text?: () => Promise<string>;
ok: boolean;

@@ -253,0 +255,0 @@ };

@@ -1,2 +0,2 @@

"use strict";const _excluded=["timestamp","isExperiment"];Object.defineProperty(exports,"__esModule",{value:!0}),exports.Utilities=void 0;var _tsRes=require("ts-res"),_kameleoonError=require("../kameleoonError"),_types=require("../types"),_kameleoonData=require("../kameleoonData"),_constants=require("../constants"),_requester=require("../requester"),_targeting=require("../targeting"),_visitProcessor=require("../kameleoonData/visitProcessor"),_constants2=require("./constants"),_types2=require("./types");function _objectWithoutProperties(a,b){if(null==a)return{};var c,d,e=_objectWithoutPropertiesLoose(a,b);if(Object.getOwnPropertySymbols){var f=Object.getOwnPropertySymbols(a);for(d=0;d<f.length;d++)c=f[d],0<=b.indexOf(c)||Object.prototype.propertyIsEnumerable.call(a,c)&&(e[c]=a[c])}return e}function _objectWithoutPropertiesLoose(a,b){if(null==a)return{};var c,d,e={},f=Object.keys(a);for(d=0;d<f.length;d++)c=f[d],0<=b.indexOf(c)||(e[c]=a[c]);return e}function ownKeys(a,b){var c=Object.keys(a);if(Object.getOwnPropertySymbols){var d=Object.getOwnPropertySymbols(a);b&&(d=d.filter(function(b){return Object.getOwnPropertyDescriptor(a,b).enumerable})),c.push.apply(c,d)}return c}function _objectSpread(a){for(var b,c=1;c<arguments.length;c++)b=null==arguments[c]?{}:arguments[c],c%2?ownKeys(Object(b),!0).forEach(function(c){_defineProperty(a,c,b[c])}):Object.getOwnPropertyDescriptors?Object.defineProperties(a,Object.getOwnPropertyDescriptors(b)):ownKeys(Object(b)).forEach(function(c){Object.defineProperty(a,c,Object.getOwnPropertyDescriptor(b,c))});return a}function _defineProperty(a,b,c){return b=_toPropertyKey(b),b in a?Object.defineProperty(a,b,{value:c,enumerable:!0,configurable:!0,writable:!0}):a[b]=c,a}function _toPropertyKey(a){var b=_toPrimitive(a,"string");return"symbol"==typeof b?b:b+""}function _toPrimitive(a,b){if("object"!=typeof a||!a)return a;var c=a[Symbol.toPrimitive];if(void 0!==c){var d=c.call(a,b||"default");if("object"!=typeof d)return d;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===b?String:Number)(a)}class Utilities{static checkTargeting(a){let{segment:b,visitorCode:c,targetingData:d,experimentId:e,variationConfiguration:f,clientConfiguration:g,packageInfo:h,dataManager:i}=a;if(!b||!b.conditionsData.firstLevel.length)return(0,_tsRes.Ok)(!0);if(!f)return(0,_tsRes.Err)(new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization));let j={};const k=f.getStoredVariations(c);k.ok&&(j=k.data);const l=i.getTree(b);let m,n,o;l.hasTargetingType(_targeting.TargetingType.SEGMENT)&&(m=i.trees,n=g.segments),l.hasTargetingType(_targeting.TargetingType.TARGET_FEATURE_FLAG)&&(o=g.ruleMap);const p=l.evaluate({variationData:j,sdkInfo:h,segments:n,ruleMap:o,trees:m,targetingData:d,experimentId:e,visitorCode:c});return p}static validateVisitorCode(a){return 0===a.length?(0,_tsRes.Err)(new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.VisitorCodeEmpty)):a.length>_constants2.VISITOR_CODE_MAX_LENGTH?(0,_tsRes.Err)(new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.VisitorCodeMaxLength)):(0,_tsRes.Ok)()}static getDataUrl(a){function b(a){if(!a.url)return;const b=a.data.type===_kameleoonData.KameleoonData.Conversion;if(e||b){const c=b?"":_requester.UrlParameter.Nonce+Utilities.getNonce();g.push(a.url+c+"\n")}}let{visitorCode:c,dataManager:d,isConsentProvided:e}=a;const f=d.getUnsentData(c),g=[];if(!f||!f.size)return"";for(const c of f.values())Array.isArray(c)?c.forEach(a=>b(a)):b(c);return g.join("")}static getVariationDataUrlAndSentExperimentIds(a){let{visitorCode:b,isConsentProvided:c,variationConfiguration:d}=a;const e=[],f=new Set,g=d.getUnsentData(b);g.ok&&g.data.length&&g.data.forEach(a=>{(a.isTargetedRule||c)&&(e.push(_requester.UrlEventType.Experiment+_requester.UrlParameter.Id+a.experimentId+_requester.UrlParameter.VariationId+a.variationId+_requester.UrlParameter.Nonce+Utilities.getNonce()+"\n"),f.add(a.experimentId+""))});const h=e.join(""),i=Array.from(f);return[h,i]}static async trackFeatureExperiment(a){let{featureFlagVariation:b,dataManager:c,visitorCode:d,requester:e,isOfflineModeOn:f,isConsentProvided:g,offlineTrackingStorage:h,variationConfiguration:i}=a;const{variationId:j,rule:k}=b,l=this.getUserAgent(d,c),m=this.getDataUrl({visitorCode:d,dataManager:c,isConsentProvided:g}),n=k?k.experimentId:0,[o,p]=this.getVariationDataUrlAndSentExperimentIds({visitorCode:d,isConsentProvided:g,variationConfiguration:i});if(!g&&!m&&!k)return;const q={visitorCode:d,dataUrl:m,variationDataUrl:o,experimentId:n,variationId:j||0,userAgent:l,isUnallocated:null===j},r=await e.trackExperiment(q);r.ok&&(g?c.clearUnsentData(d):c.clearUnsentDataByKey(d,_kameleoonData.KameleoonData.Conversion),p.forEach(a=>{i.markUnsentDataAsSent(d,a)})),!r.ok&&f&&this.addItemToOfflineTracking({item:q,storage:h,isExperiment:!0})}static convertTimeUnit(a,b){const c={[_types2.TimeUnit.Minute]:_types.Milliseconds.Minute,[_types2.TimeUnit.Hour]:_types.Milliseconds.Hour,[_types2.TimeUnit.Day]:_types.Milliseconds.Day,[_types2.TimeUnit.Week]:_types.Milliseconds.Week,[_types2.TimeUnit.Month]:_types.Milliseconds.Month};return a/c[b]}static parseFeatureVariable(a){const{key:b,type:c,value:d}=a;switch(c){case _types.VariableType.BOOLEAN:return(0,_tsRes.Ok)({key:b,type:c,value:!!d});case _types.VariableType.STRING:return(0,_tsRes.Ok)({key:b,type:c,value:d+""});case _types.VariableType.NUMBER:const e=+d;return Number.isNaN(e)?(0,_tsRes.Err)(new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.NumberParse,d+"")):(0,_tsRes.Ok)({key:b,type:c,value:e});case _types.VariableType.JSON:try{const d=JSON.parse(a.value+"");return(0,_tsRes.Ok)({key:b,type:c,value:d})}catch(a){return(0,_tsRes.Err)(new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.JSONParse,a))}default:(0,_kameleoonError.exhaustCheck)(c)}}static parseVisitorData(a){let{data:b,filters:c,visitorCode:d,dataManager:e,variationConfiguration:f}=a;const g=new _visitProcessor.VisitProcessor(c,e),{currentVisit:h,previousVisits:i,kcs:j}=b;let k=[];if(h&&k.push(h),i&&k.push(...i),!k.length)return{visitorData:[],storageVisitorData:[]};k.forEach(a=>{g.processVisit(a)}),g.processKcs(j),g.processMultipleDataTypes();const{visitorData:l,storageVisitorData:m,visitsData:n,experimentData:o}=g.data;return f.updateStoredVariations(d,o),{visitorData:l,storageVisitorData:m,visitsData:n}}static parseRegExp(a){if("/"===a[0]){const[_,b,c]=a.split("/");return new RegExp(b,c)}return new RegExp(a)}static getUserAgent(a,b){const c=b.getTargetingData(a);if(c){const a=c[_kameleoonData.KameleoonData.UserAgent];if(a)return a.value}}static isCustomData(a){return a.data.type===_kameleoonData.KameleoonData.CustomData}static insertInOrderedListMutably(a){let{list:b,element:c,order:d}=a;if(!b.includes(c)){const a=b.findIndex(a=>d===_types2.Order.Ascending?a>=c:a<=c);-1===a?b.push(c):b.splice(a,0,c)}}static updateCache(a){let{cacheManager:b,visitorCode:c,experimentId:d,variationId:e}=a;const f=b.getAliveItem(c),g=f?_objectSpread({},f):{};g[d]={variationId:e,expirationTime:Date.now()+_constants.CACHE_ITEM_LIFETIME*_types.Milliseconds.Second},b.add({key:c,data:g,lifetime:_constants.CACHE_ITEM_LIFETIME})}static getTrackingCode(a,b){let c="window.kameleoonQueue=window.kameleoonQueue||[];";const d=a.getAliveItem(b);if(!d)return c;const e={};return Object.entries(d).forEach(a=>{let[b,{variationId:d,expirationTime:f}]=a;f>Date.now()&&(c+="window.kameleoonQueue.push(['Experiments.assignVariation',".concat(b,",").concat(d,"]);"),c+="window.kameleoonQueue.push(['Experiments.trigger',".concat(b,",true]);"),e[+b]={variationId:d,expirationTime:f})}),a.add({key:b,data:e,lifetime:_constants.CACHE_ITEM_LIFETIME}),c}static async trackData(a){let{visitorCode:b,dataManager:c,requester:d,isOfflineModeOn:e,offlineTrackingStorage:f,isConsentProvided:g,isMappingIdentifier:h}=a;const i=this.getDataUrl({visitorCode:b,dataManager:c,isConsentProvided:g});if(!g&&!i)return;const j=this.getUserAgent(b,c),k={visitorCode:b,body:i,userAgent:j,isMappingIdentifier:h},l=await d.trackData(k),m=()=>g?c.clearUnsentData(b):c.clearUnsentDataByKey(b,_kameleoonData.KameleoonData.Conversion);l.ok&&m(),!l.ok&&e&&this.addItemToOfflineTracking({item:k,storage:f,isExperiment:!1,onSuccess:m}),await this.sendOfflineTracking({requester:d,storage:f})}static getNonce(){let a="";for(let b=0;b<_constants2.NONCE_LENGTH;b++){const b=Math.floor(Math.random()*_constants2.NONCE_LENGTH);a+=_constants2.HEX_CHARACTERS.charAt(b)}return a}static compareSemVer(a){let{version:b,compareVersion:c,operator:d}=a;const e=this.validateVersion(b),f=this.validateVersion(c);if(!e.ok)return(0,_tsRes.Err)(e.error);if(!f.ok)return(0,_tsRes.Err)(f.error);const[g,h,i]=e.data,[j,k,l]=f.data,[m,n,o]=[g===j,h===k,i===l];switch(d){case _targeting.VersionMatchType.EQUAL:return(0,_tsRes.Ok)(m&&n&&o);case _targeting.VersionMatchType.GREATER:return(0,_tsRes.Ok)(g>j||m&&h>k||m&&n&&i>l);case _targeting.VersionMatchType.LOWER:return(0,_tsRes.Ok)(g<j||m&&h<k||m&&n&&i<l);default:(0,_kameleoonError.exhaustCheck)(d)}}static generateRandomString(a){const b="abcdefghijklmnopqrstuvwxyz0123456789",c=[];if(0>a)return"";for(let d=0;d<a;d++)c.push(b[Math.floor(Math.random()*b.length)]);return c.join("")}static async sendOfflineTracking(a){let{requester:b,storage:c}=a;const d=c.read();if(d.ok&&d.data.requestParameters){const{requestParameters:a}=d.data,e=[];for(const c of a){const{timestamp:a,isExperiment:d}=c,f=_objectWithoutProperties(c,_excluded);let g;g=d?await b.trackExperiment(f):await b.trackData(f),g.ok&&g.data&&e.push(a)}this.deleteFromOfflineTracking({storage:c,timestamps:e})}}static addItemToOfflineTracking(a){let{item:b,isExperiment:c,storage:d,onSuccess:e}=a;const f=d.read(),g=f.ok?f.data:{},{requestParameters:h}=g,i=_objectSpread(_objectSpread({},b),{},{timestamp:new Date().getTime(),isExperiment:c}),j=h?[...h,i]:[i],k=d.write({requestParameters:j});k.ok&&e&&e()}static deleteFromOfflineTracking(a){let{timestamps:b,storage:c}=a;const d=c.read();if(d.ok){const{requestParameters:a}=d.data,e=null===a||void 0===a?void 0:a.filter(a=>!b.includes(a.timestamp));c.write({requestParameters:e})}}static validateVersion(a){const b=a.split(".").map(a=>parseInt(a,10));for(;3>b.length;)b.push(0);return b.some(a=>isNaN(a))?(0,_tsRes.Err)(new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.SemanticVersionParse,a)):(0,_tsRes.Ok)(b.slice(0,3))}}exports.Utilities=Utilities;
"use strict";const _excluded=["timestamp","isExperiment"];Object.defineProperty(exports,"__esModule",{value:!0}),exports.Utilities=void 0;var _tsRes=require("ts-res"),_kameleoonError=require("../kameleoonError"),_types=require("../types"),_kameleoonData=require("../kameleoonData"),_constants=require("../constants"),_requester=require("../requester"),_targeting=require("../targeting"),_visitProcessor=require("../kameleoonData/visitProcessor"),_constants2=require("./constants"),_types2=require("./types");function _objectWithoutProperties(a,b){if(null==a)return{};var c,d,e=_objectWithoutPropertiesLoose(a,b);if(Object.getOwnPropertySymbols){var f=Object.getOwnPropertySymbols(a);for(d=0;d<f.length;d++)c=f[d],0<=b.indexOf(c)||Object.prototype.propertyIsEnumerable.call(a,c)&&(e[c]=a[c])}return e}function _objectWithoutPropertiesLoose(a,b){if(null==a)return{};var c,d,e={},f=Object.keys(a);for(d=0;d<f.length;d++)c=f[d],0<=b.indexOf(c)||(e[c]=a[c]);return e}function ownKeys(a,b){var c=Object.keys(a);if(Object.getOwnPropertySymbols){var d=Object.getOwnPropertySymbols(a);b&&(d=d.filter(function(b){return Object.getOwnPropertyDescriptor(a,b).enumerable})),c.push.apply(c,d)}return c}function _objectSpread(a){for(var b,c=1;c<arguments.length;c++)b=null==arguments[c]?{}:arguments[c],c%2?ownKeys(Object(b),!0).forEach(function(c){_defineProperty(a,c,b[c])}):Object.getOwnPropertyDescriptors?Object.defineProperties(a,Object.getOwnPropertyDescriptors(b)):ownKeys(Object(b)).forEach(function(c){Object.defineProperty(a,c,Object.getOwnPropertyDescriptor(b,c))});return a}function _defineProperty(a,b,c){return b=_toPropertyKey(b),b in a?Object.defineProperty(a,b,{value:c,enumerable:!0,configurable:!0,writable:!0}):a[b]=c,a}function _toPropertyKey(a){var b=_toPrimitive(a,"string");return"symbol"==typeof b?b:b+""}function _toPrimitive(a,b){if("object"!=typeof a||!a)return a;var c=a[Symbol.toPrimitive];if(void 0!==c){var d=c.call(a,b||"default");if("object"!=typeof d)return d;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===b?String:Number)(a)}class Utilities{static checkTargeting(a){let{segment:b,visitorCode:c,targetingData:d,experimentId:e,variationConfiguration:f,clientConfiguration:g,packageInfo:h,dataManager:i}=a;if(!b||!b.conditionsData.firstLevel.length)return(0,_tsRes.Ok)(!0);if(!f)return(0,_tsRes.Err)(new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization));let j={};const k=f.getStoredVariations(c);k.ok&&(j=k.data);const l=i.getTree(b);let m,n,o;l.hasTargetingType(_targeting.TargetingType.SEGMENT)&&(m=i.trees,n=g.segments),l.hasTargetingType(_targeting.TargetingType.TARGET_FEATURE_FLAG)&&(o=g.ruleMap);const p=l.evaluate({variationData:j,sdkInfo:h,segments:n,ruleMap:o,trees:m,targetingData:d,experimentId:e,visitorCode:c});return p}static validateVisitorCode(a){return 0===a.length?(0,_tsRes.Err)(new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.VisitorCodeEmpty)):a.length>_constants2.VISITOR_CODE_MAX_LENGTH?(0,_tsRes.Err)(new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.VisitorCodeMaxLength)):(0,_tsRes.Ok)()}static getDataUrl(a){function b(a){if(!a.url)return;const b=a.data.type===_kameleoonData.KameleoonData.Conversion;if(e||b){const c=b?"":_requester.UrlParameter.Nonce+Utilities.getNonce();g.push(a.url+c+"\n")}}let{visitorCode:c,dataManager:d,isConsentProvided:e}=a;const f=d.getUnsentData(c),g=[];if(!f||!f.size)return"";for(const c of f.values())Array.isArray(c)?c.forEach(a=>b(a)):b(c);return g.join("")}static getVariationDataUrlAndSentExperimentIds(a){let{visitorCode:b,isConsentProvided:c,variationConfiguration:d}=a;const e=[],f=new Set,g=d.getUnsentData(b);g.ok&&g.data.length&&g.data.forEach(a=>{(a.isTargetedRule||c)&&(e.push(_requester.UrlEventType.Experiment+_requester.UrlParameter.Id+a.experimentId+_requester.UrlParameter.VariationId+a.variationId+_requester.UrlParameter.Nonce+Utilities.getNonce()+"\n"),f.add(a.experimentId+""))});const h=e.join(""),i=Array.from(f);return[h,i]}static async trackFeatureExperiment(a){let{featureFlagVariation:b,dataManager:c,visitorCode:d,requester:e,isOfflineModeOn:f,isConsentProvided:g,offlineTrackingStorage:h,variationConfiguration:i}=a;const{variationId:j,rule:k}=b,l=this.getUserAgent(d,c),m=this.getDataUrl({visitorCode:d,dataManager:c,isConsentProvided:g}),n=k?k.experimentId:0,[o,p]=this.getVariationDataUrlAndSentExperimentIds({visitorCode:d,isConsentProvided:g,variationConfiguration:i});if(!g&&!m&&!k)return;const q={visitorCode:d,dataUrl:m,variationDataUrl:o,experimentId:n,variationId:j||0,userAgent:l,isUnallocated:null===j},r=await e.trackExperiment(q);r.ok&&(g?c.clearUnsentData(d):c.clearUnsentDataByKey(d,_kameleoonData.KameleoonData.Conversion),p.forEach(a=>{i.markUnsentDataAsSent(d,a)})),!r.ok&&f&&this.addItemToOfflineTracking({item:q,storage:h,isExperiment:!0})}static convertTimeUnit(a,b){const c={[_types2.TimeUnit.Minute]:_types.Milliseconds.Minute,[_types2.TimeUnit.Hour]:_types.Milliseconds.Hour,[_types2.TimeUnit.Day]:_types.Milliseconds.Day,[_types2.TimeUnit.Week]:_types.Milliseconds.Week,[_types2.TimeUnit.Month]:_types.Milliseconds.Month};return a/c[b]}static parseFeatureVariable(a){const{key:b,type:c,value:d}=a;switch(c){case _types.VariableType.BOOLEAN:return(0,_tsRes.Ok)({key:b,type:c,value:!!d});case _types.VariableType.STRING:return(0,_tsRes.Ok)({key:b,type:c,value:d+""});case _types.VariableType.NUMBER:const e=+d;return Number.isNaN(e)?(0,_tsRes.Err)(new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.NumberParse,d+"")):(0,_tsRes.Ok)({key:b,type:c,value:e});case _types.VariableType.JSON:try{const d=JSON.parse(a.value+"");return(0,_tsRes.Ok)({key:b,type:c,value:d})}catch(a){return(0,_tsRes.Err)(new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.JSONParse,a))}default:(0,_kameleoonError.exhaustCheck)(c)}}static parseVisitorData(a){let{data:b,filters:c,visitorCode:d,dataManager:e,variationConfiguration:f}=a;const g=new _visitProcessor.VisitProcessor(c,e),{currentVisit:h,previousVisits:i,kcs:j}=b;let k=[];if(h&&k.push(h),i&&k.push(...i),!k.length)return{visitorData:[],storageVisitorData:[]};k.forEach(a=>{g.processVisit(a)}),g.processKcs(j),g.processMultipleDataTypes();const{visitorData:l,storageVisitorData:m,visitsData:n,experimentData:o}=g.data;return f.updateStoredVariations(d,o),{visitorData:l,storageVisitorData:m,visitsData:n}}static parseRegExp(a){if("/"===a[0]){const[_,b,c]=a.split("/");return new RegExp(b,c)}return new RegExp(a)}static getUserAgent(a,b){const c=b.getTargetingData(a);if(c){const a=c[_kameleoonData.KameleoonData.UserAgent];if(a)return a.value}}static isCustomData(a){return a.data.type===_kameleoonData.KameleoonData.CustomData}static insertInOrderedListMutably(a){let{list:b,element:c,order:d}=a;if(!b.includes(c)){const a=b.findIndex(a=>d===_types2.Order.Ascending?a>=c:a<=c);-1===a?b.push(c):b.splice(a,0,c)}}static updateCache(a){let{cacheManager:b,visitorCode:c,experimentId:d,variationId:e}=a;const f=b.getAliveItem(c),g=f?_objectSpread({},f):{};g[d]={variationId:e,expirationTime:Date.now()+_constants.CACHE_ITEM_LIFETIME*_types.Milliseconds.Second},b.add({key:c,data:g,lifetime:_constants.CACHE_ITEM_LIFETIME})}static getTrackingCode(a,b){let c="window.kameleoonQueue=window.kameleoonQueue||[];";const d=a.getAliveItem(b);if(!d)return c;const e={};return Object.entries(d).forEach(a=>{let[b,{variationId:d,expirationTime:f}]=a;f>Date.now()&&(c+="window.kameleoonQueue.push(['Experiments.assignVariation',".concat(b,",").concat(d,",true]);"),c+="window.kameleoonQueue.push(['Experiments.trigger',".concat(b,",true]);"),e[+b]={variationId:d,expirationTime:f})}),a.add({key:b,data:e,lifetime:_constants.CACHE_ITEM_LIFETIME}),c}static async trackData(a){let{visitorCode:b,dataManager:c,requester:d,isOfflineModeOn:e,offlineTrackingStorage:f,isConsentProvided:g,isMappingIdentifier:h}=a;const i=this.getDataUrl({visitorCode:b,dataManager:c,isConsentProvided:g});if(!g&&!i)return;const j=this.getUserAgent(b,c),k={visitorCode:b,body:i,userAgent:j,isMappingIdentifier:h},l=await d.trackData(k),m=()=>g?c.clearUnsentData(b):c.clearUnsentDataByKey(b,_kameleoonData.KameleoonData.Conversion);l.ok&&m(),!l.ok&&e&&this.addItemToOfflineTracking({item:k,storage:f,isExperiment:!1,onSuccess:m}),await this.sendOfflineTracking({requester:d,storage:f})}static getNonce(){let a="";for(let b=0;b<_constants2.NONCE_LENGTH;b++){const b=Math.floor(Math.random()*_constants2.NONCE_LENGTH);a+=_constants2.HEX_CHARACTERS.charAt(b)}return a}static compareSemVer(a){let{version:b,compareVersion:c,operator:d}=a;const e=this.validateVersion(b),f=this.validateVersion(c);if(!e.ok)return(0,_tsRes.Err)(e.error);if(!f.ok)return(0,_tsRes.Err)(f.error);const[g,h,i]=e.data,[j,k,l]=f.data,[m,n,o]=[g===j,h===k,i===l];switch(d){case _targeting.VersionMatchType.EQUAL:return(0,_tsRes.Ok)(m&&n&&o);case _targeting.VersionMatchType.GREATER:return(0,_tsRes.Ok)(g>j||m&&h>k||m&&n&&i>l);case _targeting.VersionMatchType.LOWER:return(0,_tsRes.Ok)(g<j||m&&h<k||m&&n&&i<l);default:(0,_kameleoonError.exhaustCheck)(d)}}static generateRandomString(a){const b="abcdefghijklmnopqrstuvwxyz0123456789",c=[];if(0>a)return"";for(let d=0;d<a;d++)c.push(b[Math.floor(Math.random()*b.length)]);return c.join("")}static async sendOfflineTracking(a){let{requester:b,storage:c}=a;const d=c.read();if(d.ok&&d.data.requestParameters){const{requestParameters:a}=d.data,e=[];for(const c of a){const{timestamp:a,isExperiment:d}=c,f=_objectWithoutProperties(c,_excluded);let g;g=d?await b.trackExperiment(f):await b.trackData(f),g.ok&&g.data&&e.push(a)}this.deleteFromOfflineTracking({storage:c,timestamps:e})}}static addItemToOfflineTracking(a){let{item:b,isExperiment:c,storage:d,onSuccess:e}=a;const f=d.read(),g=f.ok?f.data:{},{requestParameters:h}=g,i=_objectSpread(_objectSpread({},b),{},{timestamp:new Date().getTime(),isExperiment:c}),j=h?[...h,i]:[i],k=d.write({requestParameters:j});k.ok&&e&&e()}static deleteFromOfflineTracking(a){let{timestamps:b,storage:c}=a;const d=c.read();if(d.ok){const{requestParameters:a}=d.data,e=null===a||void 0===a?void 0:a.filter(a=>!b.includes(a.timestamp));c.write({requestParameters:e})}}static validateVersion(a){const b=a.split(".").map(a=>parseInt(a,10));for(;3>b.length;)b.push(0);return b.some(a=>isNaN(a))?(0,_tsRes.Err)(new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.SemanticVersionParse,a)):(0,_tsRes.Ok)(b.slice(0,3))}}exports.Utilities=Utilities;
//# sourceMappingURL=utilities.js.map
{
"name": "@kameleoon/javascript-sdk-core",
"version": "4.4.0",
"version": "4.4.1",
"description": "Kameleoon JS SDK Core",

@@ -5,0 +5,0 @@ "main": "dist/index.js",

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc