summaryrefslogtreecommitdiff
path: root/shared/metrics-8/node_modules/@amp-metrics/mt-metricskit-processor-clickstream/dist/mt-metricskit-processor-clickstream.esm.js
blob: 517960ff03a8492e365865d40607429a0782b55b (plain)
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
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
import { reflect as reflect$1, string as string$1, cookies, eventFields, delegatesInfo, keyValue, network } from '@amp-metrics/mt-metricskit-utils-private';
import Constraints, { connectConstraintConfig } from '@amp-metrics/mt-client-constraints';
import { system, eventHandlers } from '@amp-metrics/ae-client-kit-core';
import { loggerNamed } from '@amp-metrics/mt-client-logger-core';

var info = { version: '8.6.3', name: 'mt-metricskit-processor-clickstream' };

/*
 *  src/metrics/utils/delegate_extension.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2016 Apple Inc. All rights reserved.
 *
 */
/*
 * Delegate info functions to be used by _utils.reflect.attachDelegate
 */
var delegateInfo = {
    /**
     * Returns the name of this repository
     * Used by _utils.reflect.attachDelegate to create
     * a delegate dependence tree for the optional
     * base field, xpDelegatesInfo
     * @returns {String} Name of this repository
     */
    mtName: function () {
        return info.name;
    },
    /**
     * Returns version of this repo
     * Used by _utils.reflect.attachDelegate to create
     * a delegate dependence tree for the optional
     * base field, xpDelegatesInfo
     * @returns {String} Version of this repo
     */
    mtVersion: function () {
        return info.version;
    }
};

/**
 * Delegate-related functions (intended to eventually contain
 * all needed functions to be delegateable, like 'setDelegate')
 * @constructor
 */
var delegateExtension = {
    /**
     * Adds delegate info methods to the target (delegateable) object
     * @param {Object} targetObj Delegateable object to attach info methods to
     */
    attachDelegateInfo: function (targetObj) {
        reflect$1.extend(targetObj, delegateInfo);
    }
};

/*
 *  src/merics/config.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2015-2016 Apple Inc. All rights reserved.
 *
 */

/**
 * Extend the metrics config instance with convenience functions and delegate info
 * This should be done for every config instance that MetricsKit uses:
 * once for the default config, and once for the topic-specific config if metrics.init() is used
 * @param {Config} configInstance
 */
function initializeConfig(configInstance) {
    connectConstraintConfig(configInstance);
    delegateExtension.attachDelegateInfo(configInstance);
}

function cleanupConfig(topicConfig) {
    topicConfig.cleanup();
}

/*
 *  src/metrics/utils/constants.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2019 Apple Inc. All rights reserved.
 *
 */

var BASE_FIELDS$1 = [
    'constraintProfile',
    'constraintProfiles',
    'clientId',
    'isSignedIn',
    'page',
    'pageContext',
    'pageDetails',
    'pageId',
    'pageType',
    'xpVersionMetricsKit',
    'xpDelegatesInfo'
];

var ENVIRONMENT_REQUIRED_FIELDS = [
    'capacityData',
    'capacityDataAvailable',
    'capacityDisk',
    'capacitySystem',
    'capacitySystemAvailable',
    'dsId',
    'hostApp',
    'pageUrl',
    'pixelRatio',
    'userType',
    'windowInnerHeight',
    'windowInnerWidth',
    'windowOuterHeight',
    'windowOuterWidth'
];

var ENVIRONMENT_OPTIONAL_FIELDS = [
    'browser',
    'consumerId',
    'consumerNs',
    'hostAppVersion',
    'parentPageUrl',
    'userId',
    'xpUserIdSyncState',
    'xpAccountsMatch'
];

// These constants are used internally but not exposed publicly
var constants = {
    METRICS_KIT_BASE_FIELDS: BASE_FIELDS$1.concat(ENVIRONMENT_REQUIRED_FIELDS, ENVIRONMENT_OPTIONAL_FIELDS),
    // Used to remove the fields which are not base field in MetricsKit
    IGNORED_BASE_FIELDS: [
        'osLanguages' // only available in "enter" event handler
    ],
    REQUIRED_ENVIRONMENT_FIELD_NAMES: ENVIRONMENT_REQUIRED_FIELDS.concat('connectionType'),
    OPTIONAL_ENVIRONMENT_FIELD_NAMES: ENVIRONMENT_OPTIONAL_FIELDS.concat(['clientId', 'cookie', 'osLanguages']) // This is an optional field in MetricsKit, but a required field in client-kit-core
};

/*
 *  src/metrics/system/environment.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2015 Apple Inc. All rights reserved.
 *
 */

var Environment = system.Environment;
var exceptionString$1 = string$1.exceptionString;
var REQUIRED_ENVIRONMENT_FIELD_NAMES = constants.REQUIRED_ENVIRONMENT_FIELD_NAMES;
var OPTIONAL_ENVIRONMENT_FIELD_NAMES = constants.OPTIONAL_ENVIRONMENT_FIELD_NAMES;
var _prototypeInitialized = false;
var noOp = function () {};

/**
 * 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.
 * DEFAULT implementation: console logging
 * @see setDelegate
 * @delegatable
 * @constructor
 */
var MetricsKitEnvironment = function MetricsKitEnvironment() {
    Environment.apply(this, arguments);
    if (!_prototypeInitialized) {
        _prototypeInitialized = true;
        REQUIRED_ENVIRONMENT_FIELD_NAMES.forEach(function (fieldName) {
            MetricsKitEnvironment.prototype[fieldName] = function () {
                throw exceptionString$1('metrics.system.environment', fieldName);
            };
        });

        OPTIONAL_ENVIRONMENT_FIELD_NAMES.forEach(function (fieldName) {
            MetricsKitEnvironment.prototype[fieldName] = noOp;
        });
    }
};

MetricsKitEnvironment.prototype = new Environment();
MetricsKitEnvironment.prototype.constructor = MetricsKitEnvironment;

/**
 ************************************ 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.
 */
MetricsKitEnvironment.prototype.setDelegate = function setDelegate(delegate) {
    // This is a bit of a cheat, but it allows us to not force our users to have a whole delegate just for cookies...
    // we let them merge it in with their environment delegate:
    cookies.setDelegate(delegate);
    return reflect$1.attachDelegate(this, delegate);
};

/*
 *  src/metrics/system/event_recorder.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2015 Apple Inc. All rights reserved.
 *
 */

/**
 * Provides a replaceable "recordEvent" function to enqueue events to be sent to the metrics server.
 * The functionality in this class is typically replaced via a delegate.
 * DEFAULT implementation: error logged via logger.
 * @see setDelegate
 * @delegatable
 * @constructor
 */
var EventRecorder = function EventRecorder() {};

/**
 ************************************ 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.
 */
EventRecorder.prototype.setDelegate = function setDelegate(delegate) {
    return reflect$1.attachDelegate(this, delegate);
};

/**
 * Enqueues a JSON an event as JSON
 * NO DEFAULT IMPLEMENTATION... THIS METHOD MUST BE REPLACED
 * @param {String} topic defines the Figaro "topic" that this event should be stored under
 * @param {Promise|Object} eventFields a Promise/JavaScript object which will be converted to a JSON string and enqued for sending to Figaro according to the postFrequency schedule.
 * @returns {Object} the recorded event, or "null" if no object was recorded (e.g. if "eventFields" is null, or "disabled" is true, eventFields.eventType is one of the blacklistedEvents, etc.)
 * @overridable
 */
EventRecorder.prototype.recordEvent = function recordEvent(topic, eventFields) {
    // Don't wrap this in a helper function or the backtrace won't be as nice.
    throw string$1.exceptionString('metrics.system.event_recorder', 'recordEvent');
};

/**
 * The methodology being used to send batches of events to the server
 * This field should be hardcoded in the client based on what method it is using to encode and send its events to Figaro.
 * The three typical values are:
 *      "itms" - use this value when/if JavaScript code enqueues events for sending via the "itms.recordEvent()" method in ITML.
 *      "itunes" - use this value when/if JavaScript code enqueues events by calling the "iTunes.recordEvent()" method in Desktop Store apps.
 *      "javascript" - use this value when/if JavaScript code enqueues events for sending via the JavaScript eventQueue management. This is typically only used by older clients which don't have the built-in functionality of itms or iTunes available to them.
 * NO DEFAULT IMPLEMENTATION... THIS METHOD MUST BE REPLACED
 * @example "itms", "itunes", "javascript"
 * @returns {String}
 * @overridable
 */
EventRecorder.prototype.sendMethod = function sendMethod() {
    // Don't wrap this in a helper function or the backtrace won't be as nice.
    throw string$1.exceptionString('metrics.system.event_recorder', 'sendMethod');
};

/**
 * Sends any remaining events in the queue, then clears it
 * NO DEFAULT IMPLEMENTATION... THIS METHOD SHOULD BE REPLACED IF THE DELEGATE ENVIRONMENT SUPPORTS IT
 * @param {Boolean} appIsExiting - if events are being flushed due to your app exiting (or page going away for web-apps), pass "true".
 *                  This allows MetricsKit to modify its flush strategy to attempt to post events prior to actual termination.
 *                  In cases where appIsExiting==false, the parameter may be omitted.
 */
EventRecorder.prototype.flushUnreportedEvents = function flushUnreportedEvents(appIsExiting) {};

/*
 *  src/metrics/system/logger.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2015 Apple Inc. All rights reserved.
 *
 */
var logger = loggerNamed('mt-metricskit-processor-clickstream');

/*
 *  src/metrics/system/index.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2015 Apple Inc. All rights reserved.
 *
 */

var System = function System() {
    this.environment = new MetricsKitEnvironment();
    this.eventRecorder = new EventRecorder();
    this.logger = logger;

    for (var key in this) {
        delegateExtension.attachDelegateInfo(this[key]);
    }
};

/*
 *  src/utils/metrics_data.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2020 Apple Inc. All rights reserved.
 *
 */

/**
 *
 * @param props
 * @param props.processor
 * @param props.eventMetricsDataPromise
 * @constructor
 */
var MetricsData = function MetricsData(props) {
    // @private
    this._processor = props.processor;
    // @private
    this._eventMetricsDataPromise = props.eventMetricsDataPromise;
};

/**
 ************************************ 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.
 *
 * "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.
 */
MetricsData.prototype.setDelegate = function setDelegate(delegate) {
    return reflect$1.attachDelegate(this, delegate);
};

MetricsData.prototype.toJSON = function toJSON() {
    return this._eventMetricsDataPromise.catch(
        function (err) {
            this._processor.system.logger.error('An error occurred when generating Metrics Data. Error: \n' + err);
            return null; // return null to ignore the event
        }.bind(this)
    );
};

/**
 * Enqueues the event data to the topic queue
 * @param {String} topic defines the Figaro "topic" that this event should be stored under
 * @returns {Promise} a Promise that includes the recorded event or "null" if no object was recorded (e.g. if "eventFields" is null, or "disabled" is true, eventFields.eventType is one of the blacklistedEvents, etc.)
 */
MetricsData.prototype.recordEvent = function recordEvent(topic) {
    var vargs = Array.prototype.slice.call(arguments, 1);
    return this._processor.system.eventRecorder.recordEvent.apply(
        this._processor.system.eventRecorder,
        [topic, this.toJSON()].concat(vargs)
    );
};

/*
 *  src/metrics/event_handlers/click_stream_event_handler.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2021 Apple Inc. All rights reserved.
 *
 */

var exceptionString = string$1.exceptionString;
var ClickStreamEventHandler = function ClickStreamEventHandler(clickstreamProcessor) {
    // @private
    this._processor = clickstreamProcessor;
};

/**
 ************************************ 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 PerfKit 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.
 * @return {Boolean} true if one or more methods on the delegate object match one or more methods on the default object,
 * otherwise returns false.
 */
ClickStreamEventHandler.prototype.setDelegate = function setDelegate(delegate) {
    return reflect$1.attachDelegate(this, delegate);
};

/**
 * Returns all the fields that this eventHandler knows about.
 * The eventHandler may have accessor functions which derive some of these fields.
 * The "metricsData()" method will use this list of fields to attempt to invoke accessor methods to get field values.
 * Therefore, if callers override this function, and add additional values, and provide accessors for those values, then
 * the "metricsData()" function will ultimately call those accessors as well.
 * @return all the fields that this eventHandler knows about
 * @overridable
 * NOTE: this method must be overridden by the sub class
 */
ClickStreamEventHandler.prototype.knownFields = function knownFields() {
    throw exceptionString('ClickStreamEventHandler', 'knownFields');
};

/**
 * The type of event this is
 * @returns {String}
 * @overridable
 * NOTE: this method must be overridden by the sub class
 */
ClickStreamEventHandler.prototype.eventType = function (callerSuppliedEventFields) {
    throw exceptionString('ClickStreamEventHandler', 'eventType');
};

/**
 * All of the various eventHandlers invoke this method to generate their metrics data
 * The data is a simple map object (dictionary) with all the fields required by Figaro for that event
 * Some fields can be derived by this class itself.
 * Some fields need to be provided by callers (e.g. pageId, pageType, pageContext)
 * This function expects to be called with the correct context (eg base.processMetricsData.apply(this, arguments))
 * @param {varargs} callerSuppliedEventFieldsMapN a variable number of Object arguments from 0-N, each containing key/value pairs representing event fields to include with the returned metricsData
 * This method will check for any disabled/blacklisted events or fields, add base fields, and process/merge all data
 * @returns {Object} key/value pairs of all "page" fields + "base" fields required by Figaro
 * WARNING: May return "null" if metrics and/or the specific eventType for this handler is disabled, or on error.
 */
ClickStreamEventHandler.prototype.processMetricsData = function processMetricsData(
    pageId,
    pageType,
    pageContext /*, callerSuppliedEventFieldsMapN(varargs) */
) {
    var callArguments = arguments;
    var callerSuppliedEventFieldsMapsArray = Array.prototype.slice.call(callArguments, 3);
    var eventType = this.eventType(callerSuppliedEventFieldsMapsArray);
    var config = this._processor.config;
    var constraints = this._processor._constraints;
    var logger = this._processor.system.logger;

    var eventMetricsDataPromise = config
        .metricsDisabledOrBlacklistedEvent(eventType)
        .then(function (disabled) {
            if (disabled) {
                throw 'event was disabled';
            }
        })
        .then(
            function () {
                var includeBaseFields =
                    typeof this.mtIncludeBaseFields == 'function' ? this.mtIncludeBaseFields() : true;
                var baseEventFields = null;
                if (includeBaseFields) {
                    // Get the base fields from the base event handler
                    var baseEventHandler = this._processor.eventHandlers.base;
                    baseEventFields = baseEventHandler.metricsData.apply(baseEventHandler, callArguments);
                } else {
                    baseEventFields = {};
                }

                return baseEventFields;
            }.bind(this)
        )
        .then(
            function (baseMetricsFields) {
                var valueHandlerTasks = [];
                callerSuppliedEventFieldsMapsArray = [baseMetricsFields].concat(callerSuppliedEventFieldsMapsArray);
                var eventFieldPromises = eventFields.processMetricsData(
                    this,
                    this.knownFields(),
                    true,
                    callerSuppliedEventFieldsMapsArray
                );
                var metricsData = {};
                Object.keys(eventFieldPromises).forEach(function (field) {
                    var fieldValue = eventFieldPromises[field];
                    var valueHandler = Promise.resolve(fieldValue).then(function (value) {
                        metricsData[field] = value;
                    });
                    valueHandlerTasks.push(valueHandler);
                });

                return Promise.all(valueHandlerTasks).then(function () {
                    return metricsData;
                });
            }.bind(this)
        )
        .then(function (eventFields) {
            return constraints.applyConstraintTreatments(eventFields);
        })
        .then(function (eventFields) {
            return config.removeBlacklistedFields(eventFields);
        })
        .then(function (eventFields) {
            return config.applyDeRes(eventFields);
        })
        .catch(
            function (e) {
                logger.error(
                    'MetricsKit: Unable to generate the event (' +
                        this.eventType(callerSuppliedEventFieldsMapsArray) +
                        ') for the topic ' +
                        this._processor.config.topic() +
                        ', due to ' +
                        e
                );
                return null;
            }.bind(this)
        );

    return new MetricsData({
        processor: this._processor,
        eventMetricsDataPromise: eventMetricsDataPromise
    });
};

/*
 *  src/metrics/event_handlers/account.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2015 Apple Inc. All rights reserved.
 *
 */

/**
 * Creates and returns an object (key/value data map (dictionary)) containing all of the fields needed for this metrics event.
 * To override any functionality in this class, use the "setDelegate() method in order to override the specific functions that need customization.
 * @delegatable
 * @constructor
 */
var Account = function (metricsKit) {
    ClickStreamEventHandler.apply(this, arguments);
};

Account.prototype = Object.create(ClickStreamEventHandler.prototype);
Account.prototype.constructor = Account;

/**
 ************************************ 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.
 */
Account.prototype.setDelegate = function setDelegate(delegate) {
    return reflect$1.attachDelegate(this, delegate);
};

