-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathflagsmith-core.ts
845 lines (780 loc) · 32.3 KB
/
flagsmith-core.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
import {
IDatadogRum,
IFlags,
IFlagsmith,
GetValueOptions,
IFlagsmithResponse,
IInitConfig,
IState,
ITraits,
IFlagsmithTrait,
} from './types';
export type LikeFetch = (input: Partial<RequestInfo>, init?: Partial<RequestInit>) => Promise<Partial<Response>>
let _fetch: LikeFetch;
type RequestOptions = {
method: "GET"|"PUT"|"DELETE"|"POST",
headers: Record<string, string>
body?:string
}
type DynatraceObject = {
"javaLongOrObject": Record<string, number>,
"date": Record<string, Date>,
"shortString": Record<string, string>,
"javaDouble": Record<string, number>,
}
type AsyncStorageType = {
getItem: (key:string, cb?:(err:string|null, res:string|null)=>void)=>Promise<string|null>
setItem: (key:string, value: string)=>Promise<string|null>
} | null
let AsyncStorage: AsyncStorageType = null;
const FLAGSMITH_KEY = "BULLET_TRAIN_DB";
const FLAGSMITH_EVENT = "BULLET_TRAIN_EVENT";
const defaultAPI = 'https://edge.api.flagsmith.com/api/v1/';
// @ts-ignore
import deepEqual from 'fast-deep-equal';
let eventSource:typeof EventSource;
const initError = function (caller:string) {
return "Attempted to " + caller + " a user before calling flagsmith.init. Call flagsmith.init first, if you wish to prevent it sending a request for flags, call init with preventFetch:true."
}
type Config= {browserlessStorage?:boolean, fetch?:LikeFetch, AsyncStorage?:AsyncStorageType, eventSource?:any};
const FLAGSMITH_CONFIG_ANALYTICS_KEY = "flagsmith_value_";
const FLAGSMITH_FLAG_ANALYTICS_KEY = "flagsmith_enabled_";
const FLAGSMITH_TRAIT_ANALYTICS_KEY = "flagsmith_trait_";
const Flagsmith = class {
timestamp: number|null = null
isLoading = false
eventSource:EventSource|null = null
constructor(props: Config) {
if (props.fetch) {
_fetch = props.fetch as LikeFetch;
} else {
_fetch = (typeof fetch !== 'undefined'? fetch : global?.fetch) as LikeFetch;
}
this.canUseStorage = typeof window!=='undefined' || !!props.browserlessStorage;
this.log("Constructing flagsmith instance " + props)
if (props.eventSource) {
eventSource = props.eventSource;
}
if (props.AsyncStorage) {
AsyncStorage = props.AsyncStorage;
}
}
getJSON = (url:string, method?:"GET"|"POST"|"PUT", body?:string) => {
const { environmentID, headers } = this;
const options: RequestOptions = {
method: method || 'GET',
body,
headers: {
'x-environment-key': `${environmentID}`
}
};
if (method && method !== "GET")
options.headers['Content-Type'] = 'application/json; charset=utf-8'
if (headers) {
Object.assign(options.headers, headers)
}
if (!_fetch) {
console.error("Flagsmith: fetch is undefined, please specify a fetch implementation into flagsmith.init to support SSR.");
}
return _fetch(url, options)
.then(res => {
const lastUpdated = res.headers?.get('x-flagsmith-document-updated-at');
if(lastUpdated) {
try {
const lastUpdatedFloat = parseFloat(lastUpdated)
if(isNaN(lastUpdatedFloat)) {
throw "Failed to parse x-flagsmith-document-updated-at"
}
this.timestamp = lastUpdatedFloat
} catch (e) {
this.log(e,"Failed to parse x-flagsmith-document-updated-at",lastUpdated)
}
}
this.log("Fetch response: "+ res.status + " " + (method||"GET") + + " " + url)
return res.text!()
.then((text) => {
let err = text;
try {
err = JSON.parse(text);
} catch (e) {}
return res.status && res.status >= 200 && res.status < 300 ? err : Promise.reject(err);
})
}).catch((e)=>{
console.error("Flagsmith: Fetch error: " + e)
throw new Error("Flagsmith: Fetch error:" + e)
})
};
getFlags = (resolve?:(v?:any)=>any, reject?:(v?:any)=>any) => {
const { onChange, onError, identity, api } = this;
let resolved = false;
this.log("Get Flags")
this.isLoading = true;
const handleResponse = ({ flags: features, traits }:IFlagsmithResponse) => {
this.isLoading = false;
if (identity) {
this.withTraits = null;
}
// Handle server response
const flags:IFlags = {};
const userTraits: ITraits = {};
features = features || [];
traits = traits || [];
features.forEach(feature => {
flags[feature.feature.name.toLowerCase().replace(/ /g, '_')] = {
id: feature.feature.id,
enabled: feature.enabled,
value: feature.feature_state_value
};
});
traits.forEach(trait => {
userTraits[trait.trait_key.toLowerCase().replace(/ /g, '_')] = trait.trait_value
});
this.oldFlags = {
...this.flags
};
const flagsEqual = deepEqual(this.flags, flags);
const traitsEqual = deepEqual(this.traits, userTraits);
this.flags = flags;
this.traits = userTraits;
this.updateStorage();
if (this.datadogRum) {
try {
if (this.datadogRum!.trackTraits) {
const traits: Parameters<IDatadogRum["client"]["setUser"]>["0"] = {};
Object.keys(this.traits).map((key) => {
traits[FLAGSMITH_TRAIT_ANALYTICS_KEY + key] = this.getTrait(key);
});
const datadogRumData = {
...this.datadogRum.client.getUser(),
id: this.datadogRum.client.getUser().id || this.identity,
...traits,
};
this.log("Setting Datadog user", datadogRumData);
this.datadogRum.client.setUser(datadogRumData);
}
} catch (e) {
console.error(e)
}
}
if (this.dtrum) {
try {
const traits: DynatraceObject = {
javaDouble: {},
date: {},
shortString: {},
javaLongOrObject: {},
}
Object.keys(this.flags).map((key) => {
setDynatraceValue(traits, FLAGSMITH_CONFIG_ANALYTICS_KEY + key, this.getValue(key, {}, true))
setDynatraceValue(traits, FLAGSMITH_FLAG_ANALYTICS_KEY + key, this.hasFeature(key, true))
})
Object.keys(this.traits).map((key) => {
setDynatraceValue(traits, FLAGSMITH_TRAIT_ANALYTICS_KEY + key, this.getTrait(key))
})
this.log("Sending javaLongOrObject traits to dynatrace", traits.javaLongOrObject)
this.log("Sending date traits to dynatrace", traits.date)
this.log("Sending shortString traits to dynatrace", traits.shortString)
this.log("Sending javaDouble to dynatrace", traits.javaDouble)
// @ts-expect-error
this.dtrum.sendSessionProperties(
traits.javaLongOrObject, traits.date, traits.shortString, traits.javaDouble
)
} catch (e) {
console.error(e)
}
}
if (onChange) {
onChange(this.oldFlags, {
isFromServer: true,
flagsChanged: !flagsEqual,
traitsChanged: !traitsEqual
});
}
};
if (identity) {
return Promise.all([
this.withTraits?
this.getJSON(api + 'identities/', "POST", JSON.stringify({
"identifier": identity,
traits: Object.keys(this.withTraits).map((k)=>({
"trait_key":k,
"trait_value": this.withTraits![k]
})).filter((v)=>{
if (typeof v.trait_value === 'undefined') {
this.log("Warning - attempted to set an undefined trait value for key", v.trait_key)
return false
}
return true
})
})):
this.getJSON(api + 'identities/?identifier=' + encodeURIComponent(identity)),
])
.then((res) => {
this.withTraits = null
handleResponse(res[0] as IFlagsmithResponse)
if (resolve && !resolved) {
resolved = true;
resolve();
}
}).catch(({ message }) => {
this.isLoading = false;
onError && onError(new Error(message))
});
} else {
return Promise.all([
this.getJSON(api + "flags/")
])
.then((res) => {
handleResponse({ flags: res[0] as IFlagsmithResponse['flags'], traits:undefined })
if (resolve && !resolved) {
resolved = true;
resolve();
}
}).catch((err) => {
this.isLoading = false;
if (reject && !resolved) {
resolved = true;
reject(err);
}
onError && onError(err)
});
}
};
analyticsFlags = () => {
const { api } = this;
if (!this.evaluationEvent|| !this.evaluationEvent[this.environmentID]) {
return
}
if (this.evaluationEvent && Object.getOwnPropertyNames(this.evaluationEvent).length !== 0 && Object.getOwnPropertyNames(this.evaluationEvent[this.environmentID]).length !== 0) {
return this.getJSON(api + 'analytics/flags/', 'POST', JSON.stringify(this.evaluationEvent[this.environmentID]))
.then((res) => {
const state = this.getState();
if(!this.evaluationEvent) {
this.evaluationEvent = {}
}
this.evaluationEvent[this.environmentID] = {}
this.setState({
...state,
evaluationEvent: this.evaluationEvent,
});
this.updateEventStorage();
}).catch((err) => {
this.log("Exception fetching evaluationEvent", err);
});
}
};
datadogRum: IDatadogRum | null = null;
canUseStorage = false
analyticsInterval: NodeJS.Timer | null= null
api: string|null= null
cacheFlags= false
ts: number|null= null
enableAnalytics= false
enableLogs= false
environmentID = ""
evaluationEvent: Record<string, Record<string, number>> | null= null
flags:IFlags|null= null
getFlagInterval: NodeJS.Timer|null= null
headers?: object | null= null
initialised= false
oldFlags:IFlags|null= null
onChange:IInitConfig['onChange']|null= null
onError:IInitConfig['onError']|null = null
trigger?:(()=>void)|null= null
identity?: string|null= null
ticks: number|null= null
timer: number|null= null
traits:ITraits|null= null
dtrum= null
withTraits?: ITraits|null= null
cacheOptions = {ttl:0, skipAPI: false}
init({
environmentID,
api = defaultAPI,
headers,
onChange,
cacheFlags,
datadogRum,
onError,
defaultFlags,
fetch:fetchImplementation,
preventFetch,
enableLogs,
enableDynatrace,
enableAnalytics,
realtime,
eventSourceUrl= "https://realtime.flagsmith.com/",
AsyncStorage: _AsyncStorage,
identity,
traits,
_trigger,
state,
cacheOptions,
angularHttpClient,
}: IInitConfig) {
return new Promise((resolve, reject) => {
this.environmentID = environmentID;
this.api = api;
this.headers = headers;
this.getFlagInterval = null;
this.analyticsInterval = null;
this.onChange = (previousFlags, params) => {
if(onChange) {
onChange(previousFlags, params)
}
if(this.trigger) {
this.log("trigger called")
this.trigger()
}
}
this.trigger = _trigger || this.trigger;
this.onError = onError? (message:any)=> {
if (message instanceof Error) {
onError(message)
} else {
onError(new Error(message))
}
}: null
this.identity = identity;
this.withTraits = traits;
this.enableLogs = enableLogs|| false;
this.cacheOptions = cacheOptions? {skipAPI: !!cacheOptions.skipAPI, ttl: cacheOptions.ttl || 0} : this.cacheOptions;
if (!this.cacheOptions.ttl && this.cacheOptions.skipAPI) {
console.warn("Flagsmith: you have set a cache ttl of 0 and are skipping API calls, this means the API will not be hit unless you clear local storage.")
}
if(fetchImplementation) {
_fetch = fetchImplementation;
}
this.enableAnalytics = enableAnalytics ? enableAnalytics : false;
this.flags = Object.assign({}, defaultFlags) || {};
this.initialised = true;
this.ticks = 10000;
if (realtime && typeof window !== 'undefined') {
const connectionUrl = eventSourceUrl + "sse/environments/" + environmentID + "/stream";
if(!eventSource) {
this.log("Error, EventSource is undefined");
} else if (!this.eventSource) {
this.log("Creating event source with url " + connectionUrl)
this.eventSource = new eventSource(connectionUrl)
this.eventSource.addEventListener("environment_updated", (e)=>{
let updated_at;
try {
const data = JSON.parse(e.data)
updated_at = data.updated_at;
} catch (e) {
this.log("Could not parse sse event",e)
}
if (!updated_at) {
this.log("No updated_at received, fetching flags", e)
} else if(!this.timestamp || updated_at>this.timestamp) {
if (this.isLoading) {
this.log("updated_at is new, but flags are loading",e.data, this.timestamp)
} else {
this.log("updated_at is new, fetching flags",e.data, this.timestamp)
this.getFlags()
}
} else {
this.log("updated_at is outdated, skipping get flags", e.data, this.timestamp)
}
})
}
}
this.log("Initialising with properties",{
environmentID,
api,
headers,
onChange,
cacheFlags,
onError,
defaultFlags,
preventFetch,
enableLogs,
enableAnalytics,
AsyncStorage,
identity,
traits,
_trigger,
state,
angularHttpClient,
}, this)
this.timer = this.enableLogs ? new Date().valueOf() : null;
if (_AsyncStorage) {
AsyncStorage = _AsyncStorage;
}
this.cacheFlags = typeof AsyncStorage !== 'undefined' && !!cacheFlags;
this.setState(state as IState)
if (!environmentID) {
reject('Please specify a environment id')
throw ('Please specify a environment id');
}
if (datadogRum) {
this.datadogRum = datadogRum;
}
if (enableDynatrace) {
// @ts-expect-error Dynatrace's dtrum is exposed to global scope
if (typeof dtrum === 'undefined') {
console.error("You have attempted to enable dynatrace but dtrum is undefined, please check you have the Dynatrace RUM JavaScript API installed.")
} else {
// @ts-expect-error Dynatrace's dtrum is exposed to global scope
this.dtrum = dtrum;
}
}
if(angularHttpClient) {
// @ts-expect-error
_fetch = (url: string, params: { headers: Record<string, string>, method: "GET" | "POST" | "PUT", body: string }) => {
const {headers, method, body} = params
return new Promise((resolve) => {
switch (method) {
case "GET": {
return angularHttpClient.get(url, {
headers,
}).subscribe((v:string) => {
resolve({
ok: true,
text: () => Promise.resolve(v)
})
})
}
case "POST": {
return angularHttpClient.post(url, body, {
headers,
}).subscribe((v:string) => {
resolve({
ok: true,
text: () => Promise.resolve(v)
})
})
}
case "PUT": {
return angularHttpClient.post(url, body, {
headers,
}).subscribe((v:string) => {
resolve({
ok: true,
text: () => Promise.resolve(v)
})
})
}
}
})
}
}
if (AsyncStorage && this.canUseStorage) {
AsyncStorage.getItem(FLAGSMITH_EVENT)
.then((res)=>{
if (res){
try {
this.evaluationEvent = JSON.parse(res)
} catch (e){
this.evaluationEvent = {};
}
} else {
this.evaluationEvent = {};
}
this.analyticsInterval = setInterval(this.analyticsFlags, this.ticks!);
return true
})
}
if (this.enableAnalytics) {
if (this.analyticsInterval) {
clearInterval(this.analyticsInterval);
}
if (AsyncStorage && this.canUseStorage) {
AsyncStorage.getItem(FLAGSMITH_EVENT, (err, res) => {
if (res) {
const json = JSON.parse(res);
if (json[this.environmentID]) {
state = this.getState();
this.log("Retrieved events from cache", res);
this.setState({
...state,
evaluationEvent: json[this.environmentID],
});
}
}
return true
});
}
}
//If the user specified default flags emit a changed event immediately
if (cacheFlags) {
if (AsyncStorage && this.canUseStorage) {
AsyncStorage.getItem(FLAGSMITH_KEY, (err, res) => {
if (res) {
try {
const json = JSON.parse(res);
let cachePopulated = false;
if (json && json.api === this.api && json.environmentID === this.environmentID) {
let setState = true;
if(this.identity && (json.identity!==this.identity)) {
this.log("Ignoring cache, identity has changed from " + json.identity + " to " + this.identity )
setState = false;
}
if(this.cacheOptions.ttl){
if (!json.ts || (new Date().valueOf() - json.ts > this.cacheOptions.ttl)) {
if (json.ts) {
this.log("Ignoring cache, timestamp is too old ts:" + json.ts + " ttl: " + this.cacheOptions.ttl + " time elapsed since cache: " + (new Date().valueOf()-json.ts)+"ms")
setState = false;
}
}
}
if (setState) {
cachePopulated = true;
this.setState(json);
this.log("Retrieved flags from cache", json);
}
}
if (this.flags) { // retrieved flags from local storage
if (this.onChange) {
this.log("onChange called")
this.onChange(null, { isFromServer: false, flagsChanged: true, traitsChanged: !!this.traits });
}
this.oldFlags = this.flags;
resolve(true);
if (this.cacheOptions.skipAPI && cachePopulated) {
this.log("Skipping API, using cache")
}
if (!preventFetch && (!this.cacheOptions.skipAPI||!cachePopulated)) {
this.getFlags();
}
} else {
if (!preventFetch) {
this.getFlags(resolve, reject);
} else {
resolve(true);
}
}
} catch (e) {
this.log("Exception fetching cached logs", e);
}
} else {
if (!preventFetch) {
this.getFlags(resolve, reject)
} else {
if (defaultFlags) {
if (this.onChange) {
this.log("onChange called")
this.onChange(null, { isFromServer: false, flagsChanged: true, traitsChanged: !!this.traits });
}
}
resolve(true);
}
}
return true
});
}
} else if (!preventFetch) {
this.getFlags(resolve, reject);
} else {
if (defaultFlags) {
if (this.onChange) {
this.log("onChange called")
this.onChange(null, { isFromServer: false, flagsChanged: true, traitsChanged:!!this.traits });
}
}
resolve(true);
}
})
.catch(error => {
this.log("Error during initialisation ", error)
onError && onError(error)
});
}
getAllFlags() {
return this.flags;
}
identify(userId: string, traits?:ITraits) {
this.identity = userId;
this.log("Identify: " + this.identity)
if(traits) {
this.withTraits = {
...(this.withTraits||{}),
...traits
};
}
if (this.initialised) {
return this.getFlags();
}
return Promise.resolve();
}
getState() {
return {
api: this.api,
environmentID: this.environmentID,
flags: this.flags,
identity: this.identity,
ts: this.ts,
traits: this.traits,
evaluationEvent: this.evaluationEvent,
} as IState
}
setState(state: IState) {
if (state) {
this.initialised = true;
this.api = state.api || this.api || defaultAPI;
this.environmentID = state.environmentID || this.environmentID;
this.flags = state.flags || this.flags;
this.identity = state.identity || this.identity;
this.traits = state.traits || this.traits;
this.evaluationEvent = state.evaluationEvent || this.evaluationEvent;
this.log("setState called", this)
}
}
log(...args: (unknown)[]) {
if (this.enableLogs) {
console.log.apply(this, ["FLAGSMITH:", new Date().valueOf() - (this.timer||0), "ms", ...args]);
}
}
updateStorage() {
if (this.cacheFlags) {
this.ts = new Date().valueOf()
const state = JSON.stringify(this.getState());
this.log("Setting storage", state);
AsyncStorage!.setItem(FLAGSMITH_KEY, state);
}
}
updateEventStorage() {
if (this.enableAnalytics) {
const events = JSON.stringify(this.getState().evaluationEvent);
this.log("Setting event storage", events);
AsyncStorage!.setItem(FLAGSMITH_EVENT, events);
}
}
logout() {
this.identity = null;
this.traits = null;
if (this.initialised) {
return this.getFlags();
}
return Promise.resolve();
}
startListening(ticks = 1000) {
if (this.getFlagInterval) {
clearInterval(this.getFlagInterval);
}
this.getFlagInterval = setInterval(this.getFlags, ticks);
}
stopListening() {
if (this.getFlagInterval) {
clearInterval(this.getFlagInterval);
this.getFlagInterval = null;
}
}
getSegments() {
// noop for now
// return this.segments;
}
evaluateFlag = (key: string, method:"VALUE"|"ENABLED") => {
if (this.datadogRum) {
if (!this.datadogRum!.client!.addFeatureFlagEvaluation) {
console.error('Flagsmith: Your datadog RUM client does not support the function addFeatureFlagEvaluation, please update it.');
} else {
this.log("Sending feature flag evaluation to Datadog", key, method)
if (method === "VALUE") {
this.datadogRum!.client!.addFeatureFlagEvaluation(FLAGSMITH_CONFIG_ANALYTICS_KEY + key, this.getValue(key, { }, true));
} else {
this.datadogRum!.client!.addFeatureFlagEvaluation(FLAGSMITH_FLAG_ANALYTICS_KEY + key, this.hasFeature(key, true));
}
}
}
if (this.enableAnalytics) {
if (!this.evaluationEvent) return;
if(!this.evaluationEvent[this.environmentID]) {
this.evaluationEvent[this.environmentID] = {};
}
if (this.evaluationEvent[this.environmentID][key] === undefined) {
this.evaluationEvent[this.environmentID][key] = 0;
}
this.evaluationEvent[this.environmentID][key] += 1;
}
this.updateEventStorage();
}
getValue = (key: string, options?: GetValueOptions, skipAnalytics?:boolean) => {
const flag = this.flags && this.flags[key.toLowerCase().replace(/ /g, '_')];
let res = null;
if (flag) {
res = flag.value;
}
if(!skipAnalytics) {
this.evaluateFlag(key, "VALUE");
}
if (options?.json) {
try {
if (res === null) {
this.log("Tried to parse null flag as JSON: " + key)
return options.fallback;
}
return JSON.parse(res as string)
} catch (e) {
return options.fallback
}
}
//todo record check for value
return res;
}
getTrait = (key:string) => {
const trait = this.traits && this.traits[key.toLowerCase().replace(/ /g, '_')];
return trait;
}
getAllTraits = () => {
return this.traits
}
setTrait = (key:string, trait_value:IFlagsmithTrait) => {
const { api } = this;
if (!api) {
console.error(initError("setTrait"))
return
}
const traits:ITraits<string> = {};
traits[key] = trait_value;
return this.setTraits(traits)
};
setTraits = (traits:ITraits) => {
if (!this.api) {
console.error(initError("setTraits"))
return
}
if (!traits || typeof traits !== 'object') {
console.error("Expected object for flagsmith.setTraits");
}
this.withTraits = {
...(this.withTraits||{}),
...traits
};
if (!this.identity) {
this.log("Set traits prior to identifying", this.withTraits);
return
}
if (this.initialised) {
return this.getFlags()
}
};
hasFeature = (key: string, skipAnalytics?:boolean) => {
const flag = this.flags && this.flags[key.toLowerCase().replace(/ /g, '_')];
let res = false;
if (flag && flag.enabled) {
res = true;
}
if(!skipAnalytics) {
this.evaluateFlag(key, "ENABLED");
}
return res;
}
};
export default function ({ fetch, AsyncStorage, eventSource }:Config):IFlagsmith {
return new Flagsmith({ fetch, AsyncStorage, eventSource }) as IFlagsmith;
}
// transforms any trait to match sendSessionProperties
// https://www.dynatrace.com/support/doc/javascriptapi/interfaces/dtrum_types.DtrumApi.html#addActionProperties
const setDynatraceValue = function (obj: DynatraceObject, trait: string, value: string|number|boolean|null|undefined) {
let key: keyof DynatraceObject= 'shortString'
let convertToString = true
if (typeof value === 'number') {
key = 'javaDouble'
convertToString = false
}
// @ts-expect-error
obj[key] = obj[key] || {}
// @ts-expect-error
obj[key][trait] = convertToString ? value+"":value
}