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
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
|
import { storage, reflect, network, keyValue, number } from '@amp-metrics/mt-metricskit-utils-private';
import Logger from '@amp-metrics/mt-client-logger-core';
/*
* src/environment.js
* mt-client-config
*
* Copyright © 2016-2017 Apple Inc. All rights reserved.
*
*/
/**
* Provides a set of environment-specific (platform-specific) functions which can be individually overridden for the needs
* of the particular environment, or replaced en masse by providing a single replacement environment delegate object
* The functionality in this class is typically replaced via a delegate.
* @see setDelegate
* @delegatable
* @constructor
*/
var Environment = function () {};
/**
************************************ PUBLIC METHODS/IVARS ************************************
*/
/**
* Allows replacement of one or more of this class' functions
* Any method on the passed-in object which matches a method that this class has will be called instead of the built-in class method.
* To replace *all* methods of his class, simply have your delegate implement all the methods of this class
* Your delegate can be a true object instance, an anonymous object, or a class object.
* Your delegate is free to have as many additional non-matching methods as it likes.
* It can even act as a delegate for multiple MetricsKit objects, though that is not recommended.
*
* "setDelegate()" may be called repeatedly, with the functions in the most-recently set delegates replacing any functions matching those in the earlier delegates, as well as any as-yet unreplaced functions.
* This allows callers to use "canned" delegates to get most of their functionality, but still replace some number of methods that need custom implementations.
* If, for example, a client wants to use the "canned" itml/environment delegate with the exception of, say, the "appVersion" method, they can set itml/environment as the delegate, and
* then call "setDelegate()" again with their own delegate containing only a single method of "appVersion" as the delegate, which would leave all the other "replaced" methods intact,
* but override the "appVersion" method again, this time with their own supplied delegate.
*
* NOTE: The delegate function will have a property called origFunction representing the original function that it replaced.
* This allows the delegate to, essentially, call "super" before or after it does some work.
* If a replaced method is overridden again with a subsequent "setDelegate()" call, the "origFunction" property will be the previous delegate's function.
* @example:
* To override one or more methods, in place:
* eventRecorder.setDelegate({recordEvent: itms.recordEvent});
* To override one or more methods with a separate object:
* eventRecorder.setDelegate(eventRecorderDelegate);
* (where "eventRecorderDelegate" might be defined elsewhere as, e.g.:
* var eventRecorderDelegate = {recordEvent: itms.recordEvent,
* sendMethod: 'itms'};
* To override one or more methods with an instantiated object from a class definition:
* eventRecorder.setDelegate(new EventRecorderDelegate());
* (where "EventRecorderDelegate" might be defined elsewhere as, e.g.:
* function EventRecorderDelegate() {
* }
* EventRecorderDelegate.prototype.recordEvent = itms.recordEvent;
* EventRecorderDelegate.prototype.sendMethod = function sendMethod() {
* return 'itms';
* };
* To override one or more methods with a class object (with "static" methods):
* eventRecorder.setDelegate(EventRecorderDelegate);
* (where "EventRecorderDelegate" might be defined elsewhere as, e.g.:
* function EventRecorderDelegate() {
* }
* EventRecorderDelegate.recordEvent = itms.recordEvent;
* EventRecorderDelegate.sendMethod = function sendMethod() {
* return 'itms';
* };
* @param {Object} Object or Class with delegate method(s) to be called instead of default (built-in) methods.
* @returns {Boolean} true if one or more methods on the delegate object match one or more methods on the default object,
* otherwise returns false.
*/
Environment.prototype.setDelegate = function setDelegate(delegate) {
return reflect.attachDelegate(this, delegate);
};
Environment.prototype.localStorageObject = storage.localStorageObject;
Environment.prototype.sessionStorageObject = storage.sessionStorageObject;
/*
* src/network.js
* mt-client-config
*
* Copyright © 2018 Apple Inc. All rights reserved.
*
*/
/**
* Network request methods exposed so delegate callers can override
* @constructor
*/
var Network = function () {};
/**
* Allows replacement of one or more of this class' functions
* Any method on the passed-in object which matches a method that this class has will be called instead of the built-in class method.
* To replace *all* methods of his class, simply have your delegate implement all the methods of this class
* Your delegate can be a true object instance, an anonymous object, or a class object.
* Your delegate is free to have as many additional non-matching methods as it likes.
* It can even act as a delegate for multiple MetricsKit objects, though that is not recommended.
*
* "setDelegate()" may be called repeatedly, with the functions in the most-recently set delegates replacing any functions matching those in the earlier delegates, as well as any as-yet unreplaced functions.
* This allows callers to use "canned" delegates to get most of their functionality, but still replace some number of methods that need custom implementations.
* If, for example, a client wants to use the "canned" itml/environment delegate with the exception of, say, the "appVersion" method, they can set itml/environment as the delegate, and
* then call "setDelegate()" again with their own delegate containing only a single method of "appVersion" as the delegate, which would leave all the other "replaced" methods intact,
* but override the "appVersion" method again, this time with their own supplied delegate.
*
* NOTE: The delegate function will have a property called origFunction representing the original function that it replaced.
* This allows the delegate to, essentially, call "super" before or after it does some work.
* If a replaced method is overridden again with a subsequent "setDelegate()" call, the "origFunction" property will be the previous delegate's function.
* @example:
* To override one or more methods, in place:
* eventRecorder.setDelegate({recordEvent: itms.recordEvent});
* To override one or more methods with a separate object:
* eventRecorder.setDelegate(eventRecorderDelegate);
* (where "eventRecorderDelegate" might be defined elsewhere as, e.g.:
* var eventRecorderDelegate = {recordEvent: itms.recordEvent,
* sendMethod: 'itms'};
* To override one or more methods with an instantiated object from a class definition:
* eventRecorder.setDelegate(new EventRecorderDelegate());
* (where "EventRecorderDelegate" might be defined elsewhere as, e.g.:
* function EventRecorderDelegate() {
* }
* EventRecorderDelegate.prototype.recordEvent = itms.recordEvent;
* EventRecorderDelegate.prototype.sendMethod = function sendMethod() {
* return 'itms';
* };
* To override one or more methods with a class object (with "static" methods):
* eventRecorder.setDelegate(EventRecorderDelegate);
* (where "EventRecorderDelegate" might be defined elsewhere as, e.g.:
* function EventRecorderDelegate() {
* }
* EventRecorderDelegate.recordEvent = itms.recordEvent;
* EventRecorderDelegate.sendMethod = function sendMethod() {
* return 'itms';
* };
* @param {Object} Object or Class with delegate method(s) to be called instead of default (built-in) methods.
* @returns {Boolean} true if one or more methods on the delegate object match one or more methods on the default object,
* otherwise returns false.
*/
Network.prototype.setDelegate = function setDelegate(delegate) {
return reflect.attachDelegate(this, delegate);
};
/**
* Covers private utils implementation of makeAjaxRequest for delegation
*/
Network.prototype.makeAjaxRequest = network.makeAjaxRequest;
/*
* src/config.js
* mt-client-config
*
* Copyright © 2016-2017 Apple Inc. All rights reserved.
*
*/
var NO_TOPIC_KEY = 'noTopicConfig';
var COMPOUND_SEPARATOR = '_';
/**
* The default config should not include keys which have meaning if they are omitted.
* For example, a configSource without impressions means no impressions should be recorded, and in this case we should
* not have impressions in defaults so we don't inadvertently disobey the client's configSource.
*/
var DEFAULTS = {
configBaseUrl: 'https://xp.apple.com/config/1/report',
disabled: true // Prevent sending event if no config is available
};
// @private
var _defaultConfig;
/**
* Appends the provided source and its subsection if the subsection key matches the provided topic to the provided configSources array.
* @param {Array} configSources
* @param {String} topic
* @param {Object} source
*/
var _appendSectionAndSubsectionToConfigSources = function _appendSectionAndSubsectionToConfigSources(
configSources,
topic,
source
) {
if (source) {
configSources.push(source);
var subsection = source[topic];
if (subsection && reflect.hasAnyKeys(subsection)) {
configSources.push(subsection);
}
}
};
/**
* Provides config-related functionality including managing config sources and values.
* The functionality in this class is typically replaced via a delegate.
* @see setDelegate
* @delegatable
* @constructor
* @param {String} topic
*/
var Config = function Config(topic) {
// @public
this.environment = new Environment();
/**
* @public
* @deprecated
*/
this.network = new Network();
// @public
this.logger = /*#__PURE__*/ new Logger('mt-client-config');
// @private
this._topic = topic || NO_TOPIC_KEY;
// @private
this._debugSource = null;
// @private
this._cachedSource = null;
// @private
this._serviceSource = null;
// @private
this._initCalled = false;
// @private
this._initialized = false;
// @private
this._showedDebugWarning = false;
// @private
this._showedNoProvidedSourceWarning = false;
// @private
this._keyPathsThatSuppressWarning = {
configBaseUrl: true // used to fetch a config source, so we do not expect sources to be set when retrieving this value
};
// @private
this._configFetchPromise = null;
// @const
this.DEBUG_SOURCE_KEY = 'mtClientConfig_debugSource' + COMPOUND_SEPARATOR + this._topic;
// @const
this.CACHED_SOURCE_KEY = 'mtClientConfig_cachedSource' + COMPOUND_SEPARATOR + this._topic;
};
/**
* @return {Config} the default config instance, which is not associated with any topic
*/
Config.defaultConfig = function defaultConfig() {
if (!_defaultConfig) {
_defaultConfig = new Config(NO_TOPIC_KEY);
}
return _defaultConfig;
};
/**
************************************ PSEUDO-PRIVATE METHODS/IVARS ************************************
* These functions need to be accessible for ease of testing, but should not be used by clients
*/
Config.prototype._defaults = function _defaults() {
return DEFAULTS;
};
Config.prototype._setInitialized = function _setInitialized(initialized) {
this._initialized = initialized;
};
Config.prototype._setInitCalled = function _setInitCalled(initCalled) {
this._initCalled = initCalled;
};
Config.prototype._setShowedDebugWarning = function _setShowedDebugWarning(value) {
this._showedDebugWarning = value;
};
Config.prototype._setShowedNoProvidedSourceWarning = function _setShowedNoProvidedSourceWarning(value) {
this._showedNoProvidedSourceWarning = value;
};
/**
************************************ PUBLIC METHODS ************************************
*/
/**
* Allows replacement of one or more of this class' functions
* Any method on the passed-in object which matches a method that this class has will be called instead of the built-in class method.
* To replace *all* methods of his class, simply have your delegate implement all the methods of this class
* Your delegate can be a true object instance, an anonymous object, or a class object.
* Your delegate is free to have as many additional non-matching methods as it likes.
* It can even act as a delegate for multiple MetricsKit objects, though that is not recommended.
*
* "setDelegate()" may be called repeatedly, with the functions in the most-recently set delegates replacing any functions matching those in the earlier delegates, as well as any as-yet unreplaced functions.
* This allows callers to use "canned" delegates to get most of their functionality, but still replace some number of methods that need custom implementations.
* If, for example, a client wants to use the "canned" itml/environment delegate with the exception of, say, the "appVersion" method, they can set itml/environment as the delegate, and
* then call "setDelegate()" again with their own delegate containing only a single method of "appVersion" as the delegate, which would leave all the other "replaced" methods intact,
* but override the "appVersion" method again, this time with their own supplied delegate.
*
* NOTE: The delegate function will have a property called origFunction representing the original function that it replaced.
* This allows the delegate to, essentially, call "super" before or after it does some work.
* If a replaced method is overridden again with a subsequent "setDelegate()" call, the "origFunction" property will be the previous delegate's function.
* @example:
* To override one or more methods, in place:
* eventRecorder.setDelegate({recordEvent: itms.recordEvent});
* To override one or more methods with a separate object:
* eventRecorder.setDelegate(eventRecorderDelegate);
* (where "eventRecorderDelegate" might be defined elsewhere as, e.g.:
* var eventRecorderDelegate = {recordEvent: itms.recordEvent,
* sendMethod: 'itms'};
* To override one or more methods with an instantiated object from a class definition:
* eventRecorder.setDelegate(new EventRecorderDelegate());
* (where "EventRecorderDelegate" might be defined elsewhere as, e.g.:
* function EventRecorderDelegate() {
* }
* EventRecorderDelegate.prototype.recordEvent = itms.recordEvent;
* EventRecorderDelegate.prototype.sendMethod = function sendMethod() {
* return 'itms';
* };
* To override one or more methods with a class object (with "static" methods):
* eventRecorder.setDelegate(EventRecorderDelegate);
* (where "EventRecorderDelegate" might be defined elsewhere as, e.g.:
* function EventRecorderDelegate() {
* }
* EventRecorderDelegate.recordEvent = itms.recordEvent;
* EventRecorderDelegate.sendMethod = function sendMethod() {
* return 'itms';
* };
* @param {Object} Object or Class with delegate method(s) to be called instead of default (built-in) methods.
* @returns {Boolean} true if one or more methods on the delegate object match one or more methods on the default object,
* otherwise returns false.
*/
Config.prototype.setDelegate = function setDelegate(delegate) {
return reflect.attachDelegate(this, delegate);
};
/**
* Reset the attached delegates from
* @param delegate
*/
Config.prototype.resetDelegate = function resetDelegate() {
// reset the delegates from environment, network and logger
reflect.detachMethods(this);
// Detach the attached methods from prototype(source, debugSource and attached utility methods from mt-metricskit-utils-private, etc.) of the config instance
reflect.resetDelegates(this);
};
/**
* @return {String} the Figaro topic that this config corresponds with
* Most clients do not need to override this method
*/
Config.prototype.topic = function topic() {
return this._topic;
};
/**
* Returns the metrics config endpoint hostname
* Most clients do not need to override this method
* @deprecated
* @return {String} a hostname e.g.xp.apple.com
*/
Config.prototype.configHostname = function configHostname() {};
/**
* Returns a constructed URL to the metrics config endpoint for use with getConfig()
* Most clients do not need to override this method
* @deprecated
* @return {Promise} A Promise with a URL to the metrics config endpoint e.g. https://xp.apple.com/config/1/report/xp_its_main
*/
Config.prototype.configUrl = function configUrl() {
var configHostname = this.configHostname();
var returnUrlPromise;
if (configHostname) {
returnUrlPromise = Promise.resolve('https://' + configHostname + '/config/1/report');
} else {
returnUrlPromise = this.value('configBaseUrl');
}
return returnUrlPromise.then(
function (returnUrl) {
if (this._topic !== NO_TOPIC_KEY) {
returnUrl += '/' + this.topic();
} else {
this.logger.error('config.configUrl(): Topic must be provided');
}
return returnUrl;
}.bind(this)
);
};
/**
* This function will be used to access all of the sources for configuration data (e.g. disabled, blacklistedEvents, fieldsMap, etc.)
* THIS METHOD MUST BE PROVIDED BY A DELEGATE
* Returns an array of key/value objects (dictionaries) for all of the config sources (e.g. the bag, the page, the control parent, etc.).
* This method will be called frequently and repeatedly from the metrics.config.* functions.
* MetricsKit will use this return value to traverse the list of config objects, looking for config values.
* If later dictionaries of key/value pairs contain any keys already collected, the most late (farthest in the area) config value will overwrite earlier ones.
* IMPORTANT: This function might be called frequently and repeatedly so should be optimized for performance.
* It will be called frequently (rather than having this API provide a "setConfig" method for permanently setting the config values) since
* these config values can always be changing from one call to the next, so this ensures that they are current.
* THEREFORE: This function should NOT try to "simplify" by, e.g., merging all config sources into a single object to return when called.
* Doing so is an enormous amount of work to do each time MetricsKit needs to look up a single value.
* It is far more efficient for MetricsKit to simply interogate each configSource for the required key, rather than
* the delegate function merging *all* keys of *all* sources (looping through all values of all sources) in order to look up a single value.
* @example var sources = function() { return [itms.getBag().metrics, pageData.metrics.config]; }; // return an array of sources of app config
* @example var sources = function() { return metrics.utils.keyValue.sourcesArray(itms.getBag().metrics, pageData.metrics.config, swooshData.metrics.config); }; // Let MetricsKit help build the array from a varargs list of sources
* @example var sources = function() { return metrics.utils.keyValue.sourcesArray(existingArrayOfConfigSources, pageData.metrics.config, swooshData.metrics.config); }; // Let MetricsKit help build the array from a varargs list of sources where some args are already arrays of other sources (only works one level deep)
* @see metrics.system.configSources.sources for simple creation of the return value of config sources.
*/
Config.prototype.sources = function sources() {};
/**
* Search through the configuration sources provided by "metrics.system.configSources()", looking for the highest precedence value for "key"
* If no config sources provided, look for values in the DEFAULTS constant
* "keypath" can be a simple top-level config key such as "postFrequency" or a compound "path", such as fieldsMap.cookies
* @param {String} keyPath the dot-separated (".") path to the desired config value.
* @param {String} (optional) topic an 'override' topic which will override the main topic.
* @returns {Promise} A Promise of the value at the reached keypath. Returns "null" if the key or key's value is not found.
* Values found in later (farthest in array) dictionaries of key/value pairs overwrite earlier dictionaries.
* @see metrics.system.configSources.setDelegate()
*/
Config.prototype.value = function value(keyPath, topic) {
var getConfigValueFn = function () {
var cachedSource = this.cachedSource();
var serviceSource = this.serviceSource();
var configSourcesArray = this.sources();
var savedDebugSource = this.debugSource(); // NOTE: Always go through the accessor method, since it may need to be retrieved from localStorage
var sourceProvided = cachedSource || serviceSource || configSourcesArray || savedDebugSource;
var sourcesToCheck;
// show relevant warnings
if (!configSourcesArray && !serviceSource && !(keyPath in this._keyPathsThatSuppressWarning)) {
if (!this._showedNoProvidedSourceWarning) {
this._showedNoProvidedSourceWarning = true;
this.logger.warn(
'Metrics config: No config provided via delegate or fetched via init(), using cached config values.'
);
}
}
if (savedDebugSource) {
if (!this._showedDebugWarning) {
// We do this in case developers forget to clear this and wonder why the app isn't working correctly in normal running.
this._showedDebugWarning = true;
this.logger.warn(
'"debugSource" found.\nThis will override any same-named client-supplied configSource fields.\nThis setting "sticks" across session, use "setDebugSource(null)" to clear'
);
}
}
if (!reflect.isArray(configSourcesArray)) {
configSourcesArray = [configSourcesArray];
}
// disable the event only if there are no provided sources
// In case of fetch config failed and no cached config in local
if (keyPath === 'disabled') {
if (sourceProvided) {
sourcesToCheck = [cachedSource, serviceSource, configSourcesArray, savedDebugSource];
} else {
sourcesToCheck = [DEFAULTS];
}
} else {
// For non-disabling rules, check all sources
// Let "DEFAULTS" be overwritten by cachedSource, then serviceSource, then client-supplied configSources,
// and then let "savedDebugSource" overwrite everyone
sourcesToCheck = [DEFAULTS, cachedSource, serviceSource, configSourcesArray, savedDebugSource];
}
sourcesToCheck = this.configSourcesWithOverrides(sourcesToCheck, topic || this.topic());
// Pass each source as an individual argument; valueForKeyPath won't expand configSourcesArray if it is nested in sourcesToCheck
return keyValue.valueForKeyPath.apply(null, [keyPath].concat(sourcesToCheck));
}.bind(this);
if (this._configFetchPromise) {
return this._configFetchPromise.then(getConfigValueFn);
} else {
var value = getConfigValueFn();
return Promise.resolve(value);
}
};
/**
* Pushes any subsections within a config source to the front of the provided config sources array if the subsection key matches with the specified topic.
* This method is used by the default implementation of 'value(keyPath)' to determine precedence
* of config sources for the given topic.
* Subsections that are later in the array will take precedence over earlier subsections.
* Note that if one of the config sources is an array, this method will traverse one level deep
* to check for the presence of a dictionary that may contain a desired subsection.
* We traverse one level deep to maintain parity with _utils.keyValue.valueForKeyPath() which will be used to traverse the config sources
* @param {Array} configSources
* @param {String} topic
* @returns {Array} returnSources
*/
Config.prototype.configSourcesWithOverrides = function configSourcesWithOverrides(configSources, topic) {
var returnSources = configSources;
if (configSources && configSources.length && topic) {
returnSources = [];
for (var i = 0; i < configSources.length; i++) {
var source = configSources[i];
if (source) {
if (reflect.isArray(source) && source.length) {
var subarray = [];
for (var j = 0; j < source.length; j++) {
_appendSectionAndSubsectionToConfigSources(subarray, topic, source[j]);
}
returnSources.push(subarray);
} else {
_appendSectionAndSubsectionToConfigSources(returnSources, topic, source);
}
}
}
}
return returnSources;
};
/**
* Set's a "priority" configSource that will override any same-named client-supplied configSource fields.
* This can be done in code (e.g. in testcases) or, more typically, in Web Inspector when debugging or testing a running app (client) using MetricsKit.
* This is useful when testing, both in testcases and at runtime. One example would be to set a temporary "bag" structure that could then be tweaked at will, e.g. blacklisting fields, etc.
* This setting "sticks" across session so that it can be set, the app restarted, and the values will be present at the earliest runnings of the app.
* Use "setDebugSource(null)" to clear this value
* NOTE: If no "localStorage" is available (e.g. when testing), this value will only last for the session or until it is explicitly cleared.
* Here is an example of how to use this to test an app at runtime (and/or launch time)
* Run the app
* Open Web Inspector
* Set a variable to bag contents, e.g. var debugBag = itms.getBag();
* Call: metrics.config.setDebugSource(debugBag.metrics);
* enter: debugBag.metrics.disabled=true;
* Then do some things to generate events and make sure that:
* The app doesn’t crash
* No JavaScript events are generated in the console
* The events aren’t sent
* Reset that by entering: delete debugBag.metrics.disabled
* enter: debugBag.metrics.blacklistedEvents = [“page”, “click”];
* Then do some things to generate events and make sure that:
* The app doesn’t crash
* No JavaScript events are generated in the console
* Those events, and only those events, aren’t sent
* I save the object you set via metrics.config.setDebugSource to localStorage to facilitate testing at app startup, so remember to clear it out when you’re done or you’ll be confused why things aren’t working right in the future:
* metrics.config.setDebugSource();
* If there are values you want to be in effect at app-launch, just do the tweaking to the bag before your call to metrics.config.setDebugSource(debugBag.metrics);, passing in the tweaked bag.
* @param aDebugSource a plain old JavaScript object with keys and values which will be searched when config is requested.
* @returns {*} debugSource
*/
Config.prototype.setDebugSource = function setDebugSource(aDebugSource) {
this._debugSource = aDebugSource || null;
return storage.saveObjectToStorage(this.environment.localStorageObject(), this.DEBUG_SOURCE_KEY, this._debugSource);
};
/**
* Return any previously set debugSource which would be stored in localStorage.
* If not present in localStorage, the class variable value of debugSource will be returned.
* @returns {*} debugSource
*/
Config.prototype.debugSource = function debugSource() {
if (this._debugSource) ; else {
// Otherwise look in localStorage for one...
this._debugSource = storage.objectFromStorage(this.environment.localStorageObject(), this.DEBUG_SOURCE_KEY);
}
return this._debugSource;
};
/**
* Save a source to localStorage which will have config values that can be used in the next visit until a fresh config is fetched
* @param {Object} aSource
* @return {Object}
*/
Config.prototype.setCachedSource = function setCachedSource(aSource) {
this._cachedSource = aSource || null;
return storage.saveObjectToStorage(
this.environment.localStorageObject(),
this.CACHED_SOURCE_KEY,
this._cachedSource
);
};
/**
* Return any previously set savedSource which would be stored in localStorage.
* The class variable value of savedSource will be returned if non-null to avoid expensive reads from disk.
* @return {Object}
*/
Config.prototype.cachedSource = function cachedSource() {
if (this._cachedSource) ; else {
// Otherwise look in localStorage for one...
this._cachedSource = storage.objectFromStorage(this.environment.localStorageObject(), this.CACHED_SOURCE_KEY);
}
return this._cachedSource;
};
/**
* Set a source, typically one that was fetched from the config endpoint,
* which will have config values that can be overwritten by clients via config.setDelegate
* @param {Object} aServiceSource
* @deprecated
* @return {Object}
*/
Config.prototype.setServiceSource = function setServiceSource(aServiceSource) {
this._serviceSource = aServiceSource;
return this._serviceSource;
};
/**
* Returns a config source that was retrieved from the metrics config service endpoint
* @deprecated
* @return {Object}
*/
Config.prototype.serviceSource = function serviceSource() {
return this._serviceSource;
};
/**
* Initialize config by setting config delegate or fetching it from the config endpoint as necessary
* If we wanted config to persist across page turns, we could save it via setCachedSource and fetch it every time we wake up,
* but we expect most clients to be single page apps
*
* @param {Function} (optional) configSourcesFn - a function that returns an array of key/value objects (dictionaries) for all of the config sources
* (e.g. the bag, the page, the control parent, etc.).
* @return {Promise} A Promise for the Config initialization. Returns an rejected Promise if failed to fetch config from server
*/
Config.prototype.init = function init(configSourcesFn) {
var isDefaultConfig = this._topic === NO_TOPIC_KEY || !reflect.isFunction(configSourcesFn);
if (isDefaultConfig) {
this.logger.warn(
'config.init(): Falling back to default config because configSourcesFn or a valid topic was not provided'
);
}
// default config does not need to initialize
if (this._initCalled || isDefaultConfig) {
return Promise.resolve(this);
}
this._initCalled = true;
var self = this;
this._configFetchPromise = Promise.resolve(configSourcesFn())
.then(function (configSources) {
self.setDelegate({
sources: function sources() {
return configSources;
}
});
self._initialized = true;
return self;
})
.catch(function (error) {
self._initCalled = false;
self._initialized = false;
throw error;
});
return this._configFetchPromise;
};
/**
* Release resources of the config
*/
Config.prototype.cleanup = function cleanup() {
this._initCalled = this._initialized = false;
this.setCachedSource();
this.setDebugSource();
this.resetDelegate();
this.environment = null;
this.network = null;
this.logger = null;
this._topic = null;
this._debugSource = null;
this._cachedSource = null;
this._serviceSource = null;
this._initCalled = false;
this._initialized = false;
this._showedDebugWarning = false;
this._showedNoProvidedSourceWarning = false;
this._configFetchPromise = null;
};
/**
* Indicates whether or not config has initialized.
* Initialization is accomplished in one of the following ways:
* 1) a service source is set via a call to config.setServiceSource() TODO: Deprecated
* 2) a source function delegate is set via config.setDelegate()
* @return {Boolean}
*/
Config.prototype.initialized = function initialized() {
return this._initialized;
};
/*
* src/impls/metrics_config.js
* mt-client-config
*
* Copyright © 2020 Apple Inc. All rights reserved.
*
*/
/**
* Metrics config implementation for Config
* This class is a subclass of Config to provide the business methods for metrics collection
* @param topic
* @constructor
*/
var MetricsConfig = function MetricsConfig(topic) {
Config.call(this, topic);
};
MetricsConfig.prototype = Object.create(Config.prototype);
MetricsConfig.prototype.constructor = MetricsConfig;
/**
************************************ PUBLIC METHODS/IVARS ************************************
*/
/**
* Boolean config value which, when "true", tells clients to avoid all metrics code paths (different than simply not sending metrics).
* Useful for avoiding discovered client bugs.
* NOTE1: This will cause unrecoverable event loss, as the clients will not be recording events at all.
* NOTE2: Typically all event_handlers will check for this in addition to "recordEvent()" checking because that way
* if a client overrides "recordEvent", these checks will still take effect.
* We also test it in recordEvent() in case someone creates their own event_handler, we'd still want to exclude what needs to be excluded.
* @param {String} (optional) topic an 'override' topic which will override the main topic.
* @returns {Promise}
*/
MetricsConfig.prototype.disabled = function disabled(topic) {
return this.value('disabled', topic).then(function (disabled) {
return !!disabled;
});
};
/** @DEPERECATED per Inclusive Software Efforts; use denylistedEvents instead
* Array config value which instructs clients to avoid sending particular event types.
* Useful for reducing server processing in emergencies by abandoning less-critical events.
* Useful for dealing with urgent privacy concerns, etc., around specific events.
* NOTE1: This will cause unrecoverable event loss, as the clients will not be recording events at all.
* NOTE2: Typically all event_handlers will check for this in addition to "recordEvent()" checking because that way
* if a client overrides "recordEvent", these checks will still take effect.
* We also test it in recordEvent() in case someone creates their own event_handler, we'd still want to exclude what needs to be excluded, in case they don't.
* @param {String} (optional) topic an 'override' topic which will override the main topic.
* @returns {Promise} Guaranteed to always return a Promise with the valid array, though the array may be empty if the value was unset in config
*/
MetricsConfig.prototype.blacklistedEvents = function blacklistedEvents(topic) {
return this.denylistedEvents(topic);
};
/**
* Array config value which instructs clients to avoid sending particular event types.
* Useful for reducing server processing in emergencies by abandoning less-critical events.
* Useful for dealing with urgent privacy concerns, etc., around specific events.
* NOTE1: This will cause unrecoverable event loss, as the clients will not be recording events at all.
* NOTE2: Typically all event_handlers will check for this in addition to "recordEvent()" checking because that way
* if a client overrides "recordEvent", these checks will still take effect.
* We also test it in recordEvent() in case someone creates their own event_handler, we'd still want to exclude what needs to be excluded, in case they don't.
* @param {String} (optional) topic an 'override' topic which will override the main topic.
* @returns {Promise} Guaranteed to always return a Promise with the valid array, though it may be empty if the value was unset in config
*/
MetricsConfig.prototype.denylistedEvents = function denylistedEvents(topic) {
var blacklistedEventsArray = this.value('blacklistedEvents', topic)
.then(function (returnArray) {
return returnArray || [];
})
.catch(function () {
return [];
});
var denylistedEventsArray = this.value('denylistedEvents', topic)
.then(function (returnArray) {
return returnArray || [];
})
.catch(function () {
return [];
});
return Promise.all([blacklistedEventsArray, denylistedEventsArray]).then(function (outputs) {
var blacklistedEventsArray = outputs[0];
var denylistedEventsArray = outputs[1];
return dedupedArray(blacklistedEventsArray, denylistedEventsArray);
});
};
/**
* Returns a deduped array (similar to a Set object) using the contents from both arrayA and arrayB
* @param {Array} arrayA the first array to dedupe
* @param {Array} arrayB the other array to dedupe
* @return {Array} The deduped array
*/
function dedupedArray(arrayA, arrayB) {
var tempDict = {}; // necessary for returning array of unique values and not having access to Set object in ES5
var returnArray = [];
if (arrayA) {
for (var i = 0; i < arrayA.length; i++) {
tempDict[arrayA[i]] = 0; // value for key doesn't matter; we want a list of unique values
}
}
if (arrayB) {
for (var j = 0; j < arrayB.length; j++) {
tempDict[arrayB[j]] = 0; // value for key doesn't matter; we want a list of unique values
}
}
returnArray = Object.keys(tempDict);
return returnArray;
}
/**
* Array config value which instructs clients to avoid sending particular event fields.
* Useful for dealing with urgent privacy concerns, etc., around specific event fields (e.g. dsid)
* NOTE: Typically all event_handlers will check for this in addition to "recordEvent()" checking because that way
* if a client overrides "recordEvent", these checks will still take effect.
* We also test it in recordEvent() in case someone creates their own event_handler, we'd still want to exclude what needs to be excluded, in case they don't.
* @param {String} (optional) topic an 'override' topic which will override the main topic.
* @returns {Promise} Guaranteed to always return a Promise with the valid array, though it may be empty if the value was unset in config
*/
MetricsConfig.prototype.blacklistedFields = function blacklistedFields(topic) {
return this.denylistedFields(topic);
};
/**
* Array config value which instructs clients to avoid sending particular event fields.
* Useful for dealing with urgent privacy concerns, etc., around specific event fields (e.g. dsid)
* NOTE: Typically all event_handlers will check for this in addition to "recordEvent()" checking because that way
* if a client overrides "recordEvent", these checks will still take effect.
* We also test it in recordEvent() in case someone creates their own event_handler, we'd still want to exclude what needs to be excluded, in case they don't.
* @param {String} (optional) topic an 'override' topic which will override the main topic.
* @returns {Promise} Guaranteed to always return a Promise valid array, though it may be empty if the value was unset in config
*/
MetricsConfig.prototype.denylistedFields = function denylistedFields(topic) {
var blacklistedFieldsArray = this.value('blacklistedFields', topic)
.then(function (returnArray) {
return returnArray || [];
})
.catch(function () {
return [];
});
var denylistedFieldsArray = this.value('denylistedFields', topic)
.then(function (returnArray) {
return returnArray || [];
})
.catch(function () {
return [];
});
return Promise.all([blacklistedFieldsArray, denylistedFieldsArray]).then(function (outputs) {
var blacklistedFieldsArray = outputs[0];
var denylistedFieldsArray = outputs[1];
return dedupedArray(blacklistedFieldsArray, denylistedFieldsArray);
});
};
/** @DEPRECATED per Inclusive Software Efforts; use removeDenylistedFields instead
* Remove all blacklisted fields from the passed-in object.
* IMPORTANT: This action is performed in-place for performance of not having to create new objects each time.
* NOTE: Typically all event_handlers will call this in addition to "recordEvent()" calling it because that way
* if a client overrides "recordEvent", these checks will still take effect.
* We also test it in recordEvent() in case someone creates their own event_handler, we'd still want to exclude what needs to be excluded, in case they don't.
* @param {Object} eventFields a dictionary of event data
* @param {String} (optional) topic an 'override' topic which will override the main topic.
* @returns {Promise} the passed-in object with any blacklisted fields removed
*/
MetricsConfig.prototype.removeBlacklistedFields = function removeBlacklistedFields(eventFields, topic) {
return this.removeDenylistedFields(eventFields, topic);
};
/**
* Remove all denylisted fields from the passed-in object.
* IMPORTANT: This action is performed in-place for performance of not having to create new objects each time.
* NOTE: Typically all event_handlers will call this in addition to "recordEvent()" calling it because that way
* if a client overrides "recordEvent", these checks will still take effect.
* We also test it in recordEvent() in case someone creates their own event_handler, we'd still want to exclude what needs to be excluded, in case they don't.
* @param {Object} eventFields a dictionary of event data
* @param {String} (optional) topic an 'override' topic which will override the main topic.
* @returns {Promise} the passed-in object with any denylisted fields removed
*/
MetricsConfig.prototype.removeDenylistedFields = function removeDenylistedFields(eventFields, topic) {
if (eventFields) {
return this.denylistedFields(topic).then(function (denylistedFieldsArray) {
for (var ii = 0; ii < denylistedFieldsArray.length; ii++) {
var aDenylistedField = denylistedFieldsArray[ii];
// Double check this is not null (or empty string), or "delete" will blow up...
if (aDenylistedField) {
if (aDenylistedField in eventFields) {
delete eventFields[aDenylistedField];
}
}
}
return eventFields;
});
} else {
return Promise.resolve(eventFields);
}
};
/** @DEPRECATED per Inclusive Software Efforts; use metricsDisabledOrDenylistedEvent instead
* Convenience function used by event handlers to determine if they should build and return metricsData.
* NOTE: Typically all event_handlers will check for this in addition to "recordEvent()" checking because that way
* if a client overrides "recordEvent", these checks will still take effect.
* We also test it in recordEvent() in case someone creates their own event_handler, we'd still want to exclude what needs to be excluded, in case they don't.
* @param {String} anEventType
* @param {String} (optional) topic an 'override' topic which will override the main topic.
* @returns {Promise} returns "true" if <b>either</b> "disabled()" is true or "blacklistedEvents()" contains this eventType
*/
MetricsConfig.prototype.metricsDisabledOrBlacklistedEvent = function metricsDisabledOrBlacklistedEvent(
anEventType,
topic
) {
return this.metricsDisabledOrDenylistedEvent(anEventType, topic);
};
/**
* Convenience function used by event handlers to determine if they should build and return metricsData.
* NOTE: Typically all event_handlers will check for this in addition to "recordEvent()" checking because that way
* if a client overrides "recordEvent", these checks will still take effect.
* We also test it in recordEvent() in case someone creates their own event_handler, we'd still want to exclude what needs to be excluded, in case they don't.
* @param {String} anEventType
* @param {String} (optional) topic an 'override' topic which will override the main topic.
* @returns {Boolean} returns "true" if <b>either</b> "disabled()" is true or "denylistedEvents()" contains this eventType
*/
MetricsConfig.prototype.metricsDisabledOrDenylistedEvent = function metricsDisabledOrDenylistedEvent(
anEventType,
topic
) {
return this.disabled(topic).then(
function (disabled) {
return (
disabled ||
(anEventType
? this.denylistedEvents(topic).then(function (denylistedEvents) {
return denylistedEvents.indexOf(anEventType) > -1;
})
: false)
);
}.bind(this)
);
};
/**
* Config map which instructs clients to de-res (lower the resolution of) particular event fields.
* The Privacy team typically requires device capacity information to be de-resed.
* @param {String} (optional) topic an 'override' topic which will override the main topic.
* @returns {Promise} An array of config objects { fieldName, (optional) magnitude, (optional) significantDigits }
* Guaranteed to always return a valid array, though it may be empty if the value was unset in config
*/
MetricsConfig.prototype.deResFields = function deResFields(topic) {
return this.value('deResFields', topic).then(function (returnArray) {
return returnArray || [];
});
};
/**
* De-res appropriate fields in the passed-in object by lowering the resolution of those field values.
* For example, a raw number of bytes "de-res"'d to MB, but without the "floor" filter, would look like these examples:
* 31708938240/1024/1024 ==> 30240
* 15854469120/1024/1024 ==> 15120
* 63417876480/1024/1024 ==> 60480
*
* With the "floor" formula we replace the two least significant digits with "00"
* Doing so will convert values like so:
*
* 31708938240/1024/1024 ==> 30200
* 15854469120/1024/1024 ==> 15100
* 63417876480/1024/1024 ==> 60400
*
* IMPORTANT: This action is performed in-place for performance of not having to create new objects each time.
* NOTE: Be careful not to call this method more than once for a given event, as de-resing a number more than
* once can lead to inaccurate reporting (numbers will likely be smaller than their real values)
* @param {Object} eventFields a dictionary of event data
* @param {String} (optional) topic an 'override' topic which will override the main topic.
* @returns {Promise} the passed-in object with any fields de-resed
*/
MetricsConfig.prototype.applyDeRes = function applyDeRes(eventFields, topic) {
if (eventFields) {
return this.deResFields(topic).then(function (deResFieldsConfigArray) {
var fieldName;
deResFieldsConfigArray.forEach(function (deResFieldConfig) {
fieldName = deResFieldConfig.fieldName;
if (fieldName in eventFields) {
eventFields[fieldName] = number.deResNumber(
eventFields[fieldName],
deResFieldConfig.magnitude,
deResFieldConfig.significantDigits
);
}
});
return eventFields;
});
} else {
return Promise.resolve(eventFields);
}
};
export default Config;
export { MetricsConfig };
|