/**
 * Creates a simple map object (dictionary) with all the fields required by Figaro for this event
 * Some fields can be derived by this class itself.
 * Some fields need to be provided by callers (e.g. pageId, pageType, pageContext)
 * @param {String} pageId required for all event creation. Indicates the id of the page this event took place on.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * The type of ID may vary (e.g. adam id, grouping id, result id, etc), but is generally
 * the identifier in some persistent store. Search Results pages may have a pageId which refers to their specific dataSet,
 * otherwise known as dataSetId. If the page is better identified by a descriptive string rather than a content ID,
 * this field may be hard-coded, but it should be unique within the set of pages displayable by the app.
 * If an application is not client/server "page" oriented (where the client needs to request data from the server for each "page" of the app), then
 * this field would be generated by the client.
 * Note: A unique "page" value will created by concatenating pageType+"_"+pageId
 * @param {String} pageType required for all event creation. Indicates the type of page this event took place on.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * This value should represent the group of pages (e.g. "Genre", “Album”, “Grouping”, "Picker", "Recommendations", "Feed",
 * "Search", "Subscribe", etc.).
 * If an application is not client/server "page" oriented (where the client needs to request data from the server for each "page" of the app), then
 * this field would be generated by the client (potentially being hard-coded).
 * Note: A unique "page" value will created by concatenating pageType+"_"+pageId
 * @param {String} pageContext required for all event creation. Indicates the context within which a page is viewed.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * Contexts usually provide independent streams of activity and can typically appear as UI "tab" elements or primary navigation elements.
 * @example: iTunes Desktop: “InTheStore” or “Main”.
 * @example: iOS iTunes apps: tab name (e.g. “Featured”, “TopCharts”, etc)
 * @example: iOS Store sheets:  “Sheet” (e.g. AppStore page launched as a sheet within Mail, Springboard’s “Near Me”, Maps’ “Nearby Apps”)
 * @example a "hint", "related" click, "filter" click, etc.
 * If this event is representing a plain typed account, this field's value may be null
 * @param {varargs} callerSuppliedEventFieldsMapN a variable number of Object arguments from 0-N, each containing key/value pairs representing event fields to include with the returned metricsData
 * All event fields will be merged.
 * An attempt will be made to invoke an accessor method for each field, providing the caller the opportunity to override accessor methods.
 * If no accessor method is found, the event field value will be included in the returned metricsData as-is.
 * Later objects take precedence over earlier ones, overriding any field value that may have already been there.
 * If this parameter is null or omitted, only the known page fields will be included
 * @example metrics.eventHandlers.page.metricsData(appData.pageId, appData.pageType, appData.pageContext, element, {some:"some", known:"known", eventFieldValues:"eventFieldValues"}; someOtherKnownEventValues, appData.someAdditionalBaseFieldValues);
 * @returns key/value pairs of all event fields + "base" fields required by Figaro.
 * WARNING: May return "null" if metrics are disabled via the metrics.disabled config source value, or on error.
 * @overridable
 */
Account.prototype.metricsData = function (pageId, pageType, pageContext /*, callerSuppliedEventFieldsMapN(varargs)*/) {
    return this.processMetricsData.apply(this, arguments);
};

/**
 * Returns all the fields that this eventHandler knows about.
 * The eventHandler may have accessor functions which derive some of these fields.
 * The "metricsData()" method will use this list of fields to attempt to invoke accessor methods to get field values.
 * Therefore, if callers override this function, and add additional values, and provide accessors for those values, then
 * the "metricsData()" function will ultimately call those accessors as well.
 * @return all the fields that this eventHandler knows about
 */
Account.prototype.knownFields = function knownFields() {
    var knownFields = ['eventType', 'eventVersion', 'type'];

    return knownFields;
};

/**
 * The type of event this is
 * @returns {String}
 * @overridable
 */
Account.prototype.eventType = function (callerSuppliedEventFields) {
    return 'account';
};

/**
 * The version of the set of data to be sent up
 * @returns {number}
 * @overridable
 */
Account.prototype.eventVersion = function (callerSuppliedEventFields) {
    return (callerSuppliedEventFields && callerSuppliedEventFields.eventVersion) || 1;
};

/*
 *  src/metrics/event_handlers/base.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2015 Apple Inc. All rights reserved.
 *
 */

var BASE_FIELDS = constants.METRICS_KIT_BASE_FIELDS;
var IGNORED_BASE_FIELDS = constants.IGNORED_BASE_FIELDS;
var Base$1 = eventHandlers.Base;

/**
 * Creates and returns an object (key/value data map (dictionary)) containing all of the "base" fields common to all metrics events.
 * To override any functionality in this class, use the "setDelegate() method in order to override the specific functions that need customization.
 * @delegatable
 * @constructor
 */
var ClickstreamProcessorBase = function (clickstreamProcessor) {
    Base$1.apply(this, arguments);
};

ClickstreamProcessorBase.prototype = Object.create(Base$1.prototype);
ClickstreamProcessorBase.prototype.constructor = ClickstreamProcessorBase;

/**
 * The active environment class
 * @see src/metrics/system/Environment
 * @return {Environment}
 */
ClickstreamProcessorBase.prototype.environment = function environment() {
    return this._processor.system.environment;
};

/**
 * The active eventRecorder
 * @see src/metrics/system/eventRecorder
 * @return {Object} an eventRecorder
 */
ClickstreamProcessorBase.prototype.eventRecorder = function eventRecorder() {
    return this._processor.system.eventRecorder;
};

/**
 * Returns all the fields that this eventHandler knows about.
 * The eventHandler may have accessor functions which derive some of these fields.
 * The "metricsData()" method will use this list of fields to attempt to invoke accessor methods to get field values.
 * Therefore, if callers override this function, and add additional values, and provide accessors for those values, then
 * the "metricsData()" function will ultimately call those accessors as well.
 * @return all the fields that this eventHandler knows about
 */
ClickstreamProcessorBase.prototype.knownFields = function knownFields() {
    var parentKnownFields = Base$1.prototype.knownFields.call(this);
    if (IGNORED_BASE_FIELDS && IGNORED_BASE_FIELDS.length > 0) {
        parentKnownFields = parentKnownFields.slice();
        IGNORED_BASE_FIELDS.forEach(function (ignoredField) {
            var ignoredFieldIndex = parentKnownFields.indexOf(ignoredField);
            if (ignoredFieldIndex > -1) {
                parentKnownFields.splice(ignoredFieldIndex, 1);
            }
        });
    }

    return parentKnownFields.concat(BASE_FIELDS);
};

/**
 ************************************ PUBLIC METHODS/IVARS ************************************
 */

/**
 * Creates a simple map object (dictionary) with all the "base" fields required by Figaro
 * Some fields can be derived by this class itself.
 * Some fields need to be provided by callers (e.g. pageId, pageType, pageContext)
 * @param {String} pageId required for all event creation. Indicates the id of the page this event took place on.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * The type of ID may vary (e.g. adam id, grouping id, result id, etc), but is generally
 * the identifier in some persistent store. Search Results pages may have a pageId which refers to their specific dataSet,
 * otherwise known as dataSetId. If the page is better identified by a descriptive string rather than a content ID,
 * this field may be hard-coded, but it should be unique within the set of pages displayable by the app.
 * If an application is not client/server "page" oriented (where the client needs to request data from the server for each "page" of the app), then
 * this field would be generated by the client.
 * Note: A unique "page" value will created by concatenating pageType+"_"+pageId
 * @param {String} pageType required for all event creation. Indicates the type of page this event took place on.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * This value should represent the group of pages (e.g. "Genre", “Album”, “Grouping”, "Picker", "Recommendations", "Feed",
 * "Search", "Subscribe", etc.).
 * If an application is not client/server "page" oriented (where the client needs to request data from the server for each "page" of the app), then
 * this field would be generated by the client (potentially being hard-coded).
 * Note: A unique "page" value will created by concatenating pageType+"_"+pageId
 * @param {String} pageContext required for all event creation. Indicates the context within which a page is viewed.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * Contexts usually provide independent streams of activity and can typically appear as UI "tab" elements or primary navigation elements.
 * @example: iTunes Desktop: “InTheStore” or “Main”.
 * @example: iOS iTunes apps: tab name (e.g. “Featured”, “TopCharts”, etc)
 * @example: iOS Store sheets:  “Sheet” (e.g. AppStore page launched as a sheet within Mail, Springboard’s “Near Me”, Maps’ “Nearby Apps”)
 * @param {varargs} callerSuppliedEventFieldsMapN a variable number of Object arguments from 0-N, each containing key/value pairs representing event fields to include with the returned metricsData
 * All event fields will be merged.
 * An attempt will be made to invoke an accessor method for each *known* field, providing the caller the opportunity to override accessor methods.
 * If no accessor method is found, the event field value will be included in the returned metricsData as-is.
 * Later objects take precedence over earlier ones, overriding any field value that may have already been there.
 * If this parameter is null or omitted, only the known page fields will be included
 * @example metrics.eventHandlers.base.metricsData(appData.pageId, appData.pageType, appData.pageContext, {some:"some", known:"known", eventFieldValues:"eventFieldValues"}; someOtherKnownEventValues, appData.someAdditionalBaseFieldValues);
 * @returns {Promise} A Promise that with key/value pairs of all "page" fields + "base" fields required by Figaro.
 * WARNING: May return "null" if metrics are disabled via the metrics.disabled config source value, or on error.
 * @overridable
 */
ClickstreamProcessorBase.prototype.metricsData = function metricsData(
    pageId,
    pageType,
    pageContext /*, callerSuppliedEventFieldsMapN(varargs)*/
) {
    var metricsData = {};
    var valueTasks = [];
    var callerSuppliedEventFieldsMapsArray = Array.prototype.slice.call(arguments, 3);
    var utils = this._processor.utils;

    return this._processor.config
        .value('metricsBase')
        .then(
            function (configBaseFields) {
                if (configBaseFields) {
                    callerSuppliedEventFieldsMapsArray.push(configBaseFields);
                }
                var eventFieldPromises = utils.eventFields.processMetricsData(
                    this,
                    this.knownFields(),
                    pageId,
                    pageType,
                    pageContext,
                    callerSuppliedEventFieldsMapsArray
                );
                Object.keys(eventFieldPromises).forEach(function (field) {
                    var fieldValue = eventFieldPromises[field];
                    var valueHandler = Promise.resolve(fieldValue).then(function (value) {
                        metricsData[field] = value;
                    });
                    valueTasks.push(valueHandler);
                });

                return valueTasks;
            }.bind(this)
        )
        .then(function (valueTasks) {
            return Promise.all(valueTasks).then(function () {
                return metricsData;
            });
        });
};

// ********************* ACCESSOR FUNCTIONS *********************
/**
 * We create accessor functions for every data field because:
 * 1. Cleans/simplifies all methods that use it.
 * 2. Facilitates writing test case shims
 * 3. Allows specific feature suppliers to be overridden (via setDelegate()))
 */

// Generate the metricskit specified base field accessors
// NOTE: dynamically generate environment based accessors before the customized accessors to make these accessors to be overridable by the customized accessors.
BASE_FIELDS.forEach(function (fieldName) {
    ClickstreamProcessorBase.prototype[fieldName] = function (callerSuppliedEventFields) {
        var environment = this._processor.system.environment;
        return (callerSuppliedEventFields && callerSuppliedEventFields[fieldName]) || environment[fieldName]();
    };
});

/**
 * The name of the constraint profile used to apply constraints to fields within an event.
 * @example "strict"
 * @param {Map} callerSuppliedEventFields - NOTE: If you want to use one of these fields to help derive *this* eventField, you should
 * invoke its accessor, if one is available, in case *its* value is derived or massaged.
 * @returns {Promise|string}
 * @overridable
 */
ClickstreamProcessorBase.prototype.constraintProfile = function constraintProfile(callerSuppliedEventFields) {
    var config = this._processor.config;
    return (callerSuppliedEventFields && callerSuppliedEventFields.constraintProfile) || config.constraintProfile();
};

/**
 * The names of the constraint profiles used to apply constraints to fields within an event.
 * NOTE: This method returns the constraint profiles that are used for Constraints v2 syntax. The constraintProfile() returns the profile that is used for Constraints v1 syntax
 * @example "[strict]"
 * @param {Map} callerSuppliedEventFields - NOTE: If you want to use one of these fields to help derive *this* eventField, you should
 * invoke its accessor, if one is available, in case *its* value is derived or massaged.
 * @returns {Promise|string}
 * @overridable
 */
ClickstreamProcessorBase.prototype.constraintProfiles = function constraintProfiles(callerSuppliedEventFields) {
    var config = this._processor.config;
    return (callerSuppliedEventFields && callerSuppliedEventFields.constraintProfiles) || config.constraintProfiles();
};

/**
 * A unique identifier for each event
 * @returns {String}
 * @overridable
 */
ClickstreamProcessorBase.prototype.clientEventId = function clientEventId(callerSuppliedEventFields) {
    var eventId = callerSuppliedEventFields && callerSuppliedEventFields.clientEventId;
    if (!eventId) {
        if (string$1.cryptoRandomBase62String) {
            eventId = string$1.cryptoRandomBase62String(true);
        }
        if (!eventId) {
            eventId = string$1.uuid();
        }
    }
    return eventId;
};

/**
 * Return the value of the "xp_ci" cookie
 * @param {Map} callerSuppliedEventFields - NOTE: If you want to use one of these fields to help derive *this* eventField, you should
 * invoke its accessor, if one is available, in case *its* value is derived or massaged.
 * @returns {Promise|String} the value of the "xp_ci" cookie
 * @overridable
 */
ClickstreamProcessorBase.prototype.clientId = function clientId(callerSuppliedEventFields) {
    var clientId;
    var config = this._processor.config;

    if (callerSuppliedEventFields && callerSuppliedEventFields.clientId) {
        clientId = callerSuppliedEventFields.clientId;
    } else if (this._processor.system.environment.clientId()) {
        clientId = this._processor.system.environment.clientId();
    } else {
        clientId = config.value('ignoreClientIdCookie').then(function (ignoreClientIdCookie) {
            if (!ignoreClientIdCookie) {
                return cookies.get('xp_ci');
            }
            return undefined;
        });
    }

    return clientId;
};

/**
 * Whether or not the user is signed in
 * @example true, false
 * @param {Map} callerSuppliedEventFields - NOTE: If you want to use one of these fields to help derive *this* eventField, you should
 * invoke its accessor, if one is available, in case *its* value is derived or massaged.
 * @returns {boolean} true if the user is signed in (app has access to dsid), false if not
 * @overridable
 */
ClickstreamProcessorBase.prototype.isSignedIn = function isSignedIn(callerSuppliedEventFields) {
    return callerSuppliedEventFields && 'isSignedIn' in callerSuppliedEventFields
        ? callerSuppliedEventFields.isSignedIn
        : !!this.dsId(callerSuppliedEventFields);
};

/**
 * A unique descriptor for the page.
 * Usually [pageType_pageId]
 * If no pageId exists, "page" may be a textual identifier (e.g. "NewStation_Genres", "LearnMore_HD").
 * If an application is not client/server "page" oriented (where the client needs to request data from the server for each "page" of the app),
 * then this field would be generated by the client.
 * @example Genre_168577
 * @param {Map} callerSuppliedEventFields - NOTE: If you want to use one of these fields to help derive *this* eventField, you should
 * invoke its accessor, if one is available, in case *its* value is derived or massaged.
 * @returns {Promise|String} a unique descriptor for the page
 * @overridable
 */
ClickstreamProcessorBase.prototype.page = function page(callerSuppliedEventFields) {
    if (callerSuppliedEventFields) {
        if (callerSuppliedEventFields.page) {
            return callerSuppliedEventFields.page;
        } else if (this.pageType(callerSuppliedEventFields) && this.pageId(callerSuppliedEventFields)) {
            var config = this._processor.config;
            var pageType = this.pageType(callerSuppliedEventFields);
            var pageId = this.pageId(callerSuppliedEventFields);

            return config.value('compoundSeparator').then(function (separator) {
                return pageType + separator + pageId;
            });
        }
    } else {
        throw 'No data provided to event_handlers/base page function';
    }
};

/**
 * The context within which a page is viewed.  Contexts usually provide independent streams of activity.
 * Many implementations return the tab that a user is currently on.
 * @example
 * iTunes Desktop: "InTheStore" or "Main"
 * iOS iTunes apps: tab name (e.g. "Featured", "TopCharts", etc)
 * iOS Store sheets:  "Sheet" (e.g. AppStore page launched as a sheet within Mail, Springboard’s "Near Me", Maps’ "Nearby Apps")
 * @param {Map} callerSuppliedEventFields - NOTE: If you want to use one of these fields to help derive *this* eventField, you should
 * invoke its accessor, if one is available, in case *its* value is derived or massaged.
 * @returns {String} the context within which a page is viewed.  Contexts usually provide independent streams of activity
 * @overridable
 */
ClickstreamProcessorBase.prototype.pageContext = function pageContext(callerSuppliedEventFields) {
    return callerSuppliedEventFields && callerSuppliedEventFields.pageContext;
};

/**
 * IMPORTANT: This field cannot be deduced by this class, so either:
 *              a. this method needs to be overridden by the caller,
 *              b. the caller should pass this in as part of the key/value in the "callerSuppliedEventFieldsMapN(varargs)" parameter on the metricsData() call
 * User-readable details describing page.
 * May contain localized values (e.g. "Alicia Keys-Girl On Fire", "MusicMain").
 * Max length 25 characters.
 * If an application is not client/server "page" oriented (where the client needs to request data from the server for each "page" of the app),
 * then this field would be generated by the client, if needed.
 * @example "Top Paid iPhone Apps_Mobile Software Applications"
 * @param {Map} callerSuppliedEventFields - NOTE: If you want to use one of these fields to help derive *this* eventField, you should
 * invoke its accessor, if one is available, in case *its* value is derived or massaged.
 * @returns {String} user-readable details describing page
 * @overridable
 */
ClickstreamProcessorBase.prototype.pageDetails = function pageDetails(callerSuppliedEventFields) {
    return callerSuppliedEventFields && callerSuppliedEventFields.pageDetails;
};

/**
 * IMPORTANT: This field cannot be deduced by this class, so either:
 *              a. this method needs to be overridden by the caller,
 *              b. the caller should pass this in as part of the key/value in the "callerSuppliedEventFieldsMapN(varargs)" parameter on the metricsData() call
 * String ID of the page’s content.
 * Used to concatenate with the "pageType" param using the "compoundSeparator" config value (typically "_") to produce "page" values of the form: pageType_pageId
 * The type of ID may vary (e.g. adam id, grouping id, result id, etc), but is generally the identifier in some persistent store.
 * Search Results pages may have a pageId which refers to their specific dataSet, otherwise known as dataSetId.
 * If the page is better identified by a descriptive string rather than a content ID, this field may be hard-coded, but it should be unique within the set of pages displayable by the app
 * the descriptive string may appear in the "page" field instead.
 * If an application is not client/server "page" oriented (where the client needs to request data from the server for each "page" of the app),
 * then this field would be generated by the client.
 * @example 168577, 1, "Welcome", etc.
 * @param {Map} callerSuppliedEventFields - NOTE: If you want to use one of these fields to help derive *this* eventField, you should
 * invoke its accessor, if one is available, in case *its* value is derived or massaged.
 * @returns {String} string ID of the page’s content
 * @overridable
 */
