@kameleoon/javascript-sdk-core 4.4.7 → 4.4.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +6 -0
- package/dist/clientConfiguration/clientConfiguration.d.ts +2 -1
- package/dist/clientConfiguration/clientConfiguration.js +1 -1
- package/dist/clientConfiguration/clientConfiguration.js.map +1 -1
- package/dist/clientConfiguration/types.d.ts +2 -0
- package/dist/clientConfiguration/types.js.map +1 -1
- package/dist/eventSource/eventSource.d.ts +2 -2
- package/dist/eventSource/eventSource.js +1 -1
- package/dist/eventSource/eventSource.js.map +1 -1
- package/dist/eventSource/types.d.ts +6 -0
- package/dist/eventSource/types.js.map +1 -1
- package/dist/kameleoonClient.d.ts +1 -1
- package/dist/kameleoonClient.js +1 -1
- package/dist/kameleoonClient.js.map +1 -1
- package/dist/requester/constants.d.ts +2 -1
- package/dist/requester/constants.js +1 -1
- package/dist/requester/constants.js.map +1 -1
- package/dist/requester/index.d.ts +3 -2
- package/dist/requester/index.js +1 -1
- package/dist/requester/index.js.map +1 -1
- package/dist/requester/requester.d.ts +2 -1
- package/dist/requester/requester.js +1 -1
- package/dist/requester/requester.js.map +1 -1
- package/dist/requester/types.d.ts +3 -4
- package/dist/requester/types.js.map +1 -1
- package/dist/requester/urlProvider.d.ts +26 -18
- package/dist/requester/urlProvider.js +1 -1
- package/dist/requester/urlProvider.js.map +1 -1
- package/dist/types.d.ts +10 -2
- package/dist/types.js.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -27,7 +27,8 @@ export declare class ClientConfiguration implements IClientConfiguration {
|
|
|
27
27
|
private dataManager;
|
|
28
28
|
private visitorCodeManager;
|
|
29
29
|
private eventManager;
|
|
30
|
-
|
|
30
|
+
private urlProvider;
|
|
31
|
+
constructor({ updateInterval, urlProvider, storage, requester, dataManager, externalClientConfiguration, offlineTrackingStorage, eventSource, externalVisitorCodeManager, eventManager, }: ClientConfigurationParametersType);
|
|
31
32
|
initialize(): Promise<Result<void, KameleoonError>>;
|
|
32
33
|
private cleanupHandlers;
|
|
33
34
|
private handleExternalUpdates;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.ClientConfiguration=void 0;var _tsRes=require("ts-res"),_constants=require("./constants"),_types=require("./types"),_utilities=require("../utilities"),_eventManager=require("../eventManager")
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.ClientConfiguration=void 0;var _tsRes=require("ts-res"),_constants=require("./constants"),_types=require("./types"),_utilities=require("../utilities"),_eventManager=require("../eventManager");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 ClientConfiguration{constructor(a){let{updateInterval:b,urlProvider:c,storage:d,requester:e,dataManager:f,externalClientConfiguration:g,offlineTrackingStorage:h,eventSource:i,externalVisitorCodeManager:j,eventManager:k}=a;_defineProperty(this,"updateConfigurationIntervalId",null),_defineProperty(this,"updateType",_types.UpdateType.Idle),_defineProperty(this,"configurationData",_constants.DEFAULT_CONFIGURATION_DATA),_defineProperty(this,"featureFlagsData",new Map),_defineProperty(this,"isTargetedDeliveryRule",null),_defineProperty(this,"segmentsData",null),_defineProperty(this,"updateInterval",void 0),_defineProperty(this,"lastUpdate",void 0),_defineProperty(this,"storage",void 0),_defineProperty(this,"offlineTrackingStorage",void 0),_defineProperty(this,"requester",void 0),_defineProperty(this,"eventSource",void 0),_defineProperty(this,"externalClientConfiguration",void 0),_defineProperty(this,"mappedRules",null),_defineProperty(this,"dataManager",void 0),_defineProperty(this,"visitorCodeManager",void 0),_defineProperty(this,"eventManager",void 0),_defineProperty(this,"urlProvider",void 0),this.urlProvider=c,this.requester=e,this.updateInterval=b,this.lastUpdate=new Date,this.storage=d,this.dataManager=f,this.eventManager=k,this.externalClientConfiguration=g,this.offlineTrackingStorage=h,this.visitorCodeManager=j,this.eventSource=i}async initialize(){this.readStorageData();const a=!!this.externalClientConfiguration,b=this.checkShouldUpdate(a);if(b){const a=await this.updateClientConfiguration();if(!a.ok)return a;const b=a.data;if(b)return(0,_tsRes.Ok)()}return a?(this.handleExternalUpdates(),(0,_tsRes.Ok)()):this.updateType!==_types.UpdateType.RealTime||this.eventSource.isOpen?(this.updateType===_types.UpdateType.Polling&&this.handlePollingUpdates(),(0,_tsRes.Ok)()):(this.updateType=_types.UpdateType.Idle,this.handleRealTimeUpdates(),(0,_tsRes.Ok)())}cleanupHandlers(){this.eventSource.isOpen&&this.eventSource.close(),this.updateConfigurationIntervalId&&clearInterval(this.updateConfigurationIntervalId)}handleExternalUpdates(){this.cleanupHandlers();const{customData:a,configuration:b,featureFlags:c}=this.externalClientConfiguration;this.configurationData={customData:a,configuration:b};for(const a of c)this.featureFlagsData.set(a.featureKey,a)}handleRealTimeUpdates(){this.cleanupHandlers();const a=a=>{this.updateClientConfiguration(a).then(b=>{b.ok&&this.eventManager.fireEvent(_eventManager.EventType.ConfigurationUpdate,{timestamp:a})})};this.eventSource.open(a)}handlePollingUpdates(){this.cleanupHandlers();try{this.updateConfigurationIntervalId=setInterval(this.updateClientConfiguration.bind(this),this.updateInterval)}catch(a){throw this.updateConfigurationIntervalId&&clearInterval(this.updateConfigurationIntervalId),a}}get featureFlags(){return this.featureFlagsData}get configuration(){return this.configurationData.configuration}get segments(){if(this.segmentsData)return this.segmentsData;const a=new Map;return this.featureFlagsData.forEach(b=>{b.rules.forEach(b=>{b.segment&&!a.has(b.segment.id)&&a.set(b.segment.id,b.segment)})}),this.segmentsData=a,a}get ruleMap(){var a;if(null!==(a=this.mappedRules)&&void 0!==a&&a.size)return this.mappedRules;const b=new Map;for(const a of this.featureFlags.values())for(const c of a.rules){const{id:d,experimentId:e,variationByExposition:f}=c,g=new Map;f.forEach(a=>{let{variationKey:b,variationId:c}=a;"number"==typeof c&&g.set(b,c)}),b.set(d,{featureId:a.id,experimentId:e,variations:g})}return this.mappedRules=b,b}get isConsentRequired(){return this.configuration.consentType===_types.ConsentType.Required}get hasAnyTargetedDeliveryRule(){if(null!==this.isTargetedDeliveryRule)return this.isTargetedDeliveryRule;for(const a of this.featureFlags.values())if(a.environmentEnabled&&a.rules.some(a=>a.type===_types.RuleType.TARGETED_DELIVERY))return!0;return!1}checkIntegrity(a){if(!a)return!1;const b=Object.keys(a);if(!b.length)return!1;const c=Object.keys(_constants.DEFAULT_CLIENT_CONFIGURATION);return b.sort().join()===c.sort().join()}checkShouldUpdate(){let a=!!(0<arguments.length&&void 0!==arguments[0])&&arguments[0];const{configuration:b}=this.configurationData;if(a)return this.updateType=_types.UpdateType.Idle,!1;if(this.updateType=b.realTimeUpdate?_types.UpdateType.RealTime:_types.UpdateType.Polling,!this.featureFlags.size)return!0;const c=this.lastUpdate.getTime(),d=Date.now()-this.updateInterval;return c<d}readStorageData(){const a=this.storage.read();if(a.ok){const{data:b,lastUpdate:c}=a.data,d=this.checkIntegrity(b);if(!d){this.urlProvider.dataApiDomain=_constants.DEFAULT_CONFIGURATION_DATA.configuration.dataApiDomain;const a=_objectSpread(_objectSpread({},_constants.DEFAULT_CONFIGURATION_DATA),{},{featureFlags:[]});this.storage.write({data:a,lastUpdate:this.lastUpdate.toString()}),this.configurationData=_constants.DEFAULT_CONFIGURATION_DATA}else{this.urlProvider.dataApiDomain=b.configuration.dataApiDomain;const{featureFlags:a,customData:d}=b;null!==d&&void 0!==d&&d.length&&(this.dataManager.customDataIndexes=d);for(const b of a)this.featureFlagsData.set(b.featureKey,b);this.configurationData=b,this.lastUpdate=new Date(Date.parse(c))}}}async updateClientConfiguration(a){var b;const c=await this.requester.getClientConfiguration(a);if(!c.ok)return this.featureFlags.size?(0,_tsRes.Ok)(!0):c;_utilities.Utilities.sendOfflineTracking({storage:this.offlineTrackingStorage,requester:this.requester});const{configuration:d,customData:e,featureFlags:f}=c.data;this.configurationData={configuration:d,customData:e};for(const b of f)this.featureFlagsData.set(b.featureKey,b);null!==e&&void 0!==e&&e.length&&(this.dataManager.customDataIndexes=e),this.dataManager.clearTrees(),null===(b=this.mappedRules)||void 0===b?void 0:b.clear(),this.isTargetedDeliveryRule=null,this.segmentsData=null;const g=this.updateStorageData();if(!g.ok)return g;const h=d.realTimeUpdate?_types.UpdateType.RealTime:_types.UpdateType.Polling,i=h!==this.updateType;i&&(this.updateType=h,await this.initialize());const j=this.isConsentRequired&&!this.hasAnyTargetedDeliveryRule;return this.visitorCodeManager.consentRequired=j,(0,_tsRes.Ok)(i)}updateStorageData(){this.lastUpdate=new Date;const a=_objectSpread(_objectSpread({},this.configurationData),{},{featureFlags:Array.from(this.featureFlags.values())}),b={data:a,lastUpdate:this.lastUpdate.toString()};return this.urlProvider.dataApiDomain=this.configurationData.configuration.dataApiDomain,this.storage.write(b)}}exports.ClientConfiguration=ClientConfiguration;
|
|
2
2
|
//# sourceMappingURL=clientConfiguration.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"clientConfiguration.js","names":["ClientConfiguration","constructor","a","updateInterval","storage","requester","dataManager","externalClientConfiguration","offlineTrackingStorage","eventSource","externalVisitorCodeManager","eventManager","_defineProperty","UpdateType","Idle","DEFAULT_CONFIGURATION_DATA","Map","lastUpdate","Date","visitorCodeManager","initialize","readStorageData","isExternalConfiguration","shouldUpdate","checkShouldUpdate","updateResult","updateClientConfiguration","ok","isUpdateTypeToggled","data","Ok","handleExternalUpdates","updateType","RealTime","isOpen","Polling","handlePollingUpdates","handleRealTimeUpdates","cleanupHandlers","close","updateConfigurationIntervalId","clearInterval","customData","configuration","featureFlags","configurationData","featureFlag","featureFlagsData","set","featureKey","updateEventCallback","timestamp","then","fireEvent","EventType","ConfigurationUpdate","open","setInterval","bind","err","segments","segmentsData","forEach","flag","rules","rule","segment","has","id","ruleMap","mappedRules","size","values","experimentId","variationByExposition","variationMap","variationKey","variationId","featureId","variations","isConsentRequired","consentType","ConsentType","Required","hasAnyTargetedDeliveryRule","isTargetedDeliveryRule","environmentEnabled","some","type","RuleType","TARGETED_DELIVERY","checkIntegrity","fields","Object","keys","length","requiredFields","DEFAULT_CLIENT_CONFIGURATION","sort","join","skipChecks","arguments","realTimeUpdate","lastUpdateTime","getTime","updateWindowEdge","now","result","read","isStorageValid","UrlProvider","setDataApiDomain","dataApiDomain","_objectSpread","write","toString","customDataIndexes","parse","b","clientConfigurationResult","getClientConfiguration","Utilities","sendOfflineTracking","clearTrees","clear","updateStorageData","toggleUpdateType","consentRequired","Array","from","exports"],"sources":["../../src/clientConfiguration/clientConfiguration.ts"],"sourcesContent":["import { Ok, Result } from 'ts-res';\nimport { KameleoonError } from 'src/kameleoonError/kameleoonError';\nimport { DataManager } from 'src/kameleoonData';\nimport { Requester } from 'src/requester';\nimport { SegmentType } from 'src/targeting';\nimport { ClientDataType } from 'src/storage';\nimport { IEventSource } from 'src/eventSource';\nimport {\n DEFAULT_CLIENT_CONFIGURATION,\n DEFAULT_CONFIGURATION_DATA,\n} from './constants';\nimport {\n ClientConfigurationDataType,\n ClientConfigurationParametersType,\n ConfigurationDataType,\n ConfigurationType,\n ConsentType,\n FeatureFlagType,\n MappedRuleType,\n RuleType,\n UpdateType,\n} from './types';\nimport { Utilities } from 'src/utilities';\nimport { IStorage, OfflineTracking } from 'src/storage/types';\nimport { IVisitorCodeManager } from 'src/visitorCodeManager';\nimport { EventManager, EventType } from 'src/eventManager';\nimport { UrlProvider } from 'src/requester/urlProvider';\n\ninterface IClientConfiguration {\n initialize: (useCache?: boolean) => Promise<Result<void, KameleoonError>>;\n readonly featureFlags: Map<string, FeatureFlagType>;\n readonly configuration: ConfigurationType;\n readonly segments: Map<string, SegmentType>;\n readonly ruleMap: Map<number, MappedRuleType>;\n}\n\nexport class ClientConfiguration implements IClientConfiguration {\n private updateConfigurationIntervalId: NodeJS.Timeout | null = null;\n private updateType: UpdateType = UpdateType.Idle;\n private configurationData: ClientConfigurationDataType =\n DEFAULT_CONFIGURATION_DATA;\n private featureFlagsData: Map<string, FeatureFlagType> = new Map();\n private isTargetedDeliveryRule: boolean | null = null;\n private segmentsData: Map<string, SegmentType> | null = null;\n private updateInterval: number;\n private lastUpdate: Date;\n private storage: IStorage<ClientDataType>;\n private offlineTrackingStorage: IStorage<OfflineTracking>;\n private requester: Requester;\n private eventSource: IEventSource;\n private externalClientConfiguration?: ConfigurationDataType;\n private mappedRules: Map<number, MappedRuleType> | null = null;\n private dataManager: DataManager;\n private visitorCodeManager: IVisitorCodeManager;\n private eventManager: EventManager;\n\n constructor({\n updateInterval,\n storage,\n requester,\n dataManager,\n externalClientConfiguration,\n offlineTrackingStorage,\n eventSource,\n externalVisitorCodeManager,\n eventManager,\n }: ClientConfigurationParametersType) {\n this.requester = requester;\n this.updateInterval = updateInterval;\n this.lastUpdate = new Date();\n this.storage = storage;\n this.dataManager = dataManager;\n this.eventManager = eventManager;\n this.externalClientConfiguration = externalClientConfiguration;\n this.offlineTrackingStorage = offlineTrackingStorage;\n this.visitorCodeManager = externalVisitorCodeManager;\n this.eventSource = eventSource;\n }\n\n public async initialize(): Promise<Result<void, KameleoonError>> {\n this.readStorageData();\n\n const isExternalConfiguration = Boolean(this.externalClientConfiguration);\n const shouldUpdate = this.checkShouldUpdate(isExternalConfiguration);\n\n if (shouldUpdate) {\n const updateResult = await this.updateClientConfiguration();\n\n if (!updateResult.ok) {\n return updateResult;\n }\n\n // --- Note ---\n // If update type is being toggled `initialize` will be called again\n // so we don't need to continue execution here\n const isUpdateTypeToggled = updateResult.data;\n\n if (isUpdateTypeToggled) {\n return Ok();\n }\n }\n\n if (isExternalConfiguration) {\n this.handleExternalUpdates();\n\n return Ok();\n }\n\n if (this.updateType === UpdateType.RealTime && !this.eventSource.isOpen) {\n this.updateType = UpdateType.Idle;\n this.handleRealTimeUpdates();\n\n return Ok();\n }\n\n if (this.updateType === UpdateType.Polling) {\n this.handlePollingUpdates();\n }\n\n return Ok();\n }\n\n private cleanupHandlers(): void {\n if (this.eventSource.isOpen) {\n this.eventSource.close();\n }\n\n if (this.updateConfigurationIntervalId) {\n clearInterval(this.updateConfigurationIntervalId);\n }\n }\n\n private handleExternalUpdates(): void {\n this.cleanupHandlers();\n\n const { customData, configuration, featureFlags } =\n this.externalClientConfiguration!;\n this.configurationData = { customData, configuration };\n\n for (const featureFlag of featureFlags) {\n this.featureFlagsData.set(featureFlag.featureKey, featureFlag);\n }\n }\n\n private handleRealTimeUpdates(): void {\n this.cleanupHandlers();\n\n const updateEventCallback = (timestamp: number) => {\n this.updateClientConfiguration(timestamp).then((updateResult) => {\n if (updateResult.ok) {\n this.eventManager.fireEvent(EventType.ConfigurationUpdate, {\n timestamp,\n });\n }\n });\n };\n\n this.eventSource.open(updateEventCallback);\n }\n\n private handlePollingUpdates(): void {\n // --- Note ---\n // If `initialize` is called again the interval will be cleared\n // so theoretically we will constantly defer config update\n // but `this.lastUpdate` with `checkShouldUpdate` will prevent that\n this.cleanupHandlers();\n\n // --- Note ---\n // Error Handling is for `setInterval` emergency cleanup\n try {\n this.updateConfigurationIntervalId = setInterval(\n this.updateClientConfiguration.bind(this),\n this.updateInterval,\n );\n } catch (err) {\n if (this.updateConfigurationIntervalId) {\n clearInterval(this.updateConfigurationIntervalId);\n }\n\n throw err;\n }\n }\n\n get featureFlags(): Map<string, FeatureFlagType> {\n return this.featureFlagsData;\n }\n\n get configuration(): ConfigurationType {\n return this.configurationData.configuration;\n }\n\n get segments(): Map<string, SegmentType> {\n if (this.segmentsData) {\n return this.segmentsData;\n }\n\n const segmentsData = new Map<string, SegmentType>();\n\n this.featureFlagsData.forEach((flag) => {\n flag.rules.forEach((rule) => {\n if (rule.segment && !segmentsData.has(rule.segment.id)) {\n segmentsData.set(rule.segment.id, rule.segment);\n }\n });\n });\n\n this.segmentsData = segmentsData;\n\n return segmentsData;\n }\n\n get ruleMap(): Map<number, MappedRuleType> {\n if (this.mappedRules?.size) {\n return this.mappedRules;\n }\n\n const mappedRules = new Map<number, MappedRuleType>();\n\n for (const featureFlag of this.featureFlags.values()) {\n for (const rule of featureFlag.rules) {\n const { id, experimentId, variationByExposition } = rule;\n const variationMap = new Map<string, number>();\n\n variationByExposition.forEach(({ variationKey, variationId }) => {\n if (typeof variationId === 'number') {\n variationMap.set(variationKey, variationId);\n }\n });\n\n mappedRules.set(id, {\n featureId: featureFlag.id,\n experimentId,\n variations: variationMap,\n });\n }\n }\n\n this.mappedRules = mappedRules;\n\n return mappedRules;\n }\n\n get isConsentRequired(): boolean {\n return this.configuration.consentType === ConsentType.Required;\n }\n\n get hasAnyTargetedDeliveryRule(): boolean {\n if (this.isTargetedDeliveryRule !== null) {\n return this.isTargetedDeliveryRule;\n }\n\n for (const featureFlag of this.featureFlags.values()) {\n if (\n featureFlag.environmentEnabled &&\n featureFlag.rules.some(\n (rule) => rule.type === RuleType.TARGETED_DELIVERY,\n )\n ) {\n return true;\n }\n }\n\n return false;\n }\n\n // --- Note ---\n // Integrity check covers most of the migration scenarios\n // however in the future it will be changed to a dedicate migration\n // block that can handle all versions migrations\n private checkIntegrity(data: ConfigurationDataType | undefined): boolean {\n if (!data) {\n return false;\n }\n\n const fields = Object.keys(data);\n\n if (!fields.length) {\n return false;\n }\n\n const requiredFields = Object.keys(DEFAULT_CLIENT_CONFIGURATION);\n\n return fields.sort().join() === requiredFields.sort().join();\n }\n\n private checkShouldUpdate(skipChecks = false): boolean {\n const { configuration } = this.configurationData;\n\n // --- Note ---\n // Following `updateType` logic is done for client side\n // edge cases where we have previous campaigns on storage already, but we still want\n // to initialize SSE/Polling after page reload\n if (skipChecks) {\n this.updateType = UpdateType.Idle;\n\n return false;\n }\n\n this.updateType = configuration.realTimeUpdate\n ? UpdateType.RealTime\n : UpdateType.Polling;\n\n if (!this.featureFlags.size) {\n return true;\n }\n\n const lastUpdateTime = this.lastUpdate.getTime();\n const updateWindowEdge = Date.now() - this.updateInterval;\n\n return lastUpdateTime < updateWindowEdge;\n }\n\n private readStorageData(): void {\n const result = this.storage.read();\n\n if (result.ok) {\n const { data, lastUpdate } = result.data;\n\n const isStorageValid = this.checkIntegrity(data);\n\n // --- Note ---\n // Cleaning up storage if it's not valid for migration purposes\n if (!isStorageValid) {\n UrlProvider.setDataApiDomain(\n DEFAULT_CONFIGURATION_DATA.configuration.dataApiDomain,\n );\n\n const data = {\n ...DEFAULT_CONFIGURATION_DATA,\n featureFlags: [],\n };\n\n this.storage.write({\n data,\n lastUpdate: this.lastUpdate.toString(),\n });\n\n this.configurationData = DEFAULT_CONFIGURATION_DATA;\n } else {\n UrlProvider.setDataApiDomain(data.configuration.dataApiDomain);\n\n const { featureFlags, customData } = data;\n\n if (customData?.length) {\n this.dataManager.customDataIndexes = customData;\n }\n\n for (const featureFlag of featureFlags) {\n this.featureFlagsData.set(featureFlag.featureKey, featureFlag);\n }\n\n this.configurationData = data;\n this.lastUpdate = new Date(Date.parse(lastUpdate));\n }\n }\n }\n\n /**\n * Updates client configuration\n *\n * @param timeStamp - timestamp for real-time configuration update\n *\n * @returns `true` if current update type should be toggled (SSE/Polling)\n */\n private async updateClientConfiguration(\n timestamp?: number,\n ): Promise<Result<boolean, KameleoonError>> {\n const clientConfigurationResult =\n await this.requester.getClientConfiguration(timestamp);\n\n if (!clientConfigurationResult.ok) {\n if (this.featureFlags.size) {\n // TODO: the case of silent fail should be logged when logging is implemented\n return Ok(true);\n }\n\n return clientConfigurationResult;\n }\n\n Utilities.sendOfflineTracking({\n storage: this.offlineTrackingStorage,\n requester: this.requester,\n });\n\n const { configuration, customData, featureFlags } =\n clientConfigurationResult.data;\n\n this.configurationData = { configuration, customData };\n\n for (const featureFlag of featureFlags) {\n this.featureFlagsData.set(featureFlag.featureKey, featureFlag);\n }\n\n if (customData?.length) {\n this.dataManager.customDataIndexes = customData;\n }\n\n this.dataManager.clearTrees();\n this.mappedRules?.clear();\n this.isTargetedDeliveryRule = null;\n this.segmentsData = null;\n\n const result = this.updateStorageData();\n\n if (!result.ok) {\n return result;\n }\n\n const updateType = configuration.realTimeUpdate\n ? UpdateType.RealTime\n : UpdateType.Polling;\n\n const toggleUpdateType = updateType !== this.updateType;\n\n if (toggleUpdateType) {\n this.updateType = updateType;\n await this.initialize();\n }\n\n // --- Note ---\n // Regarding GDPR policy we should set visitorCode if legal consent isn't required\n // or we have at least one Targeted Delivery rule in configuration\n const consentRequired =\n this.isConsentRequired && !this.hasAnyTargetedDeliveryRule;\n this.visitorCodeManager.consentRequired = consentRequired;\n\n return Ok(toggleUpdateType);\n }\n\n private updateStorageData(): Result<void, KameleoonError> {\n this.lastUpdate = new Date();\n\n const configurationData = {\n ...this.configurationData,\n featureFlags: Array.from(this.featureFlags.values()),\n };\n\n const data: ClientDataType = {\n data: configurationData,\n lastUpdate: this.lastUpdate.toString(),\n };\n\n UrlProvider.setDataApiDomain(\n this.configurationData.configuration.dataApiDomain,\n );\n\n return this.storage.write(data);\n }\n}\n"],"mappings":"k6CAoCO,KAAM,CAAAA,mBAAoD,CAoB/DC,WAAWA,CAAAC,CAAA,CAU2B,IAV1B,CACVC,cAAc,CAAdA,CAAc,CACdC,OAAO,CAAPA,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gB,CAC1B,IAAI,CAAClE,iBAAiB,CAACF,aAAa,CAACqE,aACvC,CAAC,CAEM,IAAI,CAAC5G,OAAO,CAAC8G,KAAK,CAACrF,CAAI,CAChC,CACF,CAACqG,OAAA,CAAAlI,mBAAA,CAAAA,mBAAA"}
|
|
1
|
+
{"version":3,"file":"clientConfiguration.js","names":["ClientConfiguration","constructor","a","updateInterval","urlProvider","storage","requester","dataManager","externalClientConfiguration","offlineTrackingStorage","eventSource","externalVisitorCodeManager","eventManager","_defineProperty","UpdateType","Idle","DEFAULT_CONFIGURATION_DATA","Map","lastUpdate","Date","visitorCodeManager","initialize","readStorageData","isExternalConfiguration","shouldUpdate","checkShouldUpdate","updateResult","updateClientConfiguration","ok","isUpdateTypeToggled","data","Ok","handleExternalUpdates","updateType","RealTime","isOpen","Polling","handlePollingUpdates","handleRealTimeUpdates","cleanupHandlers","close","updateConfigurationIntervalId","clearInterval","customData","configuration","featureFlags","configurationData","featureFlag","featureFlagsData","set","featureKey","updateEventCallback","timestamp","then","fireEvent","EventType","ConfigurationUpdate","open","setInterval","bind","err","segments","segmentsData","forEach","flag","rules","rule","segment","has","id","ruleMap","mappedRules","size","values","experimentId","variationByExposition","variationMap","variationKey","variationId","featureId","variations","isConsentRequired","consentType","ConsentType","Required","hasAnyTargetedDeliveryRule","isTargetedDeliveryRule","environmentEnabled","some","type","RuleType","TARGETED_DELIVERY","checkIntegrity","fields","Object","keys","length","requiredFields","DEFAULT_CLIENT_CONFIGURATION","sort","join","skipChecks","arguments","realTimeUpdate","lastUpdateTime","getTime","updateWindowEdge","now","result","read","isStorageValid","dataApiDomain","_objectSpread","write","toString","customDataIndexes","parse","b","clientConfigurationResult","getClientConfiguration","Utilities","sendOfflineTracking","clearTrees","clear","updateStorageData","toggleUpdateType","consentRequired","Array","from","exports"],"sources":["../../src/clientConfiguration/clientConfiguration.ts"],"sourcesContent":["import { Ok, Result } from 'ts-res';\nimport { KameleoonError } from 'src/kameleoonError/kameleoonError';\nimport { DataManager } from 'src/kameleoonData';\nimport { Requester } from 'src/requester';\nimport { SegmentType } from 'src/targeting';\nimport { ClientDataType } from 'src/storage';\nimport { IEventSource } from 'src/eventSource';\nimport {\n DEFAULT_CLIENT_CONFIGURATION,\n DEFAULT_CONFIGURATION_DATA,\n} from './constants';\nimport {\n ClientConfigurationDataType,\n ClientConfigurationParametersType,\n ConfigurationDataType,\n ConfigurationType,\n ConsentType,\n FeatureFlagType,\n MappedRuleType,\n RuleType,\n UpdateType,\n} from './types';\nimport { Utilities } from 'src/utilities';\nimport { IStorage, OfflineTracking } from 'src/storage/types';\nimport { IVisitorCodeManager } from 'src/visitorCodeManager';\nimport { EventManager, EventType } from 'src/eventManager';\nimport { IUrlProvider } from 'src/requester/urlProvider';\n\ninterface IClientConfiguration {\n initialize: (useCache?: boolean) => Promise<Result<void, KameleoonError>>;\n readonly featureFlags: Map<string, FeatureFlagType>;\n readonly configuration: ConfigurationType;\n readonly segments: Map<string, SegmentType>;\n readonly ruleMap: Map<number, MappedRuleType>;\n}\n\nexport class ClientConfiguration implements IClientConfiguration {\n private updateConfigurationIntervalId: NodeJS.Timeout | null = null;\n private updateType: UpdateType = UpdateType.Idle;\n private configurationData: ClientConfigurationDataType =\n DEFAULT_CONFIGURATION_DATA;\n private featureFlagsData: Map<string, FeatureFlagType> = new Map();\n private isTargetedDeliveryRule: boolean | null = null;\n private segmentsData: Map<string, SegmentType> | null = null;\n private updateInterval: number;\n private lastUpdate: Date;\n private storage: IStorage<ClientDataType>;\n private offlineTrackingStorage: IStorage<OfflineTracking>;\n private requester: Requester;\n private eventSource: IEventSource;\n private externalClientConfiguration?: ConfigurationDataType;\n private mappedRules: Map<number, MappedRuleType> | null = null;\n private dataManager: DataManager;\n private visitorCodeManager: IVisitorCodeManager;\n private eventManager: EventManager;\n private urlProvider: IUrlProvider;\n\n constructor({\n updateInterval,\n urlProvider,\n storage,\n requester,\n dataManager,\n externalClientConfiguration,\n offlineTrackingStorage,\n eventSource,\n externalVisitorCodeManager,\n eventManager,\n }: ClientConfigurationParametersType) {\n this.urlProvider = urlProvider;\n this.requester = requester;\n this.updateInterval = updateInterval;\n this.lastUpdate = new Date();\n this.storage = storage;\n this.dataManager = dataManager;\n this.eventManager = eventManager;\n this.externalClientConfiguration = externalClientConfiguration;\n this.offlineTrackingStorage = offlineTrackingStorage;\n this.visitorCodeManager = externalVisitorCodeManager;\n this.eventSource = eventSource;\n }\n\n public async initialize(): Promise<Result<void, KameleoonError>> {\n this.readStorageData();\n\n const isExternalConfiguration = Boolean(this.externalClientConfiguration);\n const shouldUpdate = this.checkShouldUpdate(isExternalConfiguration);\n\n if (shouldUpdate) {\n const updateResult = await this.updateClientConfiguration();\n\n if (!updateResult.ok) {\n return updateResult;\n }\n\n // --- Note ---\n // If update type is being toggled `initialize` will be called again\n // so we don't need to continue execution here\n const isUpdateTypeToggled = updateResult.data;\n\n if (isUpdateTypeToggled) {\n return Ok();\n }\n }\n\n if (isExternalConfiguration) {\n this.handleExternalUpdates();\n\n return Ok();\n }\n\n if (this.updateType === UpdateType.RealTime && !this.eventSource.isOpen) {\n this.updateType = UpdateType.Idle;\n this.handleRealTimeUpdates();\n\n return Ok();\n }\n\n if (this.updateType === UpdateType.Polling) {\n this.handlePollingUpdates();\n }\n\n return Ok();\n }\n\n private cleanupHandlers(): void {\n if (this.eventSource.isOpen) {\n this.eventSource.close();\n }\n\n if (this.updateConfigurationIntervalId) {\n clearInterval(this.updateConfigurationIntervalId);\n }\n }\n\n private handleExternalUpdates(): void {\n this.cleanupHandlers();\n\n const { customData, configuration, featureFlags } =\n this.externalClientConfiguration!;\n this.configurationData = { customData, configuration };\n\n for (const featureFlag of featureFlags) {\n this.featureFlagsData.set(featureFlag.featureKey, featureFlag);\n }\n }\n\n private handleRealTimeUpdates(): void {\n this.cleanupHandlers();\n\n const updateEventCallback = (timestamp: number) => {\n this.updateClientConfiguration(timestamp).then((updateResult) => {\n if (updateResult.ok) {\n this.eventManager.fireEvent(EventType.ConfigurationUpdate, {\n timestamp,\n });\n }\n });\n };\n\n this.eventSource.open(updateEventCallback);\n }\n\n private handlePollingUpdates(): void {\n // --- Note ---\n // If `initialize` is called again the interval will be cleared\n // so theoretically we will constantly defer config update\n // but `this.lastUpdate` with `checkShouldUpdate` will prevent that\n this.cleanupHandlers();\n\n // --- Note ---\n // Error Handling is for `setInterval` emergency cleanup\n try {\n this.updateConfigurationIntervalId = setInterval(\n this.updateClientConfiguration.bind(this),\n this.updateInterval,\n );\n } catch (err) {\n if (this.updateConfigurationIntervalId) {\n clearInterval(this.updateConfigurationIntervalId);\n }\n\n throw err;\n }\n }\n\n get featureFlags(): Map<string, FeatureFlagType> {\n return this.featureFlagsData;\n }\n\n get configuration(): ConfigurationType {\n return this.configurationData.configuration;\n }\n\n get segments(): Map<string, SegmentType> {\n if (this.segmentsData) {\n return this.segmentsData;\n }\n\n const segmentsData = new Map<string, SegmentType>();\n\n this.featureFlagsData.forEach((flag) => {\n flag.rules.forEach((rule) => {\n if (rule.segment && !segmentsData.has(rule.segment.id)) {\n segmentsData.set(rule.segment.id, rule.segment);\n }\n });\n });\n\n this.segmentsData = segmentsData;\n\n return segmentsData;\n }\n\n get ruleMap(): Map<number, MappedRuleType> {\n if (this.mappedRules?.size) {\n return this.mappedRules;\n }\n\n const mappedRules = new Map<number, MappedRuleType>();\n\n for (const featureFlag of this.featureFlags.values()) {\n for (const rule of featureFlag.rules) {\n const { id, experimentId, variationByExposition } = rule;\n const variationMap = new Map<string, number>();\n\n variationByExposition.forEach(({ variationKey, variationId }) => {\n if (typeof variationId === 'number') {\n variationMap.set(variationKey, variationId);\n }\n });\n\n mappedRules.set(id, {\n featureId: featureFlag.id,\n experimentId,\n variations: variationMap,\n });\n }\n }\n\n this.mappedRules = mappedRules;\n\n return mappedRules;\n }\n\n get isConsentRequired(): boolean {\n return this.configuration.consentType === ConsentType.Required;\n }\n\n get hasAnyTargetedDeliveryRule(): boolean {\n if (this.isTargetedDeliveryRule !== null) {\n return this.isTargetedDeliveryRule;\n }\n\n for (const featureFlag of this.featureFlags.values()) {\n if (\n featureFlag.environmentEnabled &&\n featureFlag.rules.some(\n (rule) => rule.type === RuleType.TARGETED_DELIVERY,\n )\n ) {\n return true;\n }\n }\n\n return false;\n }\n\n // --- Note ---\n // Integrity check covers most of the migration scenarios\n // however in the future it will be changed to a dedicate migration\n // block that can handle all versions migrations\n private checkIntegrity(data: ConfigurationDataType | undefined): boolean {\n if (!data) {\n return false;\n }\n\n const fields = Object.keys(data);\n\n if (!fields.length) {\n return false;\n }\n\n const requiredFields = Object.keys(DEFAULT_CLIENT_CONFIGURATION);\n\n return fields.sort().join() === requiredFields.sort().join();\n }\n\n private checkShouldUpdate(skipChecks = false): boolean {\n const { configuration } = this.configurationData;\n\n // --- Note ---\n // Following `updateType` logic is done for client side\n // edge cases where we have previous campaigns on storage already, but we still want\n // to initialize SSE/Polling after page reload\n if (skipChecks) {\n this.updateType = UpdateType.Idle;\n\n return false;\n }\n\n this.updateType = configuration.realTimeUpdate\n ? UpdateType.RealTime\n : UpdateType.Polling;\n\n if (!this.featureFlags.size) {\n return true;\n }\n\n const lastUpdateTime = this.lastUpdate.getTime();\n const updateWindowEdge = Date.now() - this.updateInterval;\n\n return lastUpdateTime < updateWindowEdge;\n }\n\n private readStorageData(): void {\n const result = this.storage.read();\n\n if (result.ok) {\n const { data, lastUpdate } = result.data;\n\n const isStorageValid = this.checkIntegrity(data);\n\n // --- Note ---\n // Cleaning up storage if it's not valid for migration purposes\n if (!isStorageValid) {\n this.urlProvider.dataApiDomain =\n DEFAULT_CONFIGURATION_DATA.configuration.dataApiDomain;\n\n const data = {\n ...DEFAULT_CONFIGURATION_DATA,\n featureFlags: [],\n };\n\n this.storage.write({\n data,\n lastUpdate: this.lastUpdate.toString(),\n });\n\n this.configurationData = DEFAULT_CONFIGURATION_DATA;\n } else {\n this.urlProvider.dataApiDomain = data.configuration.dataApiDomain;\n\n const { featureFlags, customData } = data;\n\n if (customData?.length) {\n this.dataManager.customDataIndexes = customData;\n }\n\n for (const featureFlag of featureFlags) {\n this.featureFlagsData.set(featureFlag.featureKey, featureFlag);\n }\n\n this.configurationData = data;\n this.lastUpdate = new Date(Date.parse(lastUpdate));\n }\n }\n }\n\n /**\n * Updates client configuration\n *\n * @param timeStamp - timestamp for real-time configuration update\n *\n * @returns `true` if current update type should be toggled (SSE/Polling)\n */\n private async updateClientConfiguration(\n timestamp?: number,\n ): Promise<Result<boolean, KameleoonError>> {\n const clientConfigurationResult =\n await this.requester.getClientConfiguration(timestamp);\n\n if (!clientConfigurationResult.ok) {\n if (this.featureFlags.size) {\n // TODO: the case of silent fail should be logged when logging is implemented\n return Ok(true);\n }\n\n return clientConfigurationResult;\n }\n\n Utilities.sendOfflineTracking({\n storage: this.offlineTrackingStorage,\n requester: this.requester,\n });\n\n const { configuration, customData, featureFlags } =\n clientConfigurationResult.data;\n\n this.configurationData = { configuration, customData };\n\n for (const featureFlag of featureFlags) {\n this.featureFlagsData.set(featureFlag.featureKey, featureFlag);\n }\n\n if (customData?.length) {\n this.dataManager.customDataIndexes = customData;\n }\n\n this.dataManager.clearTrees();\n this.mappedRules?.clear();\n this.isTargetedDeliveryRule = null;\n this.segmentsData = null;\n\n const result = this.updateStorageData();\n\n if (!result.ok) {\n return result;\n }\n\n const updateType = configuration.realTimeUpdate\n ? UpdateType.RealTime\n : UpdateType.Polling;\n\n const toggleUpdateType = updateType !== this.updateType;\n\n if (toggleUpdateType) {\n this.updateType = updateType;\n await this.initialize();\n }\n\n // --- Note ---\n // Regarding GDPR policy we should set visitorCode if legal consent isn't required\n // or we have at least one Targeted Delivery rule in configuration\n const consentRequired =\n this.isConsentRequired && !this.hasAnyTargetedDeliveryRule;\n this.visitorCodeManager.consentRequired = consentRequired;\n\n return Ok(toggleUpdateType);\n }\n\n private updateStorageData(): Result<void, KameleoonError> {\n this.lastUpdate = new Date();\n\n const configurationData = {\n ...this.configurationData,\n featureFlags: Array.from(this.featureFlags.values()),\n };\n\n const data: ClientDataType = {\n data: configurationData,\n lastUpdate: this.lastUpdate.toString(),\n };\n\n this.urlProvider.dataApiDomain =\n this.configurationData.configuration.dataApiDomain;\n\n return this.storage.write(data);\n }\n}\n"],"mappings":"i3CAoCO,KAAM,CAAAA,mBAAoD,CAqB/DC,WAAWA,CAAAC,CAAA,CAW2B,IAX1B,CACVC,cAAc,CAAdA,CAAc,CACdC,WAAW,CAAXA,CAAW,CACXC,OAAO,CAAPA,CAAO,CACPC,SAAS,CAATA,CAAS,CACTC,WAAW,CAAXA,CAAW,CACXC,2BAA2B,CAA3BA,CAA2B,CAC3BC,sBAAsB,CAAtBA,CAAsB,CACtBC,WAAW,CAAXA,CAAW,CACXC,0BAA0B,CAA1BA,CAA0B,CAC1BC,YAAY,CAAZA,CACiC,CAAC,CAAAV,CAAA,CAAAW,eAAA,sCA/B2B,IAAI,EAAAA,eAAA,mBAClCC,iBAAU,CAACC,IAAI,EAAAF,eAAA,0BAE9CG,qCAA0B,EAAAH,eAAA,yBAC6B,GAAI,CAAAI,GAAK,EAAAJ,eAAA,+BACjB,IAAI,EAAAA,eAAA,qBACG,IAAI,EAAAA,eAAA,+BAAAA,eAAA,2BAAAA,eAAA,wBAAAA,eAAA,uCAAAA,eAAA,0BAAAA,eAAA,4BAAAA,eAAA,4CAAAA,eAAA,oBAQF,IAAI,EAAAA,eAAA,4BAAAA,eAAA,mCAAAA,eAAA,6BAAAA,eAAA,4BAkB5D,IAAI,CAACT,WAAW,CAAGA,CAAW,CAC9B,IAAI,CAACE,SAAS,CAAGA,CAAS,CAC1B,IAAI,CAACH,cAAc,CAAGA,CAAc,CACpC,IAAI,CAACe,UAAU,CAAG,GAAI,CAAAC,IAAM,CAC5B,IAAI,CAACd,OAAO,CAAGA,CAAO,CACtB,IAAI,CAACE,WAAW,CAAGA,CAAW,CAC9B,IAAI,CAACK,YAAY,CAAGA,CAAY,CAChC,IAAI,CAACJ,2BAA2B,CAAGA,CAA2B,CAC9D,IAAI,CAACC,sBAAsB,CAAGA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,CAAA2B,CAAiB,CAAAkE,aAAA,CAAAA,aAAA,IAClB,IAAI,CAAClE,iBAAiB,MACzBD,YAAY,CAAEkF,KAAK,CAACC,IAAI,CAAC,IAAI,CAACnF,YAAY,CAAC4B,MAAM,CAAC,CAAC,CAAC,EACrD,CAEK3C,CAAoB,CAAG,CAC3BA,IAAI,CAAEgB,CAAiB,CACvB5B,UAAU,CAAE,IAAI,CAACA,UAAU,CAACgG,QAAQ,CAAC,CACvC,CAAC,CAKD,MAHA,KAAI,CAAC9G,WAAW,CAAC2G,aAAa,CAC5B,IAAI,CAACjE,iBAAiB,CAACF,aAAa,CAACmE,aAAa,CAE7C,IAAI,CAAC1G,OAAO,CAAC4G,KAAK,CAACnF,CAAI,CAChC,CACF,CAACmG,OAAA,CAAAjI,mBAAA,CAAAA,mBAAA"}
|
|
@@ -6,6 +6,7 @@ import { ClientDataType, IStorage, OfflineTracking } from '../storage';
|
|
|
6
6
|
import { SegmentType } from '../targeting';
|
|
7
7
|
import { VariableType } from '../types';
|
|
8
8
|
import { EventManager } from '../eventManager';
|
|
9
|
+
import { IUrlProvider } from '../requester/urlProvider';
|
|
9
10
|
export type ScheduleType = {
|
|
10
11
|
dateStart: string;
|
|
11
12
|
dateEnd: string;
|
|
@@ -108,6 +109,7 @@ export type ConfigurationType = {
|
|
|
108
109
|
dataApiDomain: string;
|
|
109
110
|
};
|
|
110
111
|
export type ClientConfigurationParametersType = {
|
|
112
|
+
urlProvider: IUrlProvider;
|
|
111
113
|
updateInterval: number;
|
|
112
114
|
storage: IStorage<ClientDataType>;
|
|
113
115
|
dataManager: DataManager;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","names":["UpdateType","exports","Polling","RealTime","Idle","RuleType","TARGETED_DELIVERY","EXPERIMENTATION","FeatureFlagSdkLanguageType","ANDROID","SWIFT","JAVA","CSHARP","NODEJS","PHP","RUBY","GO","FLUTTER","REACTJS","FeatureStatus","ACTIVATED","DEACTIVATED","SCHEDULED","CustomDataScope","Visit","Visitor","Page","ConsentType","Required","NotRequired"],"sources":["../../src/clientConfiguration/types.ts"],"sourcesContent":["import { IEventSource } from 'src/eventSource';\nimport { DataManager } from 'src/kameleoonData';\nimport { Requester } from 'src/requester';\nimport { IVisitorCodeManager } from 'src/visitorCodeManager';\nimport { ClientDataType, IStorage, OfflineTracking } from 'src/storage';\nimport { SegmentType } from 'src/targeting';\nimport { VariableType } from 'src/types';\nimport { EventManager } from 'src/eventManager';\n\nexport type ScheduleType = {\n dateStart: string;\n dateEnd: string;\n};\n\nexport enum UpdateType {\n Polling,\n RealTime,\n Idle,\n}\n\nexport type JSONValue =\n | string\n | number\n | boolean\n | { [x: string]: JSONValue }\n | JSONValue[];\n\nexport type JSONType = Record<string | number | symbol, JSONValue> | null;\n\nexport enum RuleType {\n TARGETED_DELIVERY = 'TARGETED_DELIVERY',\n EXPERIMENTATION = 'EXPERIMENTATION',\n}\n\nexport enum FeatureFlagSdkLanguageType {\n ANDROID = 'ANDROID',\n SWIFT = 'SWIFT',\n JAVA = 'JAVA',\n CSHARP = 'CSHARP',\n NODEJS = 'NODEJS',\n PHP = 'PHP',\n RUBY = 'RUBY',\n GO = 'GO',\n FLUTTER = 'FLUTTER',\n REACTJS = 'REACTJS',\n}\n\nexport enum FeatureStatus {\n ACTIVATED = 'ACTIVATED',\n DEACTIVATED = 'DEACTIVATED',\n SCHEDULED = 'SCHEDULED',\n}\n\nexport enum CustomDataScope {\n Visit = 'VISIT',\n Visitor = 'VISITOR',\n Page = 'Page',\n}\n\nexport enum ConsentType {\n Required = 'REQUIRED',\n NotRequired = 'NOT_REQUIRED',\n}\n\nexport type DeviationType = {\n variationId: string;\n value: number;\n};\n\nexport type FeatureFlagType = {\n id: number;\n featureKey: string;\n environmentEnabled: boolean;\n variations: FeatureVariationType[];\n defaultVariationKey: string;\n rules: RuleItemType[];\n};\n\nexport type FeatureVariationType = {\n key: string;\n variables: FeatureVariableType[];\n};\n\nexport type FeatureVariableType = {\n key: string;\n type: VariableType;\n value: string | number | boolean;\n};\n\nexport type RuleItemType = {\n type: RuleType;\n id: number;\n respoolTime: number | null;\n order: number;\n exposition: number;\n experimentId: number;\n variationByExposition: VariationByExpositionType[];\n segment: SegmentType | null;\n};\n\nexport type MappedRuleType = {\n experimentId: number;\n featureId: number;\n // --- Note ---\n // Map<variationKey, variationId>\n variations: Map<string, number>;\n};\n\nexport type VariationByExpositionType = {\n variationKey: string;\n variationId: number;\n exposition: number;\n};\n\nexport type ConfigurationDataType = {\n featureFlags: FeatureFlagType[];\n configuration: ConfigurationType;\n customData: CustomDataConfigurationType[];\n};\n\nexport type ClientConfigurationDataType = Omit<\n ConfigurationDataType,\n 'featureFlags'\n>;\n\nexport type CustomDataConfigurationType = {\n index: number;\n localOnly: boolean;\n isMappingIdentifier: boolean;\n scope: CustomDataScope;\n};\n\nexport type ConfigurationType = {\n realTimeUpdate: boolean;\n consentType: ConsentType;\n dataApiDomain: string;\n};\n\nexport type ClientConfigurationParametersType = {\n updateInterval: number;\n storage: IStorage<ClientDataType>;\n dataManager: DataManager;\n requester: Requester;\n eventSource: IEventSource;\n eventManager: EventManager;\n offlineTrackingStorage: IStorage<OfflineTracking>;\n externalClientConfiguration?: ConfigurationDataType;\n externalVisitorCodeManager: IVisitorCodeManager;\n};\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"types.js","names":["UpdateType","exports","Polling","RealTime","Idle","RuleType","TARGETED_DELIVERY","EXPERIMENTATION","FeatureFlagSdkLanguageType","ANDROID","SWIFT","JAVA","CSHARP","NODEJS","PHP","RUBY","GO","FLUTTER","REACTJS","FeatureStatus","ACTIVATED","DEACTIVATED","SCHEDULED","CustomDataScope","Visit","Visitor","Page","ConsentType","Required","NotRequired"],"sources":["../../src/clientConfiguration/types.ts"],"sourcesContent":["import { IEventSource } from 'src/eventSource';\nimport { DataManager } from 'src/kameleoonData';\nimport { Requester } from 'src/requester';\nimport { IVisitorCodeManager } from 'src/visitorCodeManager';\nimport { ClientDataType, IStorage, OfflineTracking } from 'src/storage';\nimport { SegmentType } from 'src/targeting';\nimport { VariableType } from 'src/types';\nimport { EventManager } from 'src/eventManager';\nimport { IUrlProvider } from 'src/requester/urlProvider';\n\nexport type ScheduleType = {\n dateStart: string;\n dateEnd: string;\n};\n\nexport enum UpdateType {\n Polling,\n RealTime,\n Idle,\n}\n\nexport type JSONValue =\n | string\n | number\n | boolean\n | { [x: string]: JSONValue }\n | JSONValue[];\n\nexport type JSONType = Record<string | number | symbol, JSONValue> | null;\n\nexport enum RuleType {\n TARGETED_DELIVERY = 'TARGETED_DELIVERY',\n EXPERIMENTATION = 'EXPERIMENTATION',\n}\n\nexport enum FeatureFlagSdkLanguageType {\n ANDROID = 'ANDROID',\n SWIFT = 'SWIFT',\n JAVA = 'JAVA',\n CSHARP = 'CSHARP',\n NODEJS = 'NODEJS',\n PHP = 'PHP',\n RUBY = 'RUBY',\n GO = 'GO',\n FLUTTER = 'FLUTTER',\n REACTJS = 'REACTJS',\n}\n\nexport enum FeatureStatus {\n ACTIVATED = 'ACTIVATED',\n DEACTIVATED = 'DEACTIVATED',\n SCHEDULED = 'SCHEDULED',\n}\n\nexport enum CustomDataScope {\n Visit = 'VISIT',\n Visitor = 'VISITOR',\n Page = 'Page',\n}\n\nexport enum ConsentType {\n Required = 'REQUIRED',\n NotRequired = 'NOT_REQUIRED',\n}\n\nexport type DeviationType = {\n variationId: string;\n value: number;\n};\n\nexport type FeatureFlagType = {\n id: number;\n featureKey: string;\n environmentEnabled: boolean;\n variations: FeatureVariationType[];\n defaultVariationKey: string;\n rules: RuleItemType[];\n};\n\nexport type FeatureVariationType = {\n key: string;\n variables: FeatureVariableType[];\n};\n\nexport type FeatureVariableType = {\n key: string;\n type: VariableType;\n value: string | number | boolean;\n};\n\nexport type RuleItemType = {\n type: RuleType;\n id: number;\n respoolTime: number | null;\n order: number;\n exposition: number;\n experimentId: number;\n variationByExposition: VariationByExpositionType[];\n segment: SegmentType | null;\n};\n\nexport type MappedRuleType = {\n experimentId: number;\n featureId: number;\n // --- Note ---\n // Map<variationKey, variationId>\n variations: Map<string, number>;\n};\n\nexport type VariationByExpositionType = {\n variationKey: string;\n variationId: number;\n exposition: number;\n};\n\nexport type ConfigurationDataType = {\n featureFlags: FeatureFlagType[];\n configuration: ConfigurationType;\n customData: CustomDataConfigurationType[];\n};\n\nexport type ClientConfigurationDataType = Omit<\n ConfigurationDataType,\n 'featureFlags'\n>;\n\nexport type CustomDataConfigurationType = {\n index: number;\n localOnly: boolean;\n isMappingIdentifier: boolean;\n scope: CustomDataScope;\n};\n\nexport type ConfigurationType = {\n realTimeUpdate: boolean;\n consentType: ConsentType;\n dataApiDomain: string;\n};\n\nexport type ClientConfigurationParametersType = {\n urlProvider: IUrlProvider;\n updateInterval: number;\n storage: IStorage<ClientDataType>;\n dataManager: DataManager;\n requester: Requester;\n eventSource: IEventSource;\n eventManager: EventManager;\n offlineTrackingStorage: IStorage<OfflineTracking>;\n externalClientConfiguration?: ConfigurationDataType;\n externalVisitorCodeManager: IVisitorCodeManager;\n};\n"],"mappings":"uNAeY,CAAAA,UAAU,CAAAC,OAAA,CAAAD,UAAA,UAAVA,CAAU,QAAV,CAAAA,CAAU,CAAVA,CAAU,CAAAE,OAAA,cAAVF,CAAU,CAAVA,CAAU,CAAAG,QAAA,eAAVH,CAAU,CAAVA,CAAU,CAAAI,IAAA,WAAVJ,CAAU,MAeVK,QAAQ,CAAAJ,OAAA,CAAAI,QAAA,UAARA,CAAQ,QAAR,CAAAA,CAAQ,CAAAC,iBAAA,qBAARD,CAAQ,CAAAE,eAAA,mBAARF,CAAQ,MAKRG,0BAA0B,CAAAP,OAAA,CAAAO,0BAAA,UAA1BA,CAA0B,QAA1B,CAAAA,CAA0B,CAAAC,OAAA,WAA1BD,CAA0B,CAAAE,KAAA,SAA1BF,CAA0B,CAAAG,IAAA,QAA1BH,CAA0B,CAAAI,MAAA,UAA1BJ,CAA0B,CAAAK,MAAA,UAA1BL,CAA0B,CAAAM,GAAA,OAA1BN,CAA0B,CAAAO,IAAA,QAA1BP,CAA0B,CAAAQ,EAAA,MAA1BR,CAA0B,CAAAS,OAAA,WAA1BT,CAA0B,CAAAU,OAAA,WAA1BV,CAA0B,MAa1BW,aAAa,CAAAlB,OAAA,CAAAkB,aAAA,UAAbA,CAAa,QAAb,CAAAA,CAAa,CAAAC,SAAA,aAAbD,CAAa,CAAAE,WAAA,eAAbF,CAAa,CAAAG,SAAA,aAAbH,CAAa,MAMbI,eAAe,CAAAtB,OAAA,CAAAsB,eAAA,UAAfA,CAAe,QAAf,CAAAA,CAAe,CAAAC,KAAA,SAAfD,CAAe,CAAAE,OAAA,WAAfF,CAAe,CAAAG,IAAA,QAAfH,CAAe,MAMfI,WAAW,CAAA1B,OAAA,CAAA0B,WAAA,UAAXA,CAAW,QAAX,CAAAA,CAAW,CAAAC,QAAA,YAAXD,CAAW,CAAAE,WAAA,gBAAXF,CAAW"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { EventHandlerType,
|
|
1
|
+
import { EventHandlerType, EventSourceParametersType } from './types';
|
|
2
2
|
export interface IEventSource {
|
|
3
3
|
readonly isOpen: boolean;
|
|
4
4
|
open: (onEvent: EventHandlerType) => void;
|
|
@@ -9,7 +9,7 @@ export declare class KameleoonEventSource implements IEventSource {
|
|
|
9
9
|
private siteCode;
|
|
10
10
|
private url;
|
|
11
11
|
private isConnectionOpen;
|
|
12
|
-
constructor(siteCode
|
|
12
|
+
constructor({ siteCode, externalEventSource, urlProvider, }: EventSourceParametersType);
|
|
13
13
|
get isOpen(): boolean;
|
|
14
14
|
open(onEvent: EventHandlerType): void;
|
|
15
15
|
close(): void;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.KameleoonEventSource=void 0;
|
|
1
|
+
"use strict";var _constants=require("./constants");Object.defineProperty(exports,"__esModule",{value:!0}),exports.KameleoonEventSource=void 0;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 KameleoonEventSource{constructor(a){let{siteCode:b,externalEventSource:c,urlProvider:d}=a;_defineProperty(this,"eventSource",void 0),_defineProperty(this,"siteCode",void 0),_defineProperty(this,"url",void 0),_defineProperty(this,"isConnectionOpen",void 0),this.url=d.getEventSourceUrl(),this.siteCode=b,this.eventSource=c,this.isConnectionOpen=!1}get isOpen(){return this.isConnectionOpen}open(a){this.eventSource.open({onEvent:this.handleMessage(a),url:this.url,eventType:_constants.REAL_TIME_EVENT}),this.isConnectionOpen=!0}close(){this.eventSource.close(),this.isConnectionOpen=!1}handleMessage(a){const b=b=>{const c=JSON.parse(b.data),{siteCode:d,ts:e}=c;this.siteCode===d&&a(e)};return b}}exports.KameleoonEventSource=KameleoonEventSource;
|
|
2
2
|
//# sourceMappingURL=eventSource.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"eventSource.js","names":["KameleoonEventSource","constructor","siteCode","externalEventSource","
|
|
1
|
+
{"version":3,"file":"eventSource.js","names":["_constants","require","Object","defineProperty","exports","value","KameleoonEventSource","_defineProperty","a","b","c","_toPropertyKey","enumerable","configurable","writable","_toPrimitive","Symbol","toPrimitive","d","call","TypeError","String","Number","constructor","siteCode","externalEventSource","urlProvider","url","getEventSourceUrl","eventSource","isConnectionOpen","isOpen","open","onEvent","handleMessage","eventType","REAL_TIME_EVENT","close","onMessage","message","event","JSON","parse","data","eventSiteCode","ts"],"sources":["../../src/eventSource/eventSource.ts"],"sourcesContent":["import { REAL_TIME_EVENT } from './constants';\nimport {\n EventHandlerType,\n EventSourceParametersType,\n IExternalEventSource,\n RealTimeEventType,\n} from './types';\n\nexport interface IEventSource {\n readonly isOpen: boolean;\n open: (onEvent: EventHandlerType) => void;\n close: () => void;\n}\n\n// --- Note ---\n// Named `KameleoonEventSource` to avoid collision with native `EventSource`\nexport class KameleoonEventSource implements IEventSource {\n private eventSource: IExternalEventSource;\n private siteCode: string;\n private url: string;\n private isConnectionOpen: boolean;\n\n constructor({\n siteCode,\n externalEventSource,\n urlProvider,\n }: EventSourceParametersType) {\n this.url = urlProvider.getEventSourceUrl();\n this.siteCode = siteCode;\n this.eventSource = externalEventSource;\n this.isConnectionOpen = false;\n }\n\n get isOpen(): boolean {\n return this.isConnectionOpen;\n }\n\n public open(onEvent: EventHandlerType): void {\n this.eventSource.open({\n onEvent: this.handleMessage(onEvent),\n url: this.url,\n eventType: REAL_TIME_EVENT,\n });\n this.isConnectionOpen = true;\n }\n\n public close(): void {\n this.eventSource.close();\n this.isConnectionOpen = false;\n }\n\n private handleMessage(\n onEvent: EventHandlerType,\n ): (message: MessageEvent) => void {\n const onMessage = (message: MessageEvent): void => {\n const event: RealTimeEventType = JSON.parse(message.data);\n const { siteCode: eventSiteCode, ts } = event;\n\n if (this.siteCode === eventSiteCode) {\n onEvent(ts);\n }\n };\n\n return onMessage;\n }\n}\n"],"mappings":"aAAA,IAAAA,UAAA,CAAAC,OAAA,gBAA8CC,MAAA,CAAAC,cAAA,CAAAC,OAAA,eAAAC,KAAA,MAAAD,OAAA,CAAAE,oBAAA,iBAAAC,gBAAAC,CAAA,CAAAC,CAAA,CAAAC,CAAA,SAAAD,CAAA,CAAAE,cAAA,CAAAF,CAAA,EAAAA,CAAA,IAAAD,CAAA,CAAAN,MAAA,CAAAC,cAAA,CAAAK,CAAA,CAAAC,CAAA,EAAAJ,KAAA,CAAAK,CAAA,CAAAE,UAAA,IAAAC,YAAA,IAAAC,QAAA,MAAAN,CAAA,CAAAC,CAAA,EAAAC,CAAA,CAAAF,CAAA,UAAAG,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,CAEQI,aAAaA,CACnBD,CAAyB,CACQ,CACjC,KAAM,CAAAK,CAAS,CAAIC,CAAqB,EAAW,MAC3C,CAAAC,CAAwB,CAAGC,IAAI,CAACC,KAAK,CAACH,CAAO,CAACI,IAAI,CAAC,CACnD,CAAEnB,QAAQ,CAAEoB,CAAa,CAAEC,EAAE,CAAFA,CAAG,CAAC,CAAGL,CAAK,CAEzC,IAAI,CAAChB,QAAQ,GAAKoB,CAAa,EACjCX,CAAO,CAACY,CAAE,CAEd,CAAC,CAED,MAAO,CAAAP,CACT,CACF,CAAClC,OAAA,CAAAE,oBAAA,CAAAA,oBAAA"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { IUrlProvider } from '../requester';
|
|
1
2
|
/**
|
|
2
3
|
* @param {number} timestamp - timestamp of when the event has happened
|
|
3
4
|
* */
|
|
@@ -34,3 +35,8 @@ export type RealTimeEventType = {
|
|
|
34
35
|
siteCode: string;
|
|
35
36
|
ts: number;
|
|
36
37
|
};
|
|
38
|
+
export type EventSourceParametersType = {
|
|
39
|
+
siteCode: string;
|
|
40
|
+
urlProvider: IUrlProvider;
|
|
41
|
+
externalEventSource: IExternalEventSource;
|
|
42
|
+
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","names":[],"sources":["../../src/eventSource/types.ts"],"sourcesContent":["/**\n * @param {number} timestamp - timestamp of when the event has happened\n * */\nexport type EventHandlerType = (timestamp: number) => void;\n\n/**\n * @param {string} url - url of server sent event server which will be pasted by consumer\n * @param {string} eventType - type of event to be listened for\n * @param {(message: MessageEvent) => void} onEvent - callback to be executed when event fired\n * */\nexport type EventSourceOpenParametersType = {\n url: string;\n eventType: string;\n onEvent: (message: MessageEvent) => void;\n};\n\n/**\n * @interface an interface of External Event Source which will be used in server sent events operations\n * */\nexport interface IExternalEventSource {\n /**\n * @method open - opens event source live connection\n * @param {OpenEventSourceParamsType} parameters - parameters to be passed to the event source\n * */\n open: ({ url, eventType, onEvent }: EventSourceOpenParametersType) => void;\n /**\n * @method close - closes event source live connection\n * */\n close: () => void;\n}\n\n/**\n * @param {string} siteCode - site code from the event\n * @param {number} ts - timestamp of when the event has happened\n * */\nexport type RealTimeEventType = {\n siteCode: string;\n ts: number;\n};\n"],"mappings":""}
|
|
1
|
+
{"version":3,"file":"types.js","names":[],"sources":["../../src/eventSource/types.ts"],"sourcesContent":["import { IUrlProvider } from 'src/requester';\n\n/**\n * @param {number} timestamp - timestamp of when the event has happened\n * */\nexport type EventHandlerType = (timestamp: number) => void;\n\n/**\n * @param {string} url - url of server sent event server which will be pasted by consumer\n * @param {string} eventType - type of event to be listened for\n * @param {(message: MessageEvent) => void} onEvent - callback to be executed when event fired\n * */\nexport type EventSourceOpenParametersType = {\n url: string;\n eventType: string;\n onEvent: (message: MessageEvent) => void;\n};\n\n/**\n * @interface an interface of External Event Source which will be used in server sent events operations\n * */\nexport interface IExternalEventSource {\n /**\n * @method open - opens event source live connection\n * @param {OpenEventSourceParamsType} parameters - parameters to be passed to the event source\n * */\n open: ({ url, eventType, onEvent }: EventSourceOpenParametersType) => void;\n /**\n * @method close - closes event source live connection\n * */\n close: () => void;\n}\n\n/**\n * @param {string} siteCode - site code from the event\n * @param {number} ts - timestamp of when the event has happened\n * */\nexport type RealTimeEventType = {\n siteCode: string;\n ts: number;\n};\n\nexport type EventSourceParametersType = {\n siteCode: string;\n urlProvider: IUrlProvider;\n externalEventSource: IExternalEventSource;\n};\n"],"mappings":""}
|
|
@@ -25,7 +25,7 @@ export declare class KameleoonClient implements IKameleoonClient {
|
|
|
25
25
|
/**
|
|
26
26
|
* @param {SDKCoreParameters} sdkCoreParameters - parameters for initializing sdk core
|
|
27
27
|
*/
|
|
28
|
-
constructor({ siteCode, configuration, internalConfiguration, }: SDKCoreParameters);
|
|
28
|
+
constructor({ siteCode, dependencies, configuration, internalConfiguration, }: SDKCoreParameters);
|
|
29
29
|
initialize(useCache?: boolean): Promise<boolean>;
|
|
30
30
|
addData(visitorCode: string, ...data: KameleoonDataType[]): void;
|
|
31
31
|
getRemoteVisitorData({ visitorCode, shouldAddData, filters, isUniqueIdentifier, }: RemoteVisitorDataParamsType): Promise<KameleoonDataType[]>;
|
package/dist/kameleoonClient.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"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,externalPRNG:l}=d,m=new _cacheManager.CacheManager(_constants.CACHE_CLEANUP_TIMEOUT),n=new _storage.DataStorage(f,_storage.KameleoonStorageKey.ClientData),o=new _storage.DataStorage(f,_storage.KameleoonStorageKey.TargetingData),p=new _storage.DataStorage(f,_storage.KameleoonStorageKey.VariationData),q=new _storage.DataStorage(f,_storage.KameleoonStorageKey.OfflineTracking),r=new _storage.DataStorage(f,_storage.KameleoonStorageKey.ConsentData),s=new _kameleoonData.DataManager({storage:o,cleanupInterval:e.cleanupInterval}),t=new _requester.Requester({siteCode:b,domain:e.networkDomain,environment:e.environment,packageInfo:h,externalRequester:j,requestTimeout:e.requestTimeout,trackRetryDelay:e.trackRetryDelay}),u=new _eventSource.KameleoonEventSource(e.siteCode,g),v=new _eventManager.EventManager,w=new _clientConfiguration.ClientConfiguration({storage:n,updateInterval:e.updateInterval,dataManager:s,eventManager:v,requester:t,externalClientConfiguration:k,offlineTrackingStorage:q,eventSource:u,externalVisitorCodeManager:i}),x=new _variationConfiguration.VariationConfiguration(p);_utilities.Utilities.prng=l,this.variationConfiguration=x,this.requester=t,this.trackingCache=m,this.dataManager=s,this.clientConfiguration=w,this.externalPackageInfo=h,this.offlineTrackingStorage=q,this.consentDataStorage=r,this.visitorCodeManager=i,this.eventManager=v}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,featureFlagVariation:g,requester:this.requester,dataManager:this.dataManager,isOfflineModeOn:this.isOfflineModeOn,isConsentProvided:this._isConsentProvided(a),offlineTrackingStorage:this.offlineTrackingStorage,variationConfiguration:this.variationConfiguration}),(0,_tsRes.Ok)(g)}}exports.KameleoonClient=KameleoonClient;
|
|
1
|
+
"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){var b;let{siteCode:c,dependencies:d,configuration:e,internalConfiguration:f}=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:g}=new _clientSettings.ClientSettings(c,e);this.environment=g.environment;const{externalStorage:h,externalEventSource:i,externalPackageInfo:j,externalVisitorCodeManager:k,externalRequester:l,externalClientConfiguration:m,externalPRNG:n}=f,o=new _cacheManager.CacheManager(_constants.CACHE_CLEANUP_TIMEOUT),p=new _storage.DataStorage(h,_storage.KameleoonStorageKey.ClientData),q=new _storage.DataStorage(h,_storage.KameleoonStorageKey.TargetingData),r=new _storage.DataStorage(h,_storage.KameleoonStorageKey.VariationData),s=new _storage.DataStorage(h,_storage.KameleoonStorageKey.OfflineTracking),t=new _storage.DataStorage(h,_storage.KameleoonStorageKey.ConsentData),u=new _kameleoonData.DataManager({storage:q,cleanupInterval:g.cleanupInterval}),v=null!==(b=null===d||void 0===d?void 0:d.urlProvider)&&void 0!==b?b:new _requester.UrlProvider;v.initialize({domain:g.networkDomain,siteCode:g.siteCode,packageInfo:j,environment:g.environment});const w=new _requester.Requester({urlProvider:v,packageInfo:j,externalRequester:l,requestTimeout:g.requestTimeout,trackRetryDelay:g.trackRetryDelay}),x=new _eventSource.KameleoonEventSource({siteCode:g.siteCode,externalEventSource:i,urlProvider:v}),y=new _eventManager.EventManager,z=new _clientConfiguration.ClientConfiguration({urlProvider:v,storage:p,updateInterval:g.updateInterval,dataManager:u,eventManager:y,requester:w,externalClientConfiguration:m,offlineTrackingStorage:s,eventSource:x,externalVisitorCodeManager:k}),A=new _variationConfiguration.VariationConfiguration(r);_utilities.Utilities.prng=n,this.variationConfiguration=A,this.requester=w,this.trackingCache=o,this.dataManager=u,this.clientConfiguration=z,this.externalPackageInfo=j,this.offlineTrackingStorage=s,this.consentDataStorage=t,this.visitorCodeManager=k,this.eventManager=y}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,featureFlagVariation:g,requester:this.requester,dataManager:this.dataManager,isOfflineModeOn:this.isOfflineModeOn,isConsentProvided:this._isConsentProvided(a),offlineTrackingStorage:this.offlineTrackingStorage,variationConfiguration:this.variationConfiguration}),(0,_tsRes.Ok)(g)}}exports.KameleoonClient=KameleoonClient;
|
|
2
2
|
//# sourceMappingURL=kameleoonClient.js.map
|