ClickstreamProcessorBase.prototype.pageId = function pageId(callerSuppliedEventFields) {
    // TODO:KBERN: add screamer here if this is not provided?
    return callerSuppliedEventFields && callerSuppliedEventFields.pageId;
};

/**
 * IMPORTANT: This field cannot be deduced by this class, so either:
 *              a. this method needs to be overridden by the caller,
 *              b. the caller should pass this in as part of the key/value in the "callerSuppliedEventFieldsMapN(varargs)" parameter on the metricsData() call
 * Name for the group of pages this page is (e.g. "Album" or "Grouping").
 * If an application is not client/server "page" oriented (where the client needs to request data from the server for each "page" of the app),
 * then this field would be generated by the client.
 * Used to concatenate with the "pageId" param using the "compoundSeparator" config value (typically "_") to produce "page" values of the form: pageType_pageId
 * @example "Genre", "Album", "Grouping", "Picker", "Recommendations", "Feed", "Search", "Subscribe", etc.)
 * @param {Map} callerSuppliedEventFields - NOTE: If you want to use one of these fields to help derive *this* eventField, you should
 * invoke its accessor, if one is available, in case *its* value is derived or massaged.
 * @returns {String} name for the group of pages this page is (e.g. "Album" or "Grouping").
 * @overridable
 */
ClickstreamProcessorBase.prototype.pageType = function pageType(callerSuppliedEventFields) {
    // TODO:KBERN: add screamer here if this is not provided?
    return callerSuppliedEventFields && callerSuppliedEventFields.pageType;
};

/**
 * The percentage, from 0 to 1, that an item should be on screen before being considered impressionable
 * This field should be based on the client's most recent config value of "viewablePercentage".
 * This is valuable for problem analysis because it indicates if and how clients are honoring the "viewablePercentage" value
 * they were supplied with.
 * This cannot be a "passthrough" field, because it can change (via new config) during program execution, so the value
 * in effect at event creation time is what is needed.
 * @example 0.5
 * @param {Map} callerSuppliedEventFields - NOTE: If you want to use one of these fields to help derive *this* eventField, you should
 * invoke its accessor, if one is available, in case *its* value is derived or massaged.
 * @returns {Promise|number} the percentage, from 0 to 1, that an item should be on screen before being considered impressionable
 * @overridable
 */
ClickstreamProcessorBase.prototype.xpViewablePercentage = function xpViewablePercentage(callerSuppliedEventFields) {
    var config = this._processor.config;
    return (
        (callerSuppliedEventFields && callerSuppliedEventFields.xpViewablePercentage) ||
        config.value('impressions.viewablePercentage')
    );
};

/**
 * The version of MetricsKit being used
 * Pulled from the version in the package.json via
 * the dynamically created info.js
 * @example "0.1.3", "2.0.1"
 * @returns {String} version of MetricsKit being used
 * @overridable //this should be changed to not be overridable
 */
ClickstreamProcessorBase.prototype.xpVersionMetricsKit = function xpVersionMetricsKit() {
    return info.version;
};

/**
 * The versions and names, and delegate dependencies of delegates attached to MetricsKit
 * @example
 *  // If a delegate with the same name/version value is added
 *  // to the same target multiple times, (such as a case where
 *  // portions of one delegate are attached separately to a target)
 *  // each delegate is only represented
 *  // once per 'level' of delegate children
 *  [{
 *      version: '1.2.3',
 *      name: '@amp-metrics/mt-metricskit-delegates-itml'
 *   }
 *   {
 *      version: '3.2.1',
 *      name: '@amp-metrics/mt-metricskit-delegates-html',
 *      delegates:[{
 *          version: '2.1.3',
 *          name: '@amp-metrics/mt-metricskit-delegates-html-ios'
 *      }]
 *  }]
 * @returns {Array} Info of delegates attached to MetricsKit
 * @overridable //this should be changed to not be overridable
 */
ClickstreamProcessorBase.prototype.xpDelegatesInfo = function xpDelegatesInfo() {
    var delegateTree = delegatesInfo.getStoredDelegateObject(this);
    var delegateChildren = delegateTree && delegateTree.delegates;
    // If no delegates have been attached to MetricsKit,
    // return undefined so the field is removed from the event
    return delegateChildren ? delegateChildren : undefined;
};

/*
 *  src/metrics/event_handlers/buyConfirmed.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2015 Apple Inc. All rights reserved.
 *
 */

/**
 * Creates and returns an object (key/value data map (dictionary)) containing all of the fields needed for this metrics event.
 * To override any functionality in this class, use the "setDelegate() method in order to override the specific functions that need customization.
 * <p>
 * PLEASE READ:
 * What follows is an important discussion of how buys operate in iTunes Stores, and how to accurately collect metrics data during that flow.
 * <p>
 * The typical flow of a "buy" in an iTunes Store is:
 * <ol>
 *     <li>User performs some "buy" action (e.g. click a "buy" button or a "subscribe" button)
 *     <li>JavaScript code then creates some "buyData" (including some "buyParams") needed by the Finance servers in order to execute the buy.
 *     <li>JavaScript code then invokes a native "buy" call such as itms.buy(buyData) or itunes.buy(buyData).
 *     <li>In response to the "buy()" call, the native code returns immediately, making the rest of the procedure asynchronous to the JavaScript code.
 *     <li>Native code then makes an HTTP request to the Finance servers with the buyData
 *     <li>Finance servers then reply with a "success" or "failure" response.
 *     <li>When Finance response comes back from Finance, the native code will invoke a JavaScript callback such as "onBuy(buyInfo)".
 *     <li>The "buyInfo" parameter may contain a "result" value (buyInfo.result).
 *     <li>JavaScript code checks buyInfo.return and if present and non-zero/non-null typically invokes (or publishes) a "buyConfirmed" JavaScript event, and if not, invokes (or publishes) a "buyFailed" event.
 *     <li>Within that "buyConfirmed" callback function (perhaps subscribed to), is where the metrics "buyConfirmed" event should be created a and recorded.
 * </ol>
 * </p>
 * That is the <i>typical</i> flow. But things can go wrong.
 * The Finance servers can, for example, in the response to the "buy" request, instruct the native client code to "detour" the user through a Finance flow such as credit card validation, terms of service agreement, etc.
 * When that occurs, the native code <i>will invoke the JavaScript "onBuy" function with a result value indicating buy failure!</i>.
 * However, the buy may not have "really" failed... after the user completes the Finance flow, the "buy" request might eventually succeed, in which case the native code is notified and it will call the JavaScript client's "onBuy" callback with a <i>success</i> return value (causing the "buyConfirmed" to be published), even though it has already called it with a failure code!
 * <p>
 * Due to this special case, the metrics code needs to stash away the metrics data in place at the time the user requests the "buy" and then use that data later (perhaps much later) when/if the "buyConfirmed" actually occurs.
 * In order to marry the metrics data from the time of the "buy", to the event returned in any given "buyConfirmed" (remember, it's all asynchronous), the client creates a "clientBuyId" and uses that as a key to store metrics data.
 * It also passes that key as a query param on the "buy" request so that...
 * When/if the "buyConfirmed" callback is finally called, it will contain the "clientBuyId" value which the metrics code can then use to look up the metrics data that was in place at the time of the "buy".
 * <p>
 * This "detoured" "edge case" of users being redirected through Finance flows can happen a significant percentage of the time (possibly 10-20%) so it has to be handled for accurate metrics.
 * <p>
 * MetricsKit attempts to hide as much of this edge-case craziness as possible, and aid in facilitating the handling of it.
 * <p>
 * <b>To properly instrument buyConfirmed events, JavaScript clients should:</b>
 * <ol>
 *     <li>at <b>"buy"</b> time
 *         <ol>
 *             <li> Create a "clientBuyId" via a call to:
 *                  <br><b><i>metrics.eventHandlers.buyConfirmed.createClientBuyId()</i></b>.
 *                  <br>NOTE: each successive call to this function will return a different clientBuyId
 *             <li> Include that value with the "buyParams" via a call to:
 *                  <br><b><i>metrics.eventHandlers.buyConfirmed.clientBuyIdQueryParamString(clientBuyId)</i></b>
 *             <li> Cache all metrics data needed for the (ulitmate) "buyConfirmed" event, keying off that clientBuyId, via a call to:
 *                  <br><b><i>metrics.eventHandlers.buyConfirmed.cacheMetricsBuyData(clientBuyId, metricsBuyData)</i></b>
 *                  <br>Caching the data here ensures that the metrics buy data accurately reflects the user state at the time of the "buy" vs. their state when the asynchronous "buyConfirmed" callback is received.
 *             <li> Invoke the native "itms/iTunes.buy(buyData)" function.
 *             <br>The clientBuyId will be passed through all the subsequent Finance calls, and eventually be returned to the client when the buy finally succeeds or fails.
 *         </ol>
 *     <li>at <b>"buyFailed"</b> time (which will only happen if user gets "detoured" through a Finance flow)
 *         <ol>
 *             <li> notify MetricsKit that the buy may be detoured via a call to:
 *                  <br><b><i>metrics.eventHandlers.buyConfirmed.buyFailureOccurred(clientBuyId)</i></b> (MetricsKit will add a "detoured" flag to the stashed data)
 *         </ol>
 *     <li>at <b>"buyConfirmed"</b> time (regardless of whether or not it previously failed)
 *         <ol>
 *             <li> retrieve the clientBuyId from the buyData included with the "buyConfirmed" native callback, e.g.:
 *             <br>     var clientBuyId = buyInfo.options.clientBuyId;
 *             <br> This is the same clientBuyId that was supplied as a query parameter during the initial itms/iTunes.buy() call and is plumbed through any Finance flows that occurred.
 *             <li> retrieve the cached metrics data via a call to:
 *                  <br><b><i>metrics.eventHandlers.buyConfirmed.uncacheMetricsBuyData(clientBuyId)</i></b>.
 *                  <br><b>IMPORTANT</b>: If cached data is successfully retrieved for the supplied clientBuyId, that data will be removed in order to keep the cache size under control
 *             <li> prepare the data required by the "buyConfirmed" event (be sure to include the "detoured" flag, if present)
 *             <li> create the "buyConfirmed" metrics event via a call to:
 *                  <br><b><i>metrics.eventHandlers.buyConfirmed.metricsData()</i></b>, including the retrieved cached metrics data.
 *         </ol>
 * </ol>
 *
 * JavaScript clients should
 *
 * @delegatable
 * @constructor
 */
var BuyConfirmed = function (metricsKit) {
    ClickStreamEventHandler.apply(this, arguments);
};

BuyConfirmed.prototype = Object.create(ClickStreamEventHandler.prototype);
BuyConfirmed.prototype.constructor = BuyConfirmed;

/**
 ************************************ 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} delegate 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.
 */
BuyConfirmed.prototype.setDelegate = function setDelegate(delegate) {
    return reflect$1.attachDelegate(this, delegate);
};

/**
 * Creates a simple map object (dictionary) with all the fields required by Figaro for this event
 * Some fields can be derived by this class itself.
 * Some fields need to be provided by callers (e.g. pageId, pageType, pageContext)
 * @param {String} pageId required for all event creation. Indicates the id of the page this event took place on.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * The type of ID may vary (e.g. adam id, grouping id, result id, etc), but is generally
 * the identifier in some persistent store. Search Results pages may have a pageId which refers to their specific dataSet,
 * otherwise known as dataSetId. If the page is better identified by a descriptive string rather than a content ID,
 * this field may be hard-coded, but it should be unique within the set of pages displayable by the app.
 * If an application is not client/server "page" oriented (where the client needs to request data from the server for each "page" of the app), then
 * this field would be generated by the client.
 * Note: A unique "page" value will created by concatenating pageType+"_"+pageId
 * @param {String} pageType required for all event creation. Indicates the type of page this event took place on.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * This value should represent the group of pages (e.g. "Genre", “Album”, “Grouping”, "Picker", "Recommendations", "Feed",
 * "Search", "Subscribe", etc.).
 * If an application is not client/server "page" oriented (where the client needs to request data from the server for each "page" of the app), then
 * this field would be generated by the client (potentially being hard-coded).
 * Note: A unique "page" value will created by concatenating pageType+"_"+pageId
 * @param {String} pageContext required for all event creation. Indicates the context within which a page is viewed.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * Contexts usually provide independent streams of activity and can typically appear as UI "tab" elements or primary navigation elements.
 * @example: iTunes Desktop: “InTheStore” or “Main”.
 * @example: iOS iTunes apps: tab name (e.g. “Featured”, “TopCharts”, etc)
 * @example: iOS Store sheets:  “Sheet” (e.g. AppStore page launched as a sheet within Mail, Springboard’s “Near Me”, Maps’ “Nearby Apps”)
 * @example a "hint", "related" click, "filter" click, etc.
 * If this event is representing a plain typed buyConfirmed, this field's value may be null
 * @param {varargs} callerSuppliedEventFieldsMapN a variable number of Object arguments from 0-N, each containing key/value pairs representing event fields to include with the returned metricsData
 * All event fields will be merged.
 * An attempt will be made to invoke an accessor method for each field, providing the caller the opportunity to override accessor methods.
 * If no accessor method is found, the event field value will be included in the returned metricsData as-is.
 * Later objects take precedence over earlier ones, overriding any field value that may have already been there.
 * If this parameter is null or omitted, only the known page fields will be included
 * @example metrics.eventHandlers.page.metricsData(appData.pageId, appData.pageType, appData.pageContext, element, {some:"some", known:"known", eventFieldValues:"eventFieldValues"}; someOtherKnownEventValues, appData.someAdditionalBaseFieldValues);
 * @returns {map} key/value pairs of all event fields + "base" fields required by Figaro.
 * WARNING: May return "null" if metrics are disabled via the metrics.disabled config source value, or on error.
 * @overridable
 */
BuyConfirmed.prototype.metricsData = function (
    pageId,
    pageType,
    pageContext /*, callerSuppliedEventFieldsMapN(varargs)*/
) {
    return this.processMetricsData.apply(this, arguments);
};

/**
 * Returns all the fields that this eventHandler knows about.
 * The eventHandler may have accessor functions which derive some of these fields.
 * The "metricsData()" method will use this list of fields to attempt to invoke accessor methods to get field values.
 * Therefore, if callers override this function, and add additional values, and provide accessors for those values, then
 * the "metricsData()" function will ultimately call those accessors as well.
 * @returns {array} all the fields that this eventHandler knows about
 */
BuyConfirmed.prototype.knownFields = function knownFields() {
    var knownFields = ['eventType', 'eventVersion'];

    return knownFields;
};

/**
 * The type of event this is
 * @returns {String}
 * @overridable
 */
BuyConfirmed.prototype.eventType = function (callerSuppliedEventFields) {
    return 'buyConfirmed';
};

/**
 * The version of the set of data to be sent up
 * @returns {number}
 * @overridable
 */
BuyConfirmed.prototype.eventVersion = function (callerSuppliedEventFields) {
    return (callerSuppliedEventFields && callerSuppliedEventFields.eventVersion) || 1;
};

/**
 * <i>NOTE: Please read the full description of the "buy" process at the top of this page before attempting to utilize these methdos</i>
 * Called at the time a user initiates a "buy" (e.g. typically immediately before the itms/iTunes.buy(buyData) calls)
 * This function is used as a cacheKey to store metrics data when the user initiates a "buy" and to retrieve that information if the buy "fails" by virtue of the user
 * being forced through, e.g., a Finance flow (CC validation, TOS acceptance, etc.), and then later a "buySuccess" (buyConfirmed) comes through, this value allows
 * the client application to bind to the metrics data that would have been included if the buy had initially succeeded.
 * @returns {number} returns a unique integer value with each call. The uniqueness only last for a single JavaScript "session" (it is merely an incremented value)
 */
BuyConfirmed.prototype.createClientBuyId = function () {
    var newClientId = null;
    var environment = this._processor.system.environment;
    var previousClientBuyId = environment.sessionStorageObject().getItem('mtMetricsKit_previousClientBuyId');

    // May coerce type of previousClientBuyId to Number, NaN result should be reset to 1
    newClientId = ++previousClientBuyId;
    if (!previousClientBuyId) {
        this._processor.system.logger.warn(
            'Metrics: buyConfirmed.createClientBuyId: clientBuyId did not exist or was of incorrect type, reset to 1.'
        );
        newClientId = 1;
    }
    // We use sessionStorage in case our page/JS context goes away and then comes back, we continue where we left off.
    environment.sessionStorageObject().setItem('mtMetricsKit_previousClientBuyId', newClientId);

    return newClientId;
};

// NOTE: I know this method is a trivial convenience and is not so helpful to callers, but what it *does* do is that its existence makes it explicit to callers that clientBuyId needs to be added to their buParams query parameters
//       It also leaves the name of that query param under our control, preventing errors and allowing for transparent changes in the future.
/**
 * <i>NOTE: Please read the full description of the "buy" process at the top of this page before attempting to utilize these methdos</i>
 * Called at the time a user initiates a "buy" (e.g. typically immediately before the itms/iTunes.buy(buyData) calls)
 * Convenience method for creating the appropriate query param string to include with the "buyParams" on a typical "itms/iTunes.buy(buyInfo)" call
 * @param {number} clientBuyId is the value returned by the "createClientBuyId()". Remember to only call that method once, as it returns a different value each time.
 * @returns {String} a query param string with "clientBuyId" as a key and the value of the passed-in "clientBuyId" as a value, e.g. "&clientBuyId=2"
 * <br>NOTE: The returned string is always prefaced with an ampersand (&), never a question mark (?)
 * @example
 *     var clientBuyId = metrics.eventHandlers.buyConfirmed.createClientBuyId();
 *     buyData.offers[i].buyParams = buyData.offers[i].buyParams + "&someBuyParam=" + someBuyParamValue + metrics.eventHandlers.buyConfirmed.clientBuyIdQueryParamString(clientBuyId(clientBuyId);
 */
BuyConfirmed.prototype.clientBuyIdQueryParamString = function (clientBuyId) {
    return '&clientBuyId=' + clientBuyId;
};

/**
 * <i>NOTE: Please read the full description of the "buy" process at the top of this page before attempting to utilize these methods</i>
 * <i>NOTE: This code is not actually used in the generation of "buyConfirmed" events, but still seems like the best home for it.</i>
 * Called at the time a user initiates a "buy" (e.g. typically immediately before the itms/iTunes.buy(buyData) calls)
 * Convenience method for creating the appropriate query param string to include with the "buyParams" on a typical "itms/iTunes.buy(buyInfo)" call
 * @param {String} pageId is the pageId of the page where the buy originated.
 * @param {String} pageType is the pageType of the page where the buy originated.
 * @param {String} pageContext is the pageContext of the page where the buy originated.
 * @param {String} (optional) topic is the topic that will be used to send "dialog" events to if dialogs are presented as a result of the "buy()" call. If omitted, it will default to "xp_its_main"
 * @param {varargs} (optional) callerSuppliedBuyParamsMapsN a variable number of Object arguments from 0-N,
 *                             each containing key/value pairs representing buy parameters to include in
 *                             the returned string
 * @returns {Promise} a Promise that returns an unescaped query param string with 'mt' prefixed keys and the value of the passed-in parameters, plus 'mtPrevPage', derived from the
 * MetricsKit-cached pageHistory (see page event documentation)
 * - mtPrevPage (The previous page, using the pageHistory field)
 * - mtPageType (The pageType field of the page from which the purchase occurs)
 * - mtPageId (The pageId field of the page from which the purchase occurs).  Figaro can use this to ensure that the app being purchased shares an ID with the product page.
 * - mtPageContext (The pageContext field of the page from which the purchase occurs)
 * - mtTopic (The context of an event (e.g. “xp_its_main”).)
 * - mtRequestId (A client generated UUID for every request, to be used in visit stitching to stitch client side event together with server side buy.)
 * Refer to base field documentation for undocumented fields below
 * - mtApp
 * - mtEventTime
 * - mtClientId
 * e.g. "&mtPrevPage=Picker_Welcome&mtPageId=Subscribe&pageType=Picker&pageContext=ForYou"
 * <br>NOTE: The returned string is always prefaced with an ampersand (&), never a question mark (?)
 * @example
 *     var metricsBuyParamsString = await metrics.eventHandlers.buyConfirmed.metricsBuyParamsString(pageId, pageType, pageContext, "xp_its_main", { mtHardwareModel: "iPhone", extRefApp2: "com.apple.Mail" });
 *     buyData.offers[i].buyParams = buyData.offers[i].buyParams + "&someBuyParam=" + someBuyParamValue + "&" + metricsBuyParamsString;
 */
BuyConfirmed.prototype.metricsBuyParamsString = function (
    pageId,
    pageType,
    pageContext,
    topic /*, callerSuppliedBuyParamsMapsN(varargs)*/
) {
    var base = this._processor.eventHandlers.base;
    var page = this._processor.eventHandlers.page;
    var callerSuppliedBuyParamsMapsArray = Array.prototype.slice.call(arguments, 4);
    var pageHistory = page.pageHistory();
    var clientIdPromise = base.clientId();
    var mtPrevPage;

    if (Array.isArray(pageHistory)) {
        if (pageHistory.length >= 2) {
            mtPrevPage = pageHistory[pageHistory.length - 2];
        }
    } else {
        this._processor.system.logger.warn('MetricsKit: metricsBuyParamsString: pageHistory is not an Array');
    }

    return Promise.resolve(clientIdPromise).then(
        function (clientId) {
            var buyParams = {
                mtApp: base.app(callerSuppliedBuyParamsMapsArray),
                mtEventTime: Date.now(),
                mtHardwareBrand: base.hardwareBrand(callerSuppliedBuyParamsMapsArray),
                mtHardwareFamily: base.hardwareFamily(callerSuppliedBuyParamsMapsArray),
                mtHardwareModel: base.hardwareModel(callerSuppliedBuyParamsMapsArray),
                mtHostApp: base.hostApp(callerSuppliedBuyParamsMapsArray),
                mtHostAppVersion: base.hostAppVersion(callerSuppliedBuyParamsMapsArray),
                mtOs: base.os(callerSuppliedBuyParamsMapsArray),
                mtOsBuildNumber: base.osBuildNumber(callerSuppliedBuyParamsMapsArray),
                mtOsVersion: base.osVersion(callerSuppliedBuyParamsMapsArray),
                mtPageId: pageId,
                mtPageType: pageType,
                mtPageContext: pageContext,
                mtTopic: topic || 'xp_its_main',
                mtPrevPage: mtPrevPage,
                mtRequestId: string$1.uuid(),
                mtClientId: clientId
            };

            reflect$1.extend.apply(reflect$1, [buyParams].concat(callerSuppliedBuyParamsMapsArray));

            // NOTE: if any of these fields are null or "undefined",
            // they will be omitted in the "paramString()" function.
            return string$1.paramString(buyParams);
        }.bind(this)
    );
};

/**
 * <i>NOTE: Please read the full description of the "buy" process at the top of this page before attempting to utilize these methdos</i>
 * <i><b>IMPORTANT</b>: If this method successfully retrieves data for the supplied clientBuyId, that data will be removed in order to keep the cache size under control
 * Called at the time a user initiates a "buy" (e.g. typically immediately before the itms/iTunes.buy(buyData) calls)
 * This function is used to serialize (to string) and cache metrics data when the user initiates a "buy".
 * This data will be retrieved later during the "buyConfirmed" native callback (via the "uncacheMetricsBuyData()" function) and ensures that the metrics buy data accurately reflects the user state at the time of the "buy" vs. their state when the asynchronous "buyConfirmed" callback is received.
 * For example, the user may have been forced through a Finance flow (CC validation, TOS acceptance, etc.) and then later a "buySuccess" (buyConfirmed) comes through.
 * @param {number} clientBuyId is the value returned by the "createClientBuyId()". Remember to only call that method once, as it returns a different value each time.
 * @param {object} metricsBuyData is the value returned by the "createClientBuyId()". Remember to only call that method once, as it returns a different value each time.
 */
BuyConfirmed.prototype.cacheMetricsBuyData = function (clientBuyId, metricsBuyData) {
    var environment = this._processor.system.environment;
    // Since these methods are similarly named, let's just help out the caller by checking...
    if (arguments.length != 2) {
        this._processor.system.logger.error(
            'buyConfirmed.cacheMetricsBuyData(): function invoked with incorrect number of parameters. Perhaps you meant to retrieve cached data instead of setting it, which would be a call to uncacheMetricsBuyData(clientBuyId)?'
        );
    } else {
        // sessionStorage only accepts string values...
        var serializedData = JSON.stringify(metricsBuyData);
        environment
            .sessionStorageObject()
            .setItem('mtMetricsKit_metricsBuyData_for_clientBuyId_' + clientBuyId, serializedData);
    }
};

/**
 * <i>NOTE: Please read the full description of the "buy" process at the top of this page before attempting to utilize these methdos</i>
 * Called at the time JavaScript receives a "buyConfirmed" callback from the native code.
 * This function is used to deserialize (from string) and return the metrics data that was cached when the user initiated the "buy" via the cacheMetricsBuyData() function.
 * This data should be the data used to include when creating the buyConfirmed event via the metrics.eventHandlers.buyConfirmed.metricsData() function.
 * @param {number} clientBuyId is retrieved from the buyData included with the "buyConfirmed" native callback, e.g.:
 * <br>     var clientBuyId = buyInfo.options.clientBuyId;
 * <br> This is the same clientBuyId that was supplied as a query parameter during the initial itms/iTunes.buy() call and is plumbed through any Finance flows that occurred.
 * @returns {object} the same data that was initially stored with this clientBuyId at itms/iTunes.buy() time via the call to: "cacheMetricsBuyData()"
 * If no data is found for this clientBuyId, "null" will be returned (typically that should never happen)
 */
BuyConfirmed.prototype.uncacheMetricsBuyData = function (clientBuyId) {
    var returnValue = null;
    var environment = this._processor.system.environment;

    // Since these methods are similarly named, let's just help out the caller by checking...
    if (arguments.length != 1) {
        this._processor.system.logger.error(
            'buyConfirmed.uncacheMetricsBuyData(): function invoked with incorrect number of parameters. Perhaps you meant to set cached data instead of retrieving it, which would be a call to cacheMetricsBuyData(clientBuyId, metricsBuyData)?'
        );
    } else {
        // sessionStorage only accepts string values...
        var serializedData = environment
            .sessionStorageObject()
            .getItem('mtMetricsKit_metricsBuyData_for_clientBuyId_' + clientBuyId);

        if (serializedData) {
            returnValue = JSON.parse(serializedData);
            environment.sessionStorageObject().removeItem('mtMetricsKit_metricsBuyData_for_clientBuyId_' + clientBuyId);
        }
    }
    return returnValue;
};

/**
 * <i>NOTE: Please read the full description of the "buy" process at the top of this page before attempting to utilize these methdos</i>
 * Called at the time JavaScript receives a "buyFailed" callback from the native code.
 * This function is used to flag "buys" that have been "detoured" through a Finance flow with the "detoured=true" flag.
 * If a buy fails (which is why "buyFailed" would be called) but then later succeeds (after a Finance detour), we will have set the "detoured" flag by virtue of this call.
 * @param {number} clientBuyId is retrieved from the buyData included with the "buyFailed" native callback, e.g.:
 * <br>     var clientBuyId = buyInfo.options.clientBuyId;
 * <br> This is the same clientBuyId that was supplied as a query parameter during the initial itms/iTunes.buy() call and is plumbed through any Finance flows that occurred.
 */
BuyConfirmed.prototype.buyFailureOccurred = function (clientBuyId) {
    var uncacheMetricsBuyData = this.uncacheMetricsBuyData(clientBuyId);

    if (uncacheMetricsBuyData) {
        uncacheMetricsBuyData.detoured = true;
        // Put it back, since a) we added a field and b) asking for it removed it.
        this.cacheMetricsBuyData(clientBuyId, uncacheMetricsBuyData);
    }
};

/*
 *  src/metrics/event_handlers/click.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2015 Apple Inc. All rights reserved.
 *
 */

// TODO: move to utils-private
var safeJSONParse = function safeJSONParse(text) {
    var returnValue = null;

    try {
        returnValue = JSON.parse(text);
    } catch (e) {
        logger.error('MetricsKit: error parsing click data - ' + e);
    }

    return returnValue;
};

/**
 * Creates and returns an object (key/value data map (dictionary)) containing all of the fields needed for this metrics event.
 * To override any functionality in this class, use the "setDelegate() method in order to override the specific functions that need customization.
 * @delegatable
 * @constructor
 */
var Click = function (metricsKit) {
    ClickStreamEventHandler.apply(this, arguments);
};

Click.prototype = Object.create(ClickStreamEventHandler.prototype);
Click.prototype.constructor = Click;

/**
 ************************************ PUBLIC METHODS/IVARS ************************************
 */

/**
 * Creates a simple map object (dictionary) with all the fields required by Figaro for this event
 * Some fields can be derived by this class itself.
 * Some fields need to be provided by callers (e.g. pageId, pageType, pageContext)
 * @param {String} pageId required for all event creation. Indicates the id of the page this event took place on.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * The type of ID may vary (e.g. adam id, grouping id, result id, etc), but is generally
 * the identifier in some persistent store. Search Results pages may have a pageId which refers to their specific dataSet,
 * otherwise known as dataSetId. If the page is better identified by a descriptive string rather than a content ID,
 * this field may be hard-coded, but it should be unique within the set of pages displayable by the app.
 * If an application is not client/server "page" oriented (where the client needs to request data from the server for each "page" of the app), then
 * this field would be generated by the client.
 * Note: A unique "page" value will created by concatenating pageType+"_"+pageId
 * @param {String} pageType required for all event creation. Indicates the type of page this event took place on.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * This value should represent the group of pages (e.g. "Genre", “Album”, “Grouping”, "Picker", "Recommendations", "Feed",
 * "Search", "Subscribe", etc.).
 * If an application is not client/server "page" oriented (where the client needs to request data from the server for each "page" of the app), then
 * this field would be generated by the client (potentially being hard-coded).
 * Note: A unique "page" value will created by concatenating pageType+"_"+pageId
 * @param {String} pageContext required for all event creation. Indicates the context within which a page is viewed.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * Contexts usually provide independent streams of activity and can typically appear as UI "tab" elements or primary navigation elements.
 * @example: iTunes Desktop: “InTheStore” or “Main”.
 * @example: iOS iTunes apps: tab name (e.g. “Featured”, “TopCharts”, etc)
 * @example: iOS Store sheets:  “Sheet” (e.g. AppStore page launched as a sheet within Mail, Springboard’s “Near Me”, Maps’ “Nearby Apps”)
 * @param {Object} targetElement The element from which the click event originated
 * @param {varargs} callerSuppliedEventFieldsMapN a variable number of Object arguments from 0-N, each containing key/value pairs representing event fields to include with the returned metricsData
 * All event fields will be merged.
 * An attempt will be made to invoke an accessor method for each field, providing the caller the opportunity to override accessor methods.
 * If no accessor method is found, the event field value will be included in the returned metricsData as-is.
 * Later objects take precedence over earlier ones, overriding any field value that may have already been there.
 * If this parameter is null or omitted, only the known page fields will be included
 * @example metrics.eventHandlers.page.metricsData(appData.pageId, appData.pageType, appData.pageContext, element, {some:"some", known:"known", eventFieldValues:"eventFieldValues"}, someOtherKnownEventValues, appData.someAdditionalBaseFieldValues);
 * WARNING: May return "null" if metrics are disabled via the metrics.disabled config source value, or on error.
 * @returns key/value pairs of all event fields + "base" fields required by Figaro.
 * @overridable
 */
Click.prototype.metricsData = function (
    pageId,
    pageType,
    pageContext,
    targetElement /*, callerSuppliedEventFieldsMapN(varargs)*/
) {
    var argumentsArray = [pageId, pageType, pageContext];
    var utils = this._processor.utils;

    if (targetElement) {
        argumentsArray.push({
            location: utils.eventFields.buildLocationStructure(targetElement, this.locationDataForElement)
        });
        argumentsArray.push(this.dataForElement(targetElement) || {});
    }
    argumentsArray = argumentsArray.concat(Array.prototype.slice.call(arguments, 4));

    return this.processMetricsData.apply(this, argumentsArray);
};

/**
 * Returns all the fields that this eventHandler knows about.
 * The eventHandler may have accessor functions which derive some of these fields.
 * The "metricsData()" method will use this list of fields to attempt to invoke accessor methods to get field values.
 * Therefore, if callers override this function, and add additional values, and provide accessors for those values, then
 * the "metricsData()" function will ultimately call those accessors as well.
 * @return all the fields that this eventHandler knows about
 */
Click.prototype.knownFields = function knownFields() {
    var knownFields = [
        'actionContext',
        'actionDetails',
        'actionType',
        'actionUrl',
        'eventType',
        'eventVersion',
        'impressions',
        'location',
        'targetId',
        'targetType',
        'positionX',
        'positionY',
        'xpViewablePercentage'
    ];

    return knownFields;
};

/**
 * The parsed click data that was attached to a clicked element
 * @param {Object} targetElement The clicked element
 * @return {Object} the parsed click data that was attached to the element as a data attribute, if present and valid, otherwise null
 * @overridable
 */
Click.prototype.dataForElement = function dataForElement(element) {
    var returnValue = null;

    if (element && reflect$1.isFunction(element.hasAttribute) && reflect$1.isFunction(element.getAttribute)) {
        var clickDataAttribute = this.dataAttribute();
        if (element.hasAttribute(clickDataAttribute)) {
            returnValue = safeJSONParse(element.getAttribute(clickDataAttribute));
        }
    }

    return returnValue;
};

/**
 * The data attribute used to attach click data to DOM-like elements in the view model
 * @returns {String}
 * @overridable
 */
Click.prototype.dataAttribute = function dataAttribute() {
    return 'data-metrics-click';
};

/**
 * The relevant location dictionary for an element
 * @param {Object} element an element in the view heirarchy
 * @return {Object} the location data for the element, if present and valid, otherwise null
 *     The default implementation looks for a data attribute called 'data-metrics-location'
 *     and, if present, parses the attribute into a dictionary, and adds the elements' position
 *     within its parent container as a field called 'locationPosition'
 * @overridable
 */
Click.prototype.locationDataForElement = function locationDataForElement(element) {
    var parentNode = element.parentNode;
    var position = 0;
    var location = null;

    var siblingElements;
    var sibling;
    var siblingLocationInfo;
    var siblingLocationType;

    // if this element has a location type defined (in other words, it has a semantic value from the end user
    // point of view like shelf, lockup etc) then add it to the location stack otherwise don't.
    // for ex. we may have a bunch of <section> elements in our dom tree but there is no point in including
    // them in the location stack
    if (element.hasAttribute && element.hasAttribute('data-metrics-location')) {
        location = safeJSONParse(element.getAttribute('data-metrics-location'));
        if (location.locationType) {
            if (parentNode) {
                // determine our location in the children array of our parent
                siblingElements = parentNode.childNodes;
                for (var i = 0; i < siblingElements.length; i++) {
                    // ITML childNodes list uses .item(i) accessor instead of [i]
                    sibling =
                        (typeof siblingElements.item === 'function' && siblingElements.item(i)) || siblingElements[i];
                    siblingLocationInfo =
                        sibling.hasAttribute && sibling.hasAttribute('data-metrics-location')
                            ? safeJSONParse(sibling.getAttribute('data-metrics-location'))
                            : undefined;
                    siblingLocationType = siblingLocationInfo ? siblingLocationInfo.locationType : undefined;
                    if (siblingLocationType) {
                        if (sibling === element) {
                            // we now know the position of the element, so stop here
                            break;
                        } else {
                            // we consider all siblings that have the data-metrics-location attribute and the same parent container as the target element
                            // for calculating position. for ex. on a grouping page, we may have 2 swooshes, followed by a title text div and then
                            // one more swoosh. We count the preceding swooshes and the title text div sibling element when calculating the position
                            // of the 3rd swoosh. The position of the last swoosh should be '3' (with '0' based index).
                            position++;
                        }
                    }
                }
            }
            location.locationPosition = position;
        }
    }

    return location;
};

/**
 * The type of event this is
 * @returns {String}
 * @overridable
 */
Click.prototype.eventType = function (callerSuppliedEventFields) {
    return 'click';
};

/**
 * The version of the set of data to be sent up
 * @returns {number}
 * @overridable
 */
Click.prototype.eventVersion = function (callerSuppliedEventFields) {
    return (callerSuppliedEventFields && callerSuppliedEventFields.eventVersion) || 4;
};

/**
 * A list of flattened impression objects for this event
 * Default behavior assumes the impressions have already been flattened and just returns them, but clients can override this with their own flattening implementation
 * @returns {Array} an array of impression objects, or undefined if no event fields were provided by the caller
 * @overridable
 */
Click.prototype.impressions = function impressions(callerSuppliedEventFields) {
    return callerSuppliedEventFields ? callerSuppliedEventFields.impressions : undefined;
};

/**
 * The percentage, from 0 to 1, that an item should be on screen before being considered impressionable
 * This field should be based on the client's most recent config value of "viewablePercentage".
 * @returns {number} the percentage, from 0 to 1, that an item should be on screen before being considered impressionable
 * @overridable
 */
Click.prototype.xpViewablePercentage = function xpViewablePercentage(callerSuppliedEventFields) {
    return this._processor.eventHandlers.base.xpViewablePercentage(callerSuppliedEventFields);
};

/*
 *  src/metrics/event_handlers/dialog.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2015 Apple Inc. All rights reserved.
 *
 */

/**
 * Creates and returns an object (key/value data map (dictionary)) containing all of the fields needed for this metrics event.
 * To override any functionality in this class, use the "setDelegate() method in order to override the specific functions that need customization.
 * @delegatable
 * @constructor
 */
var Dialog = function (metricsKit) {
    ClickStreamEventHandler.apply(this, arguments);
};

Dialog.prototype = Object.create(ClickStreamEventHandler.prototype);
Dialog.prototype.constructor = Dialog;

/**
 ************************************ 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.
 */
Dialog.prototype.setDelegate = function setDelegate(delegate) {
    return reflect$1.attachDelegate(this, delegate);
};

/**
 * Creates a simple map object (dictionary) with all the fields required by Figaro for this event
 * Some fields can be derived by this class itself.
 * Some fields need to be provided by callers (e.g. pageId, pageType, pageContext)
 * @param {String} pageId required for all event creation. Indicates the id of the page this event took place on.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * The type of ID may vary (e.g. adam id, grouping id, result id, etc), but is generally
 * the identifier in some persistent store. Search Results pages may have a pageId which refers to their specific dataSet,
 * otherwise known as dataSetId. If the page is better identified by a descriptive string rather than a content ID,
 * this field may be hard-coded, but it should be unique within the set of pages displayable by the app.
 * If an application is not client/server "page" oriented (where the client needs to request data from the server for each "page" of the app), then
 * this field would be generated by the client.
 * Note: A unique "page" value will created by concatenating pageType+"_"+pageId
 * @param {String} pageType required for all event creation. Indicates the type of page this event took place on.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * This value should represent the group of pages (e.g. "Genre", “Album”, “Grouping”, "Picker", "Recommendations", "Feed",
 * "Search", "Subscribe", etc.).
 * If an application is not client/server "page" oriented (where the client needs to request data from the server for each "page" of the app), then
 * this field would be generated by the client (potentially being hard-coded).
 * Note: A unique "page" value will created by concatenating pageType+"_"+pageId
 * @param {String} pageContext required for all event creation. Indicates the context within which a page is viewed.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * Contexts usually provide independent streams of activity and can typically appear as UI "tab" elements or primary navigation elements.
 * @example: iTunes Desktop: “InTheStore” or “Main”.
 * @example: iOS iTunes apps: tab name (e.g. “Featured”, “TopCharts”, etc)
 * @example: iOS Store sheets:  “Sheet” (e.g. AppStore page launched as a sheet within Mail, Springboard’s “Near Me”, Maps’ “Nearby Apps”)
 * @example a "hint", "related" click, "filter" click, etc.
 * If this event is representing a plain typed dialog, this field's value may be null
 * @param {varargs} callerSuppliedEventFieldsMapN a variable number of Object arguments from 0-N, each containing key/value pairs representing event fields to include with the returned metricsData
 * All event fields will be merged.
 * An attempt will be made to invoke an accessor method for each field, providing the caller the opportunity to override accessor methods.
 * If no accessor method is found, the event field value will be included in the returned metricsData as-is.
 * Later objects take precedence over earlier ones, overriding any field value that may have already been there.
 * If this parameter is null or omitted, only the known page fields will be included
 * @example metrics.eventHandlers.page.metricsData(appData.pageId, appData.pageType, appData.pageContext, element, {some:"some", known:"known", eventFieldValues:"eventFieldValues"}, someOtherKnownEventValues, appData.someAdditionalBaseFieldValues);
 * @returns key/value pairs of all event fields + "base" fields required by Figaro.
 * WARNING: May return "null" if metrics are disabled via the metrics.disabled config source value, or on error.
 * @overridable
 */
Dialog.prototype.metricsData = function (pageId, pageType, pageContext /*, callerSuppliedEventFieldsMapN(varargs)*/) {
    return this.processMetricsData.apply(this, arguments);
};

/**
 * Returns all the fields that this eventHandler knows about.
 * The eventHandler may have accessor functions which derive some of these fields.
 * The "metricsData()" method will use this list of fields to attempt to invoke accessor methods to get field values.
 * Therefore, if callers override this function, and add additional values, and provide accessors for those values, then
 * the "metricsData()" function will ultimately call those accessors as well.
 * @return all the fields that this eventHandler knows about
 */
Dialog.prototype.knownFields = function knownFields() {
    var knownFields = ['buttons', 'code', 'details', 'message', 'type', 'eventType', 'eventVersion', 'type'];

    return knownFields;
};

/**
 * The type of event this is
 * @returns {String}
 * @overridable
 */
Dialog.prototype.eventType = function (callerSuppliedEventFields) {
    return 'dialog';
};

/**
 * The version of the set of data to be sent up
 * @returns {number}
 * @overridable
 */
Dialog.prototype.eventVersion = function (callerSuppliedEventFields) {
    // Since these have an additional field "type" beyond eventVersion 1 (sent via server-requested "GET" URL ping in MXPFailure.java)
    return (callerSuppliedEventFields && callerSuppliedEventFields.eventVersion) || 2;
};

/*
 *  src/metrics/event_handlers/enter.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2015 Apple Inc. All rights reserved.
 *
 */

/**
 * Creates and returns an object (key/value data map (dictionary)) containing all of the fields needed for this metrics event.
 * To override any functionality in this class, use the "setDelegate() method in order to override the specific functions that need customization.
 * @delegatable
 * @constructor
 */
var Enter = function (metricsKit) {
    ClickStreamEventHandler.apply(this, arguments);
};

Enter.prototype = Object.create(ClickStreamEventHandler.prototype);
Enter.prototype.constructor = Enter;

/**
 ************************************ 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.
 */
Enter.prototype.setDelegate = function setDelegate(delegate) {
    return reflect$1.attachDelegate(this, delegate);
};

/**
 * Creates a simple map object (dictionary) with all the fields required by Figaro for this event
 * Some fields can be derived by this class itself.
 * Some fields need to be provided by callers (e.g. pageId, pageType, pageContext)
 * @param {String} pageId required for all event creation. Indicates the id of the page this event took place on.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * The type of ID may vary (e.g. adam id, grouping id, result id, etc), but is generally
 * the identifier in some persistent store. Search Results pages may have a pageId which refers to their specific dataSet,
 * otherwise known as dataSetId. If the page is better identified by a descriptive string rather than a content ID,
 * this field may be hard-coded, but it should be unique within the set of pages displayable by the app.
 * If an application is not client/server "page" oriented (where the client needs to request data from the server for each "page" of the app), then
 * this field would be generated by the client.
 * Note: A unique "page" value will created by concatenating pageType+"_"+pageId
 * @param {String} pageType required for all event creation. Indicates the type of page this event took place on.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * This value should represent the group of pages (e.g. "Genre", “Album”, “Grouping”, "Picker", "Recommendations", "Feed",
 * "Search", "Subscribe", etc.).
 * If an application is not client/server "page" oriented (where the client needs to request data from the server for each "page" of the app), then
 * this field would be generated by the client (potentially being hard-coded).
 * Note: A unique "page" value will created by concatenating pageType+"_"+pageId
 * @param {String} pageContext required for all event creation. Indicates the context within which a page is viewed.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * Contexts usually provide independent streams of activity and can typically appear as UI "tab" elements or primary navigation elements.
 * @example: iTunes Desktop: “InTheStore” or “Main”.
 * @example: iOS iTunes apps: tab name (e.g. “Featured”, “TopCharts”, etc)
 * @example: iOS Store sheets:  “Sheet” (e.g. AppStore page launched as a sheet within Mail, Springboard’s “Near Me”, Maps’ “Nearby Apps”)
 * @example a "hint", "related" click, "filter" click, etc.
 * If this event is representing a plain typed enter, this field's value may be null
 * @param {varargs} callerSuppliedEventFieldsMapN a variable number of Object arguments from 0-N, each containing key/value pairs representing event fields to include with the returned metricsData
 * All event fields will be merged.
 * An attempt will be made to invoke an accessor method for each field, providing the caller the opportunity to override accessor methods.
 * If no accessor method is found, the event field value will be included in the returned metricsData as-is.
 * Later objects take precedence over earlier ones, overriding any field value that may have already been there.
 * If this parameter is null or omitted, only the known page fields will be included
 * @example metrics.eventHandlers.page.metricsData(appData.pageId, appData.pageType, appData.pageContext, element, {some:"some", known:"known", eventFieldValues:"eventFieldValues"}, someOtherKnownEventValues, appData.someAdditionalBaseFieldValues);
 * @returns key/value pairs of all event fields + "base" fields required by Figaro.
 * WARNING: May return "null" if metrics are disabled via the metrics.disabled config source value, or on error.
 * @overridable
 */
Enter.prototype.metricsData = function (pageId, pageType, pageContext /*, callerSuppliedEventFieldsMapN(varargs)*/) {
    return this.processMetricsData.apply(this, arguments);
};

/**
 * Returns all the fields that this eventHandler knows about.
 * The eventHandler may have accessor functions which derive some of these fields.
 * The "metricsData()" method will use this list of fields to attempt to invoke accessor methods to get field values.
 * Therefore, if callers override this function, and add additional values, and provide accessors for those values, then
 * the "metricsData()" function will ultimately call those accessors as well.
 * @return all the fields that this eventHandler knows about
 */
Enter.prototype.knownFields = function knownFields() {
    var knownFields = ['eventType', 'eventVersion', 'extRefUrl', 'osLanguages', 'refApp', 'type'];

    return knownFields;
};

/**
 * The type of event this is
 * @returns {String}
 * @overridable
 */
Enter.prototype.eventType = function (callerSuppliedEventFields) {
    return 'enter';
};

/**
 * The version of the set of data to be sent up
 * @returns {number}
 * @overridable
 */
Enter.prototype.eventVersion = function (callerSuppliedEventFields) {
    return (callerSuppliedEventFields && callerSuppliedEventFields.eventVersion) || 1;
};

/**
 * OS language preferences; a string array of language IDs, ordered in descending preference
 * @param {Map} callerSuppliedEventFields - NOTE: If you want to use one of these fields to help derive *this* eventField, you should
 * invoke its accessor, if one is available, in case *its* value is derived or massaged.
 * @returns {Array} a list of preferred languages (strings) e.g. ['en-US', 'fr-CA']
 * @overridable
 */
Enter.prototype.osLanguages = function osLanguages(callerSuppliedEventFields) {
    return (
        (callerSuppliedEventFields && callerSuppliedEventFields.osLanguages) ||
        this._processor.system.environment.osLanguages()
    );
};

/*
 *  src/metrics/event_handlers/exit.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2015 Apple Inc. All rights reserved.
 *
 */

/**
 * Creates and returns an object (key/value data map (dictionary)) containing all of the fields needed for this metrics event.
 * To override any functionality in this class, use the "setDelegate() method in order to override the specific functions that need customization.
 * @delegatable
 * @constructor
 */
var Exit = function (metricsKit) {
    ClickStreamEventHandler.apply(this, arguments);
};

Exit.prototype = Object.create(ClickStreamEventHandler.prototype);
Exit.prototype.constructor = Exit;

/**
 ************************************ 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.
 */
Exit.prototype.setDelegate = function setDelegate(delegate) {
    return reflect$1.attachDelegate(this, delegate);
};

/**
 * Creates a simple map object (dictionary) with all the fields required by Figaro for this event
 * Some fields can be derived by this class itself.
 * Some fields need to be provided by callers (e.g. pageId, pageType, pageContext)
 * @param {String} pageId required for all event creation. Indicates the id of the page this event took place on.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * The type of ID may vary (e.g. adam id, grouping id, result id, etc), but is generally
 * the identifier in some persistent store. Search Results pages may have a pageId which refers to their specific dataSet,
 * otherwise known as dataSetId. If the page is better identified by a descriptive string rather than a content ID,
 * this field may be hard-coded, but it should be unique within the set of pages displayable by the app.
 * If an application is not client/server "page" oriented (where the client needs to request data from the server for each "page" of the app), then
 * this field would be generated by the client.
 * Note: A unique "page" value will created by concatenating pageType+"_"+pageId
 * @param {String} pageType required for all event creation. Indicates the type of page this event took place on.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * This value should represent the group of pages (e.g. "Genre", “Album”, “Grouping”, "Picker", "Recommendations", "Feed",
 * "Search", "Subscribe", etc.).
 * If an application is not client/server "page" oriented (where the client needs to request data from the server for each "page" of the app), then
 * this field would be generated by the client (potentially being hard-coded).
 * Note: A unique "page" value will created by concatenating pageType+"_"+pageId
 * @param {String} pageContext required for all event creation. Indicates the context within which a page is viewed.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * Contexts usually provide independent streams of activity and can typically appear as UI "tab" elements or primary navigation elements.
 * @example: iTunes Desktop: “InTheStore” or “Main”.
 * @example: iOS iTunes apps: tab name (e.g. “Featured”, “TopCharts”, etc)
 * @example: iOS Store sheets:  “Sheet” (e.g. AppStore page launched as a sheet within Mail, Springboard’s “Near Me”, Maps’ “Nearby Apps”)
 * @example a "hint", "related" click, "filter" click, etc.
 * If this event is representing a plain typed exit, this field's value may be null
 * @param {varargs} callerSuppliedEventFieldsMapN a variable number of Object arguments from 0-N, each containing key/value pairs representing event fields to include with the returned metricsData
 * All event fields will be merged.
 * An attempt will be made to invoke an accessor method for each field, providing the caller the opportunity to override accessor methods.
 * If no accessor method is found, the event field value will be included in the returned metricsData as-is.
 * Later objects take precedence over earlier ones, overriding any field value that may have already been there.
 * If this parameter is null or omitted, only the known page fields will be included
 * @example metrics.eventHandlers.page.metricsData(appData.pageId, appData.pageType, appData.pageContext, element, {some:"some", known:"known", eventFieldValues:"eventFieldValues"}, someOtherKnownEventValues, appData.someAdditionalBaseFieldValues);
 * @returns key/value pairs of all event fields + "base" fields required by Figaro.
 * WARNING: May return "null" if metrics are disabled via the metrics.disabled config source value, or on error.
 * @overridable
 */
Exit.prototype.metricsData = function (pageId, pageType, pageContext /*, callerSuppliedEventFieldsMapN(varargs)*/) {
    return this.processMetricsData.apply(this, arguments);
};

/**
 * Returns all the fields that this eventHandler knows about.
 * The eventHandler may have accessor functions which derive some of these fields.
 * The "metricsData()" method will use this list of fields to attempt to invoke accessor methods to get field values.
 * Therefore, if callers override this function, and add additional values, and provide accessors for those values, then
 * the "metricsData()" function will ultimately call those accessors as well.
 * @return all the fields that this eventHandler knows about
 */
Exit.prototype.knownFields = function knownFields() {
    var knownFields = ['destinationUrl', 'eventType', 'eventVersion', 'type'];

    return knownFields;
};

/**
 * The type of event this is
 * @returns {String}
 * @overridable
 */
Exit.prototype.eventType = function (callerSuppliedEventFields) {
    return 'exit';
};

/**
 * The version of the set of data to be sent up
 * @returns {number}
 * @overridable
 */
Exit.prototype.eventVersion = function (callerSuppliedEventFields) {
    return (callerSuppliedEventFields && callerSuppliedEventFields.eventVersion) || 1;
};

/*
 *  src/metrics/event_handlers/flexible.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2015 Apple Inc. All rights reserved.
 *
 */

/**
 * Creates and returns an object (key/value data map (dictionary)) containing all of the fields needed for this metrics event.
 * To override any functionality in this class, use the "setDelegate() method in order to override the specific functions that need customization.
 * @delegatable
 * @constructor
 */
var Flexible = function (metricsKit) {
    ClickStreamEventHandler.apply(this, arguments);
};

Flexible.prototype = Object.create(ClickStreamEventHandler.prototype);
Flexible.prototype.constructor = Flexible;

/**
 ************************************ PUBLIC METHODS/IVARS ************************************
 */

/**
 * Creates a simple map object (dictionary)
 * @param {String} eventType required for all event creation.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * @param {varargs} callerSuppliedEventFieldsMapN a variable number of Object arguments from 0-N, each containing key/value pairs representing event fields to include with the returned metricsData
 * All event fields will be merged.
 * An attempt will be made to invoke an accessor method for each field, providing the caller the opportunity to override accessor methods.
 * If no accessor method is found, the event field value will be included in the returned metricsData as-is.
 * Later objects take precedence over earlier ones, overriding any field value that may have already been there.
 * If this parameter is null or omitted, only the known page fields will be included
 * @example metrics.eventHandlers.flexible.metricsData('anEventType', {some:"some", known:"known", eventFieldValues:"eventFieldValues"}, someOtherKnownEventValues, appData.someAdditionalBaseFieldValues);
 * @returns {Promise} A promise that will return key/value pairs of all event fields, merged and cleaned (removes keys that are typeof 'function', keys with 'null' values, keys with 'undefined' values)
 * WARNING: The Promise may return "null" if metrics are disabled via the metrics.disabled config source value, or on error.
 * @overridable
 */
Flexible.prototype.metricsData = function (eventType /*, callerSuppliedEventFieldsMapN(varargs)*/) {
    var eventData = [undefined, undefined, undefined]; // leave page fields undefined

    // include eventType so it gets processed
    eventData.push({ eventType: eventType });

    var callerSuppliedEventFieldsMapsArray = Array.prototype.slice.call(arguments, 1);
    eventData = eventData.concat(callerSuppliedEventFieldsMapsArray);

    return this.processMetricsData.apply(this, eventData);
};

/**
 * Returns all the fields that this eventHandler knows about.
 * The eventHandler may have accessor functions which derive some of these fields.
 * The "metricsData()" method will use this list of fields to attempt to invoke accessor methods to get field values.
 * Therefore, if callers override this function, and add additional values, and provide accessors for those values, then
 * the "metricsData()" function will ultimately call those accessors as well.
 * @return all the fields that this eventHandler knows about
 */
Flexible.prototype.knownFields = function knownFields() {
    var knownFields = ['eventTime', 'eventType'];

    return knownFields;
};

/**
 * A flag indicating whether this event should include base fields. Defaults to false for flexible events.
 * @returns {Boolean}
 * @overridable
 */
Flexible.prototype.mtIncludeBaseFields = function mtIncludeBaseFields() {
    return false;
};

/**
 * The time (UTC) in milliseconds at which this event happened.
 * This field is central to determining the sequence of user events
 * Use online epoch converter to test your values.
 * @example 1437356433388 (http://www.epochconverter.com converts that to:  July 19, 2015 at 6:40:33 PM PDT GMT-7:00 DST)
 * @param {Map} callerSuppliedEventFields - NOTE: If you want to use one of these fields to help derive *this* eventField, you should
 * invoke it's accessor, if one is available, in case *it's* value is derived or massaged.
 * @returns {number} the time (UTC) in milliseconds at which this event happened
 * @overridable
 */
Flexible.prototype.eventTime = function eventTime(callerSuppliedEventFields) {
    return (callerSuppliedEventFields && callerSuppliedEventFields.eventTime) || Date.now();
};

/**
 * The type of event this is
 * @returns {String}
 * @overridable
 */
Flexible.prototype.eventType = function (callerSuppliedEventFields) {
    return (callerSuppliedEventFields && callerSuppliedEventFields.eventType) || undefined;
};

/*
 *  src/metrics/event_handlers/impressions.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2015 Apple Inc. All rights reserved.
 *
 */

/**
 * Creates and returns an object (key/value data map (dictionary)) containing all of the fields needed for this metrics event.
 * To override any functionality in this class, use the "setDelegate() method in order to override the specific functions that need customization.
 * @delegatable
 * @constructor
 */
var Impressions = function (metricsKit) {
    ClickStreamEventHandler.apply(this, arguments);
};

Impressions.prototype = Object.create(ClickStreamEventHandler.prototype);
Impressions.prototype.constructor = Impressions;

/**
 ************************************ 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.
 */
Impressions.prototype.setDelegate = function setDelegate(delegate) {
    return reflect$1.attachDelegate(this, delegate);
};

/**
 * Creates a simple map object (dictionary) with all the fields required by Figaro for this event
 * Some fields can be derived by this class itself.
 * Some fields need to be provided by callers (e.g. pageId, pageType, pageContext)
 * @param {String} pageId required for all event creation. Indicates the id of the page this event took place on.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * The type of ID may vary (e.g. adam id, grouping id, result id, etc), but is generally
 * the identifier in some persistent store. Search Results pages may have a pageId which refers to their specific dataSet,
 * otherwise known as dataSetId. If the page is better identified by a descriptive string rather than a content ID,
 * this field may be hard-coded, but it should be unique within the set of pages displayable by the app.
 * If an application is not client/server "page" oriented (where the client needs to request data from the server for each "page" of the app), then
 * this field would be generated by the client.
 * Note: A unique "page" value will created by concatenating pageType+"_"+pageId
 * @param {String} pageType required for all event creation. Indicates the type of page this event took place on.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * This value should represent the group of pages (e.g. "Genre", “Album”, “Grouping”, "Picker", "Recommendations", "Feed",
 * "Search", "Subscribe", etc.).
 * If an application is not client/server "page" oriented (where the client needs to request data from the server for each "page" of the app), then
 * this field would be generated by the client (potentially being hard-coded).
 * Note: A unique "page" value will created by concatenating pageType+"_"+pageId
 * @param {String} pageContext required for all event creation. Indicates the context within which a page is viewed.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * Contexts usually provide independent streams of activity and can typically appear as UI "tab" elements or primary navigation elements.
 * @example: iTunes Desktop: “InTheStore” or “Main”.
 * @example: iOS iTunes apps: tab name (e.g. “Featured”, “TopCharts”, etc)
 * @example: iOS Store sheets:  “Sheet” (e.g. AppStore page launched as a sheet within Mail, Springboard’s “Near Me”, Maps’ “Nearby Apps”)
 * @param {varargs} callerSuppliedEventFieldsMapN a variable number of Object arguments from 0-N, each containing key/value pairs representing event fields to include with the returned metricsData
 * All event fields will be merged.
 * An attempt will be made to invoke an accessor method for each field, providing the caller the opportunity to override accessor methods.
 * If no accessor method is found, the event field value will be included in the returned metricsData as-is.
 * Later objects take precedence over earlier ones, overriding any field value that may have already been there.
 * If this parameter is null or omitted, only the known page fields will be included
 * @example metrics.eventHandlers.page.metricsData(appData.pageId, appData.pageType, appData.pageContext, element, {some:"some", known:"known", eventFieldValues:"eventFieldValues"}, someOtherKnownEventValues, appData.someAdditionalBaseFieldValues);
 * @returns key/value pairs of all event fields + "base" fields required by Figaro.
 * WARNING: May return "null" if metrics are disabled via the metrics.disabled config source value, or on error.
 * @overridable
 */
Impressions.prototype.metricsData = function (
    pageId,
    pageType,
    pageContext /*, callerSuppliedEventFieldsMapN(varargs)*/
) {
    return this.processMetricsData.apply(this, arguments);
};

/**
 * Returns all the fields that this eventHandler knows about.
 * The eventHandler may have accessor functions which derive some of these fields.
 * The "metricsData()" method will use this list of fields to attempt to invoke accessor methods to get field values.
 * Therefore, if callers override this function, and add additional values, and provide accessors for those values, then
 * the "metricsData()" function will ultimately call those accessors as well.
 * @return all the fields that this eventHandler knows about
 */
Impressions.prototype.knownFields = function knownFields() {
    var knownFields = ['eventType', 'eventVersion', 'impressions', 'xpViewablePercentage', 'xpViewableThreshold'];

    return knownFields;
};

/**
 * The type of event this is
 * @returns {String}
 * @overridable
 */
Impressions.prototype.eventType = function (callerSuppliedEventFields) {
    return 'impressions';
};

/**
 * The version of the set of data to be sent up
 * @returns {number}
 * @overridable
 */
Impressions.prototype.eventVersion = function (callerSuppliedEventFields) {
    return (callerSuppliedEventFields && callerSuppliedEventFields.eventVersion) || 3;
};

/**
 * A list of flattened impression objects for this event
 * Default behavior assumes the impressions have already been flattened and just returns them, but clients can override this with their own flattening implementation
 * @returns {Array} an array of impression objects, or undefined if no event fields were provided by the caller
 * @overridable
 */
Impressions.prototype.impressions = function impressions(callerSuppliedEventFields) {
    return callerSuppliedEventFields ? callerSuppliedEventFields.impressions : undefined;
};

/**
 * The percentage, from 0 to 1, that an item should be on screen before being considered impressionable
 * This field should be based on the client's most recent config value of "viewablePercentage".
 * @returns {number} the percentage, from 0 to 1, that an item should be on screen before being considered impressionable
 * @overridable
 */
Impressions.prototype.xpViewablePercentage = function xpViewablePercentage(callerSuppliedEventFields) {
    var base = this._processor.eventHandlers.base;
    return base.xpViewablePercentage(callerSuppliedEventFields);
};

/**
 * The continuous duration, in milliseconds, that an item should be on screen before being considered impressed
 * This field should be based on the client's most recent config value of "viewableThreshold".
 * This is valuable for problem analysis because it indicates if and how clients are honoring the "viewableThreshold" value
 * they were supplied with.
 * This cannot be a "passthrough" field, because it can change (via new config) during program execution, so the value
 * in effect at event creation time is what is needed.
 * @example 1000
 * @param {Map} callerSuppliedEventFields - NOTE: If you want to use one of these fields to help derive *this* eventField, you should
 * invoke it's accessor, if one is available, in case *it's* value is derived or massaged.
 * @returns {number} the continuous duration, in milliseconds, that an item should be on screen before being considered impressed
 * @overridable
 */
Impressions.prototype.xpViewableThreshold = function xpViewableThreshold(callerSuppliedEventFields) {
    var config = this._processor.config;
    return (
        (callerSuppliedEventFields && callerSuppliedEventFields.xpViewableThreshold) ||
        config.value('impressions.viewableThreshold')
    );
};

/*
 *  src/metrics/event_handlers/media.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2015 Apple Inc. All rights reserved.
 *
 */

/**
 * Creates and returns an object (key/value data map (dictionary)) containing all of the "media" fields + all of the "base" events common to all metrics events.
 * To override any functionality in this class, use the "utils.override() method in order to override the specific functions that need customization.
 * @delegatable
 * @constructor
 */
var Media = function (metricsKit) {
    ClickStreamEventHandler.apply(this, arguments);
};

Media.prototype = Object.create(ClickStreamEventHandler.prototype);
Media.prototype.constructor = Media;

/**
 * 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.
 */
Media.prototype.setDelegate = function setDelegate(delegate) {
    return reflect$1.attachDelegate(this, delegate);
};

/**
 * Creates a simple map object (dictionary) with all the fields required by Figaro
 * Some fields can be derived by this class itself.
 * Some fields need to be provided by callers (e.g. pageId, pageType, pageContext)
 * @param {String} pageId required for all event creation. Indicates the id of the page this event took place on.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * The type of ID may vary (e.g. adam id, grouping id, result id, etc), but is generally
 * the identifier in some persistent store. Search Results pages may have a pageId which refers to their specific dataSet,
 * otherwise known as dataSetId. If the page is better identified by a descriptive string rather than a content ID,
 * this field may be hard-coded, but it should be unique within the set of pages displayable by the app.
 * If an application is not client/server "page" oriented (where the client needs to request data from the server for each "page" of the app), then
 * this field would be generated by the client.
 * Note: A unique "page" value will created by concatenating pageType+"_"+pageId
 * @param {String} pageType required for all event creation. Indicates the type of page this event took place on.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * This value should represent the group of pages (e.g. "Genre", “Album”, “Grouping”, "Picker", "Recommendations", "Feed",
 * "Search", "Subscribe", etc.).
 * If an application is not client/server "page" oriented (where the client needs to request data from the server for each "page" of the app), then
 * this field would be generated by the client (potentially being hard-coded).
 * Note: A unique "page" value will created by concatenating pageType+"_"+pageId
 * @param {String} pageContext required for all event creation. Indicates the context within which a page is viewed.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * Contexts usually provide independent streams of activity and can typically appear as UI "tab" elements or primary navigation elements.
 * @example: iTunes Desktop: “InTheStore” or “Main”.
 * @example: iOS iTunes apps: tab name (e.g. “Featured”, “TopCharts”, etc)
 * @example: iOS Store sheets:  “Sheet” (e.g. AppStore page launched as a sheet within Mail, Springboard’s “Near Me”, Maps’ “Nearby Apps”)
 * @param {varargs} callerSuppliedEventFieldsMapN a variable number of Object arguments from 0-N, each containing key/value pairs representing event fields to include with the returned metricsData
 * All event fields will be merged.
 * An attempt will be made to invoke an accessor method for each field, providing the caller the opportunity to override accessor methods.
 * If no accessor method is found, the event field value will be included in the returned metricsData as-is.
 * Later objects take precedence over earlier ones, overriding any field value that may have already been there.
 * If this parameter is null or omitted, only the known page fields will be included
 * @example metrics.eventHandlers.media.metricsData(appData.pageId, appData.pageType, appData.pageContext, {some:"some", known:"known", eventFieldValues:"eventFieldValues"}, someOtherKnownEventValues, appData.someAdditionalBaseFieldValues);
 * @returns key/value pairs of all event fields + "base" fields required by Figaro.
 * WARNING: May return "null" if metrics are disabled via the metrics.disabled config source value, or on error.
 * @overridable
 */
Media.prototype.metricsData = function (pageId, pageType, pageContext /*, callerSuppliedEventFieldsMapN(varargs)*/) {
    return this.processMetricsData.apply(this, arguments);
};

/**
 * Returns all the fields that this eventHandler knows about.
 * The eventHandler may have accessor functions which derive some of these fields.
 * The "metricsData()" method will use this list of fields to attempt to invoke accessor methods to get field values.
 * Therefore, if callers override this function, and add additional values, and provide accessors for those values, then
 * the "metricsData()" function will ultimately call those accessors as well.
 * @return all the fields that this eventHandler knows about
 */
Media.prototype.knownFields = function knownFields() {
    var knownFields = [
        'eventType',
        'eventVersion',
        'id',
        'idType',
        'type',
        'typeDetails',
        'actionType',
        'actionDetails',
        'url',
        'duration',
        'position'
    ];
    return knownFields;
};

// ********************* ACCESSOR FUNCTIONS *********************
/**
 * We create accessor functions for every data field because:
 * 1. Cleans/simplifies all methods that use it.
 * 2. Facilitates writing test case shims
 * 3. Allows specific feature suppliers to be overridden (via setDelegate())
 */

/**
 * The type of event this is
 * @returns {String}
 * @overridable
 */
Media.prototype.eventType = function (callerSuppliedEventFields) {
    return 'media';
};

/**
 * The version of the set of data to be sent up
 * @returns {number}
 * @overridable
 */
Media.prototype.eventVersion = function (callerSuppliedEventFields) {
    return (callerSuppliedEventFields && callerSuppliedEventFields.eventVersion) || 1;
};

/*
 *  src/metrics/event_handlers/page.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2015 Apple Inc. All rights reserved.
 *
 */

/**
 * Creates and returns an object (key/value data map (dictionary)) containing all of the "page" fields + all of the "base" events common to all metrics events.
 * To override any functionality in this class, use the "utils.override() method in order to override the specific functions that need customization.
 * @delegatable
 * @constructor
 */
var Page = function (metricsKit) {
    ClickStreamEventHandler.apply(this, arguments);
    // @private
    this.pageHistoryCache = [];
};

Page.prototype = Object.create(ClickStreamEventHandler.prototype);
Page.prototype.constructor = Page;

/**
 ************************************ 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.
 */
Page.prototype.setDelegate = function setDelegate(delegate) {
    return reflect$1.attachDelegate(this, delegate);
};

/**
 * Creates a simple map object (dictionary) with all the fields required by Figaro
 * Some fields can be derived by this class itself.
 * Some fields need to be provided by callers (e.g. pageId, pageType, pageContext)
 * @param {String} pageId required for all event creation. Indicates the id of the page this event took place on.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * The type of ID may vary (e.g. adam id, grouping id, result id, etc), but is generally
 * the identifier in some persistent store. Search Results pages may have a pageId which refers to their specific dataSet,
 * otherwise known as dataSetId. If the page is better identified by a descriptive string rather than a content ID,
 * this field may be hard-coded, but it should be unique within the set of pages displayable by the app.
 * If an application is not client/server "page" oriented (where the client needs to request data from the server for each "page" of the app), then
 * this field would be generated by the client.
 * Note: A unique "page" value will created by concatenating pageType+"_"+pageId
 * @param {String} pageType required for all event creation. Indicates the type of page this event took place on.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * This value should represent the group of pages (e.g. "Genre", “Album”, “Grouping”, "Picker", "Recommendations", "Feed",
 * "Search", "Subscribe", etc.).
 * If an application is not client/server "page" oriented (where the client needs to request data from the server for each "page" of the app), then
 * this field would be generated by the client (potentially being hard-coded).
 * Note: A unique "page" value will created by concatenating pageType+"_"+pageId
 * @param {String} pageContext required for all event creation. Indicates the context within which a page is viewed.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * Contexts usually provide independent streams of activity and can typically appear as UI "tab" elements or primary navigation elements.
 * @example: iTunes Desktop: “InTheStore” or “Main”.
 * @example: iOS iTunes apps: tab name (e.g. “Featured”, “TopCharts”, etc)
 * @example: iOS Store sheets:  “Sheet” (e.g. AppStore page launched as a sheet within Mail, Springboard’s “Near Me”, Maps’ “Nearby Apps”)
 * @param {varargs} callerSuppliedEventFieldsMapN a variable number of Object arguments from 0-N, each containing key/value pairs representing event fields to include with the returned metricsData
 * All event fields will be merged.
 * An attempt will be made to invoke an accessor method for each field, providing the caller the opportunity to override accessor methods.
 * If no accessor method is found, the event field value will be included in the returned metricsData as-is.
 * Later objects take precedence over earlier ones, overriding any field value that may have already been there.
 * If this parameter is null or omitted, only the known page fields will be included
 * @example metrics.eventHandlers.page.metricsData(appData.pageId, appData.pageType, appData.pageContext, {some:"some", known:"known", eventFieldValues:"eventFieldValues"}, someOtherKnownEventValues, appData.someAdditionalBaseFieldValues);
 * @returns key/value pairs of all event fields + "base" fields required by Figaro.
 * WARNING: May return "null" if metrics are disabled via the metrics.disabled config source value, or on error.
 * @overridable
 */
Page.prototype.metricsData = function (pageId, pageType, pageContext /*, callerSuppliedEventFieldsMapN(varargs)*/) {
    return this.processMetricsData.apply(this, arguments);
};

/**
 * Returns all the fields that this eventHandler knows about.
 * The eventHandler may have accessor functions which derive some of these fields.
 * The "metricsData()" method will use this list of fields to attempt to invoke accessor methods to get field values.
 * Therefore, if callers override this function, and add additional values, and provide accessors for those values, then
 * the "metricsData()" function will ultimately call those accessors as well.
 * @return all the fields that this eventHandler knows about
 */
Page.prototype.knownFields = function knownFields() {
    var knownFields = [
        'eventType',
        'eventVersion',
        'extRefUrl',
        'hostApp',
        'refApp',
        'refUrl',
        'requestStartTime',
        'responseStartTime',
        'responseEndTime',
        'pageHistory',
        'pageLoadTime',
        'pageRenderTime',
        'searchFilters',
        'searchTerm'
    ];

    return knownFields;
};

// ********************* ACCESSOR FUNCTIONS *********************
/**
 * We create accessor functions for every data field because:
 * 1. Cleans/simplifies all methods that use it.
 * 2. Facilitates writing test case shims
 * 3. Allows specific feature suppliers to be overridden (via setDelegate())
 */

/**
 * The type of event this is
 * @returns {String}
 * @overridable
 */
Page.prototype.eventType = function (callerSuppliedEventFields) {
    return 'page';
};

/**
 * The version of the set of data to be sent up
 * @returns {number}
 * @overridable
 */
Page.prototype.eventVersion = function (callerSuppliedEventFields) {
    return (callerSuppliedEventFields && callerSuppliedEventFields.eventVersion) || 1;
};

/**
 * If a value for this accessor's field exists in "callerSuppliedEventFields", the accessor may want to honor the caller's desire and return that, iff no massaging is needed.
 * Returns an array of the past <= 5 values of 'page' fields from prior page events,
 * storing the current value for use in the next request
 * @param {Map} callerSuppliedEventFields - NOTE: If you want to use one of these fields to help derive *this* eventField, you should
 * invoke it's accessor, if one is available, in case *it's* value is derived or massaged.
 * @return {Array} The past 5 or fewer page event's 'page' fields, *not including* the current page.
 */
Page.prototype.pageHistory = function pageHistory(callerSuppliedEventFields) {
    var returnValue;

    callerSuppliedEventFields = callerSuppliedEventFields || {};
    if (callerSuppliedEventFields.pageHistory) {
        returnValue = callerSuppliedEventFields.pageHistory;
    } else {
        returnValue = this.pageHistoryCache.slice(0); // returns a clone
        var currentPageName = callerSuppliedEventFields.page;

        if (currentPageName) {
            if (this.pageHistoryCache.length >= 5) {
                this.pageHistoryCache.shift();
            }
            this.pageHistoryCache.push(currentPageName);
        }
    }
    return returnValue;
};

/*
 *  src/metrics/event_handlers/search.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2015 Apple Inc. All rights reserved.
 *
 */

/**
 * Creates and returns an object (key/value data map (dictionary)) containing all of the fields needed for this metrics event.
 * To override any functionality in this class, use the "setDelegate() method in order to override the specific functions that need customization.
 * @delegatable
 * @constructor
 */
var Search = function (metricsKit) {
    ClickStreamEventHandler.apply(this, arguments);
};

Search.prototype = Object.create(ClickStreamEventHandler.prototype);
Search.prototype.constructor = Search;

/**
 ************************************ 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.
 */
Search.prototype.setDelegate = function setDelegate(delegate) {
    return reflect$1.attachDelegate(this, delegate);
};

/**
 * Creates a simple map object (dictionary) with all the fields required by Figaro for this event
 * Some fields can be derived by this class itself.
 * Some fields need to be provided by callers (e.g. pageId, pageType, pageContext)
 * @param {String} pageId required for all event creation. Indicates the id of the page this event took place on.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * The type of ID may vary (e.g. adam id, grouping id, result id, etc), but is generally
 * the identifier in some persistent store. Search Results pages may have a pageId which refers to their specific dataSet,
 * otherwise known as dataSetId. If the page is better identified by a descriptive string rather than a content ID,
 * this field may be hard-coded, but it should be unique within the set of pages displayable by the app.
 * If an application is not client/server "page" oriented (where the client needs to request data from the server for each "page" of the app), then
 * this field would be generated by the client.
 * Note: A unique "page" value will created by concatenating pageType+"_"+pageId
 * @param {String} pageType required for all event creation. Indicates the type of page this event took place on.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * This value should represent the group of pages (e.g. "Genre", “Album”, “Grouping”, "Picker", "Recommendations", "Feed",
 * "Search", "Subscribe", etc.).
 * If an application is not client/server "page" oriented (where the client needs to request data from the server for each "page" of the app), then
 * this field would be generated by the client (potentially being hard-coded).
 * Note: A unique "page" value will created by concatenating pageType+"_"+pageId
 * @param {String} pageContext required for all event creation. Indicates the context within which a page is viewed.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * Contexts usually provide independent streams of activity and can typically appear as UI "tab" elements or primary navigation elements.
 * @example: iTunes Desktop: “InTheStore” or “Main”.
 * @example: iOS iTunes apps: tab name (e.g. “Featured”, “TopCharts”, etc)
 * @example: iOS Store sheets:  “Sheet” (e.g. AppStore page launched as a sheet within Mail, Springboard’s “Near Me”, Maps’ “Nearby Apps”)
 * @example a "hint", "related" click, "filter" click, etc.
 * If this event is representing a plain typed search, this field's value may be null
 * @param {varargs} callerSuppliedEventFieldsMapN a variable number of Object arguments from 0-N, each containing key/value pairs representing event fields to include with the returned metricsData
 * All event fields will be merged.
 * An attempt will be made to invoke an accessor method for each field, providing the caller the opportunity to override accessor methods.
 * If no accessor method is found, the event field value will be included in the returned metricsData as-is.
 * Later objects take precedence over earlier ones, overriding any field value that may have already been there.
 * If this parameter is null or omitted, only the known page fields will be included
 * @example metrics.eventHandlers.page.metricsData(appData.pageId, appData.pageType, appData.pageContext, element, {some:"some", known:"known", eventFieldValues:"eventFieldValues"}, someOtherKnownEventValues, appData.someAdditionalBaseFieldValues);
 * @returns key/value pairs of all event fields + "base" fields required by Figaro.
 * WARNING: May return "null" if metrics are disabled via the metrics.disabled config source value, or on error.
 * @overridable
 */
Search.prototype.metricsData = function (pageId, pageType, pageContext /*, callerSuppliedEventFieldsMapN(varargs)*/) {
    // TODO:ATHOMPSON: Add back in with ability to add/not add targetElement param
    return this.processMetricsData.apply(this, arguments);
};

/**
 * Returns all the fields that this eventHandler knows about.
 * The eventHandler may have accessor functions which derive some of these fields.
 * The "metricsData()" method will use this list of fields to attempt to invoke accessor methods to get field values.
 * Therefore, if callers override this function, and add additional values, and provide accessors for those values, then
 * the "metricsData()" function will ultimately call those accessors as well.
 * @return all the fields that this eventHandler knows about
 */
Search.prototype.knownFields = function knownFields() {
    var knownFields = [
        'actionDetails',
        'actionType',
        'actionUrl',
        'eventType',
        'eventVersion',
        'filters',
        'location',
        'targetId',
        'targetType',
        'term'
    ];

    return knownFields;
};

/**
 * The type of event this is
 * @returns {String}
 * @overridable
 */
Search.prototype.eventType = function (callerSuppliedEventFields) {
    return 'search';
};

/**
 * The version of the set of data to be sent up
 * @returns {number}
 * @overridable
 */
Search.prototype.eventVersion = function (callerSuppliedEventFields) {
    return (callerSuppliedEventFields && callerSuppliedEventFields.eventVersion) || 2;
};

/*
 *  src/metrics/event_handlers/transaction.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2015 Apple Inc. All rights reserved.
 *
 */

/**
 * Creates and returns an object (key/value data map (dictionary)) containing all of the fields needed for this metrics event.
 * To override any functionality in this class, use the "setDelegate() method in order to override the specific functions that need customization.
 * @delegatable
 * @constructor
 */
var Transaction = function (metricsKit) {
    ClickStreamEventHandler.apply(this, arguments);
};

Transaction.prototype = Object.create(ClickStreamEventHandler.prototype);
Transaction.prototype.constructor = Transaction;

/**
 ************************************ 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.
 */
Transaction.prototype.setDelegate = function setDelegate(delegate) {
    return reflect$1.attachDelegate(this, delegate);
};

/**
 * Creates a simple map object (dictionary) with all the fields required by Figaro for this event
 * Some fields can be derived by this class itself.
 * Some fields need to be provided by callers (e.g. the transaction fields and values)
 * @param {Map<String:Any>} transactionMetrics key/value pairs associated with this transaction; typically provided in the response from the buyProduct endpoint
 * @param {varargs} callerSuppliedEventFieldsMapN a variable number of Object arguments from 0-N, each containing key/value pairs representing event fields to include with the returned metricsData
 * All event fields will be merged.
 * An attempt will be made to invoke an accessor method for each field, providing the caller the opportunity to override accessor methods.
 * If no accessor method is found, the event field value will be included in the returned metricsData as-is.
 * Later objects take precedence over earlier ones, overriding any field value that may have already been there.
 * If this parameter is null or omitted, only the transaction metrics will be included
 * @example metrics.eventHandlers.transaction.metricsData(buyProductResponseMetrics, {some:"some", known:"known", eventFieldValues:"eventFieldValues"}, someOtherKnownEventValues, appData.someAdditionalBaseFieldValues);
 * @returns key/value pairs of all event fields + "base" fields required by Figaro.
 * WARNING: May return "null" if metrics are disabled via the metrics.disabled config source value, or on error.
 * @overridable
 */
Transaction.prototype.metricsData = function metricsData(
    transactionMetrics /*, callerSuppliedEventFieldsMapN(varargs)*/
) {
    var argsArray = [null, null, null].concat(Array.prototype.slice.call(arguments));
    return this.processMetricsData.apply(this, argsArray);
};

/**
 * Returns all the fields that this eventHandler knows about.
 * The eventHandler may have accessor functions which derive some of these fields.
 * The "metricsData()" method will use this list of fields to attempt to invoke accessor methods to get field values.
 * Therefore, if callers override this function, and add additional values, and provide accessors for those values, then
 * the "metricsData()" function will ultimately call those accessors as well.
 * @return all the fields that this eventHandler knows about
 */
Transaction.prototype.knownFields = function knownFields() {
    var knownFields = ['eventType', 'eventVersion'];

    return knownFields;
};

/**
 * The type of event this is
 * @returns {String}
 * @overridable
 */
Transaction.prototype.eventType = function (callerSuppliedEventFields) {
    return 'transaction';
};

/**
 * The version of the set of data to be sent up
 * @returns {number}
 * @overridable
 */
Transaction.prototype.eventVersion = function (callerSuppliedEventFields) {
    return (callerSuppliedEventFields && callerSuppliedEventFields.eventVersion) || 1;
};

/*
 *  src/metrics/event_handlers/index.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2015 Apple Inc. All rights reserved.
 *
 */

var EventHandlers = function (metricsKitInstance) {
    this.account = new Account(metricsKitInstance);
    this.base = new ClickstreamProcessorBase(metricsKitInstance);
    this.buyConfirmed = new BuyConfirmed(metricsKitInstance);
    this.click = new Click(metricsKitInstance);
    this.dialog = new Dialog(metricsKitInstance);
    this.enter = new Enter(metricsKitInstance);
    this.exit = new Exit(metricsKitInstance);
    this.flexible = new Flexible(metricsKitInstance);
    this.impressions = new Impressions(metricsKitInstance);
    this.media = new Media(metricsKitInstance);
    this.page = new Page(metricsKitInstance);
    this.search = new Search(metricsKitInstance);
    this.transaction = new Transaction(metricsKitInstance);

    delegateExtension.attachDelegateInfo(this.account);
    delegateExtension.attachDelegateInfo(this.base);
    delegateExtension.attachDelegateInfo(this.buyConfirmed);
    delegateExtension.attachDelegateInfo(this.click);
    delegateExtension.attachDelegateInfo(this.enter);
    delegateExtension.attachDelegateInfo(this.exit);
    delegateExtension.attachDelegateInfo(this.flexible);
    delegateExtension.attachDelegateInfo(this.impressions);
    delegateExtension.attachDelegateInfo(this.media);
    delegateExtension.attachDelegateInfo(this.page);
    delegateExtension.attachDelegateInfo(this.search);
    delegateExtension.attachDelegateInfo(this.transaction);
};

/*
 *  src/metrics/utils/event_fields.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2015 Apple Inc. All rights reserved.
 *
 */

/**
 * Removes duplicate impressions from an array of sibling impressions (i.e. impressions with the same parent) based on whether its index is unique
 * This is needed because the impressions spec:
 *      https://connectme.apple.com/docs/DOC-240953
 * states that:
 *      iii. If items come into view, then go out of view, then come back, they are not counted twice.
 * So, if a user scrolls a swoosh away from a lockup, and then back, so that the lockup is in view again, it will appear twice (with the same index-within-parent) in the impressions-object-tree
 * returned from ITMLKit, but we don't want it included twice, so we remove the dupes here.
 * NOTE: This should never happen with an impressions list retrieved via "itms.snapshotImpressions()" but for caller-simplicity, and since our caller is typically walking the tree already, some of our callers may invoke it even when unnecessary.
 * @param  {Array} impressions An array of impressions to dedupe
 * @return {Array} A set of unique impressions
 */
var dedupeSiblingImpressions = function (impressions) {
    var uniqueIndices = {};
    var dedupedSiblingImpressions = [];
    var currentIndex;
    if (impressions && impressions[0] && impressions[0].index !== undefined) {
        for (var i = 0; i < impressions.length; ++i) {
            currentIndex = impressions[i].index;
            if (!uniqueIndices[currentIndex]) {
                uniqueIndices[currentIndex] = true;
                dedupedSiblingImpressions.push(impressions[i]);
            }
        }
    }
    return dedupedSiblingImpressions;
};

/**
 * These routines are useful for clients to create and access Metrics data and config
 * @constructor
 */
var EventFields$1 = function (processor) {
    // @private
    this._processor = processor;
};

/**
 ************************************ PUBLIC METHODS/IVARS ************************************
 */
/**
 * Uses the provided id to generate its idType
 * @param {String} idString The id to generate a type for
 * @param {String} (Optional) separator id separator, if not provided, this function will return a Promise otherwise the function will return the id string.
 * @return {Promise|String} returns a string of the idType of the provided id if providing separator otherwise returns a Promise
 */
EventFields$1.prototype.getIdType = function (idString, separator) {
    var config = this._processor.config;
    var defaultPrefix = 'its';
    var prefixSeparatorIndex = idString.indexOf('.');
    var prefix = prefixSeparatorIndex !== -1 ? idString.substring(0, prefixSeparatorIndex) : defaultPrefix;

    return reflect$1.isString(separator)
        ? prefix + separator + 'id'
        : config.value('compoundSeparator').then(function (separator) {
              return prefix + separator + 'id';
          });
};

/**
 * This method is the workhorse of all the various eventHandlers.
 * It will take all of the parameters of the callers "metricsData()" method, merge them together,
 * invoke accessors on their known fields, and return the resultant map.
 * @param eventHandler the calling eventHandler
 * @param knownFields the calling eventHandler's list (array) of strings that are that handler's known field values.
 * If the caller has accessors to be invoked, they must be present in the "knownFields" array
 * @returns {Arguments} all of the arguments that the calling eventHandler received.
 * @example:
 * Page.prototype.metricsData = function(pageId, pageType, pageContext, eventFieldsMapN(varargs))
 *      {return utils.eventFields.processMetricsData(this, arguments);
 */
EventFields$1.prototype.processMetricsData = function (
    eventHandler,
    knownFields,
    pageId,
    pageType,
    pageContext,
    callerSuppliedEventFieldsMapsArray
) {
    // Combine all passed-in fields...
    var combinedFieldsMapsArray = [
        {
            pageId: pageId,
            pageType: pageType,
            pageContext: pageContext
        }
    ];
    if (reflect$1.isArray(callerSuppliedEventFieldsMapsArray)) {
        combinedFieldsMapsArray = combinedFieldsMapsArray.concat(callerSuppliedEventFieldsMapsArray);
    }

    return eventFields.processMetricsData(eventHandler, knownFields, true, combinedFieldsMapsArray);
};
/**
 * Returns an object containing the intersection of properties in
 * data and matching string values in the fieldMap property corresponding to 'sectionName'
 * ( e.g. fieldMap.custom[sectionName] is an object containing arrays of strings which
 * correspond to the keys desired in the mappedFields object )
 * @param {Object} data The model data corresponding to element we're mapping fields for
 * @param {String} sectionName Specifies which custom fieldMap to use (eg: 'impressions', 'location', or 'custom')
 * @return {Promise} A Promise that returns an object contains intersection of data and fieldsMap values
 * @example
 * // where impressionFieldsMapSection = {
 * //   impressionType: ['type', 'impressionType'],
 * //   id: ['targetId', 'id']
 * //};
 * applyFieldsMap({type: 'button', id: '123', name: 'playbutton'}, 'impressions')
 * // returns {impressionType: 'button', id: '123'}
 */
EventFields$1.prototype.applyFieldsMap = function (data, sectionName) {
    var config = this._processor.config;
    var self = this;

    if (data && sectionName) {
        return config.value('fieldsMap').then(function (fieldsMap) {
            var mappedFields = {};
            fieldsMap = fieldsMap || {};
            var fieldsMapSection = keyValue.valueForKeyPath(sectionName, fieldsMap, fieldsMap.custom);
            if (fieldsMapSection) {
                var i;
                if (Array.isArray(fieldsMapSection)) {
                    for (i = 0; i < fieldsMapSection.length; ++i) {
                        if (data[fieldsMapSection[i]]) {
                            mappedFields[fieldsMapSection[i]] = data[fieldsMapSection[i]];
                        }
                    }
                } else if (typeof fieldsMapSection === 'object') {
                    for (var key in fieldsMapSection) {
                        for (i = 0; i < fieldsMapSection[key].length; ++i) {
                            var value = keyValue.valueForKeyPath(fieldsMapSection[key][i], data);
                            if (value) {
                                mappedFields[key] = value;
                                break;
                            }
                        }
                    }
                } else {
                    self._processor.system.logger.error(
                        'mt-metricskit-processor-clickstream: incorrect data type provided to applyFieldsMap (only accepts objects and Arrays)'
                    );
                }
            } else {
                self._processor.system.logger.error(
                    'mt-metricskit-processor-clickstream: unable to get fieldsMap from config-source'
                );
            }

            return mappedFields;
        });
    } else {
        if (!data) {
            this._processor.system.logger.error(
                'mt-metricskit-processor-clickstream: No data provided to applyFieldsMap'
            );
        }
        if (!sectionName) {
            this._processor.system.logger.error(
                'mt-metricskit-processor-clickstream: No sectionName provided to applyFieldsMap'
            );
        }
        return Promise.resolve(undefined);
    }
};
/**
 * Creates a deduped & flattened representation of the list of impressions tree nodes provided
 * reassigns some impressions values for use with metrics processing
 * @param {Array} impressions Array of IKJSImpressions objects
 * @param {number} currentId The index at which to increment impresionId off of
 * @return {Promise} A Promise returns impressionsArray array of Objects corresponding to and created from data in impressions
 */
EventFields$1.prototype.flattenImpressions = function (impressions, currentId) {
    var config = this._processor.config;

    // Because this function needs to load "compoundSeparator" from config in the loop and also recursively build impressions.
    // So create the internal flattenImpressions function to make we load the  "compoundSeparator" outside of the function to make the function simple and clean.
    var recursivelyFlattenImpressions = function recursivelyFlattenImpressions(impressions, currentId, separator) {
        var impressionsArray = [];
        var anImpression;
        var impressionData;
        var childrenArray;
        var decodedData;
        var impressionId = currentId || 1;

        if (impressions) {
            impressions = dedupeSiblingImpressions(impressions);
            for (var i = 0; i < impressions.length; i++) {
                anImpression = impressions[i];
                if (typeof anImpression.data === 'string') {
                    try {
                        impressionData = JSON.parse(anImpression.data);
                    } catch (anException) {
                        // Lets' see if the exception happened because someone put URIEncoded data in the impression...
                        decodedData = decodeURIComponent(anImpression.data);
                        try {
                            impressionData = JSON.parse(decodedData);
                        } catch (anotherException) {
                            // So, the error is not [necessarily] due to encoding. Let's not stop the app here by letting this exception propogate, throw the original exception.
                            // (see the discussion about catching exceptions here in this radar: <rdar://problem/23810404> Metricskit: JSON parse error in flattenImpressions
                            this._processor.system.logger.error(
                                'mt-metricskit-processor-clickstream: non-JSON serialized data found on impression object. Cannot parse.',
                                anException
                            );
                        }
                    }
                } else {
                    impressionData = anImpression;
                }
                if (impressionData) {
                    impressionData.impressionTimes = anImpression.timestamps;
                    impressionData.impressionIndex = anImpression.index;
                    if (impressionData.id && !impressionData.idType) {
                        if (anImpression.kind === 'genre') {
                            // Remove when server provides genre id prefixes
                            impressionData.idType = 'label' + separator + 'id';
                        } else {
                            impressionData.idType = this.getIdType(impressionData.id.toString(), separator);
                        }
                    }
                    if (anImpression.parent && anImpression.parent.impressionId !== undefined) {
                        // if no parent, parent === null
                        impressionData.impressionParentId = anImpression.parent.impressionId;
                    }
                    impressionData.impressionId = impressionId;
                    anImpression.impressionId = impressionId; // saves this value for use as parentId
                    ++impressionId;
                    impressionsArray.push(impressionData);
                    if (keyValue.valueForKeyPath('children.length', anImpression) > 0) {
                        childrenArray = recursivelyFlattenImpressions(anImpression.children, impressionId, separator);
                        impressionsArray = impressionsArray.concat(childrenArray);
                        impressionId += childrenArray.length;
                    }
                }
            }
        } else {
            this._processor.system.logger.warn('Fuse-Metrics: No impressions provided to to flattenImpressions');
        }

        return impressionsArray;
    }.bind(this);

    return config.value('compoundSeparator').then(function (separator) {
        return recursivelyFlattenImpressions(impressions, currentId, separator);
    });
};

/**
 * Returns a flat array representing the location of the clicked element
 * @param {Object} targetElement The clicked element, requires attribute data-metrics-location with obj key of locationType
 * @param {Function} locationFn a function that takes an element as an argument and calculates
 *     the location dictionary for that element
 * @return {Array} A flat array representing the location of the target element
 */
EventFields$1.prototype.buildLocationStructure = function buildLocationStructure(targetElement, locationFn) {
    var currentElement = targetElement;
    var locationStack = [];
    var location;

    //loop and add element locations to the the location stack to be returned
    while (currentElement) {
        location = locationFn.call(locationFn, currentElement);
        if (location) {
            locationStack.push(location);
        }

        currentElement = currentElement.parentNode;
    }
    return locationStack;
};

/*
 *  src/network.js
 *  mt-metricskit-processor-clickstream
 *
 *  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$1.attachDelegate(this, delegate);
};

/**
 * Covers private util network functions for delegation
 */
Network.prototype.makeAjaxRequest = network.makeAjaxRequest;

/*
 *  src/metrics/utils/reflect.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2015 Apple Inc. All rights reserved.
 *
 */

/**
 * Object Reflection Primitive Methods (e.g. "Map" type methods)
 * copied from private utils so delegate callers can use them
 * @constructor
 */
var reflect = {
    /**
     ************************************ PUBLIC METHODS/IVARS ************************************
     */
    /**
     * Replace any "target" methods found on "delegate" with the delegate's version of the method.
     * The replacement function will actually be our own wrapper function with the original function attached as a property called origFunction
     * in case the delegate's replacement method wants to, essentially, call "super"
     * We do delegation this way, vs. checking each time a "target" function is called, because this way we don't pollute the implementation
     * of all the target's functions.
     * Subsequent calls to "attachDelegate" will then replace whatever methods *they* match, including methods that have already been replaced.
     * This allows callers to use "canned" delegates to get most of their functionality, but still replace some number of methods that need custom implementations.
     * NOTE: Only methods present on "target" will be replaced. If a delegate method is not found on target, "false" will be returned.
     * If a replaced method is overridden again with a subsequent "setDelegate()" call, the "origFunction" property will be the previous delegate's function.
     * @param target
     * @param delegate
     * @returns {Boolean} true if one or more methods on the delegate object match one or more methods on the default object,
     */
    attachDelegate: function attachDelegate(target, delegate) {
        return reflect$1.attachDelegate(target, delegate);
    },

    /**
     * Adds all the fields of the objects in the varargs to the fields in the first parameter, "obj".
     * *All* "hasOwnProperty" fields will be added, including functions and fields with no values.
     * @param {Object} targetObject an object with keys and values. If only one parameter is provided, the return value will be the non-null values of that single object.
     * @param {varargs} sourceObjectN a variable number of Object arguments from 0-N. Each object's fields will be copied into targetObject. Later objects take precedence over earlier ones.
     * @return targetObject (*not* a clone) with the additional fields added..
     */
    extend: function extend(targetObject /* , ...sourceObjectN(varargs) */) {
        return reflect$1.extend.apply(reflect$1, arguments);
    },

    /**
     * Bind the execution context of the methods of given Object to itself.
     * NOTE: Only bind the functions that are owned by the parameter object
     * @param {Object} targetObject an object with keys and values.
     */
    bindFunctionsContext: function bindFunctionsContext(targetObject) {
        if (targetObject) {
            for (var key in targetObject) {
                if (typeof targetObject[key] === 'function') {
                    targetObject[key] = targetObject[key].bind(targetObject);
                }
            }
        }
    }
};

/*
 *  src/metrics/utils/string.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2015-2017 Apple Inc. All rights reserved.
 *
 */

/**
 * String related util methods
 * copied from private utils so delegate callers can use them
 * @constructor
 */
var string = {
    /**
     ************************************ PUBLIC METHODS/IVARS ************************************
     */
    /**
     * Parses a user agent string for a particular product name and returns its version
     * @param {String} userAgent that conforms with RFC 7231 section 5.5.3 regarding User-Agents
     * @param {String} (optional) productName the name of a product identifier to search for e.g. 'iTunes'; if omitted, defaults to the first identifier
     * @return {String} the version of the product, or null if none found
     * @example
     *      productVersionFromUserAgent('iTunes/12.6 (Macintosh; OS X 10.12.4) AppleWebKit/603.1.30.0.34') returns '12.6'
     *      productVersionFromUserAgent('iTunes/12.6 (Macintosh; OS X 10.12.4) AppleWebKit/603.1.30.0.34', 'AppleWebKit') returns '603.1.30.0.34'
     *      productVersionFromUserAgent('iTunes/12.6 (Macintosh; OS X 10.12.4) AppleWebKit/603.1.30.0.34', 'Macintosh') returns null
     *          (strings contained in parentheses are counted as comments, not product identifiers)
     */
    versionStringFromUserAgent: function versionStringFromUserAgent(userAgent, productName) {
        return string$1.versionStringFromUserAgent(userAgent, productName);
    }
};

/*
 *  src/metrics/utils/index.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2015-2016 Apple Inc. All rights reserved.
 *
 */

var Utils = function Utils(mtkitInstance) {
    // TODO if no client is using it, maybe it could be removed from Utils class
    this.delegateExtension = delegateExtension;
    // assign new eventFields instance to utils, to give eventFields the metricsKit instance context.
    this.eventFields = new EventFields$1(mtkitInstance);
    // bind the context to eventHandlers to avoid losing the runtime context if the client assign function to a variable.
    reflect.bindFunctionsContext(this.eventFields);

    // copy keyValue from private utils for historical reasons in case clients are using it
    // this can probably be removed with more research
    // TODO if no client is using it, maybe it could be removed from Utils class
    this.keyValue = keyValue;
    this.network = new Network();
    // TODO if no client is using it, maybe it could be removed from Utils class
    this.reflect = reflect;
    // TODO if no client is using it, maybe it could be removed from Utils class
    this.string = string;
};

/*
 *  src/utils/event_field_accessors/base.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2021 Apple Inc. All rights reserved.
 *
 */

var Base = function (metricsKit) {
    // @private
    this._eventHandler = new Flexible(metricsKit);
};

/**
 ************************************ PUBLIC METHODS ************************************
 */

/**
 * Return the corresponding clientId with the giving status
 * @param {Object} qualifiers
 * @param {Boolean} qualifiers.isSignedIn - A boolean value indicating the returned clientId is for signed-in status or signed-out status.
 * @returns {Promise} A Promise that resolved the clientId, will return null if
 *      1. the entire event is denied by config
 *      2. the clientId is a denied field
 */
Base.prototype.clientId = function clientId(qualifiers) {
    return this._eventHandler
        .metricsData('', qualifiers)
        .toJSON()
        .then(function (eventFields) {
            return eventFields ? eventFields.clientId : null;
        });
};

/*
 *  src/event_fields/index.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2021 Apple Inc. All rights reserved.
 *
 */

var EventFields = function (metricsKitInstance) {
    this.base = new Base(metricsKitInstance);
};

/*
 *  src/metrics/clickstream_processor.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2020 Apple Inc. All rights reserved.
 *
 */

/**
 * Supplies a JavaScript entrypoint to metrics functionality
 * Since JavaScript is prototype-based and not class-based, and  doesn't provide an "official" object model, this API is presented as a functional API, but still retains the ability to
 * override and customize functionality via the "setDelegate()" method. In this way, it doesn't carry with it the spare baggage of exposing a bolt-on object model which may
 * differ from a bolt-on (or homegrown) object model already existing in the app.
 * @module src/metrics
 * @param {Object}  delegates - The below interface will be generated by Metrics delegates(mt-metricskit-delegates-*). Clients don't have to generate it by themselves
 *                               For more details, please reference the respective document of mt-metricskit-delegates-*
 * @constructor
 */
var ClickstreamProcessor = function ClickstreamProcessor(delegates) {
    if (!reflect$1.isDefinedNonNull(delegates)) {
        throw new Error('No delegate is provided to ClickstreamProcessor');
    }

    /**
     ************************************ PRIVATE IVARS ************************************
     */

    // @private
    this._initCalled = false;

    // @private
    this._delegatePackage = delegates;

    /**
     ************************************ PUBLIC METHODS/IVARS ************************************
     */

    /**
     * Access the various "system" classes defined in ClickstreamProcessor.
     * These classes are typically system/platform specific
     * These classes can have their functionality replaced either en masse or piecemeal via the setDelegate() method.
     * Available system classes are:
     *      environment
     *      eventRecorder
     *      logger
     * @example: metrics.system.environment.setDelegate(myEnvironmentFunctions)
     * @see setDelegate()
     */
    this.system = new System();

    /**
     * Access the various configuration values.
     * These are basically pretty wrappers on config fields retrieved via the "configValue" method.
     * Note: Must be created in the constructor in order for a client to set a debug source before fetching config with init()
     * @example: metrics.config.isDisabled()
     */
    this.config = this._delegatePackage.config;

    /**
     * Sub-library providing access to all the various eventHandlers of ClickstreamProcessor.
     */
    this.eventHandlers = new EventHandlers(this);

    /**
     * Sub-library providing access to all the various eventFields of ClickstreamProcessor.
     */
    this.eventFields = new EventFields(this);

    /**
     * Sub-library providing various utility functions which are useful when interacting with ClickstreamProcessor
     */
    this.utils = new Utils(this);

    this._constraints = null;
};

/**
 * Initialize ClickstreamProcessor - will register, fetch config, set delegates, etc.
 * NOTE: This API should not be called more than once. Subsequent calls will have no effect (no-op).
 * NOTE 2: This function initializes metrics config values which are required for proper event generation.
 *         This initialization will be asynchronous unless a configSourcesFn is provided.
 *         Events that are generated before initialization have completed will use config defaults.
 *         If clients want to ensure that config is fetched before events are generated,
 *         they can do one of the following when calling clickstreamProcessor.init():
 *                (1) provide a configSourcesFn; in existing clients the config sources function is provided via the metrics.config.setDelegate() API
 *                (2) wait until the init() callback completes before generating and recording any events (Note that when using this method,
 *                    any user actions that occured before the callback completes will have later eventTimes than when they actually occured)
 *
 * ADDITIONAL DESIGN NOTES:
 * Promise/PubSub:
 *     These would require some polyfill or additional module support, which we do not want to bake into our framework.
 *     We will expect that clients will honor the init() contract by not calling it more than once, and we provide a completion callback.
 * Deferring event generation:
 *     We could store a queue of events to generate once we have config. However, this is complex and error prone, and requires
 *     the eventRecorder to have special knowledge that this is happening and knowledge about how to properly generate those events
 *     (for example, the eventTime should reflect the time the deferred event was queued, not the time it was later generated).
 * Using defaults:
 *     Most config values are common to the majority of apps and do not change very much, so in the interest of simplicity,
 *     we choose to fall back to default config values for any events generated before config resolves.
 *     The ingestion server will enrich clientId on events in a batch missing clientId.
 *     As an additional fallback, we store the most recently fetched config in localStorage for any future visits from the same browser.
 *
 *  @returns {Promise} A Promise that resolved the MetricsKit initialization
 */
ClickstreamProcessor.prototype.init = function init() {
    var initPromise = Promise.resolve();
    if (!this._initCalled) {
        this._initCalled = true;

        // set any provided delegates
        if (this._delegatePackage) {
            reflect$1.setDelegates(this.eventHandlers, this._delegatePackage);
            reflect$1.setDelegates(this.system, this._delegatePackage);
            // TODO rdar://92551827 (Add test case for clickstream processor delegate initialization)
            reflect$1.setDelegates(this.utils, this._delegatePackage);
        }

        // Init config
        initializeConfig(this.config);
        initPromise = this._delegatePackage.init();

        this._constraints = new Constraints(this.config, {
            environment: this.system.environment
        });
    }

    return initPromise;
};

/**
 * Release resources from MetricsKit
 */
ClickstreamProcessor.prototype.cleanup = function cleanup() {
    if (this._delegatePackage && reflect$1.isFunction(this._delegatePackage.cleanup)) {
        // cleanup delegate before cleanup config, in case the cleanup method of delegate uses the config
        this._delegatePackage.cleanup();
    }
    cleanupConfig(this.config);
    reflect$1.resetDelegates(this.eventHandlers);
    reflect$1.resetDelegates(this.system);
    reflect$1.resetDelegates(this.utils);
    this.config = null;
    this.system = null;
    this.eventHandlers = null;
    this.utils = null;
    this._delegatePackage = null;
    this._constraints = null;
    this._initCalled = false;
};

export { ClickstreamProcessor };