summaryrefslogtreecommitdiffstats
path: root/toolkit/components/ml/vendor/ort-dev.js
blob: 8c53b1521de4f2dfaa6f71d8dba066af83902c25 (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
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359
15360
15361
15362
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378
15379
15380
15381
15382
15383
15384
15385
15386
15387
15388
15389
15390
15391
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407
15408
15409
15410
15411
15412
15413
15414
15415
15416
15417
15418
15419
15420
15421
15422
15423
15424
15425
15426
15427
15428
15429
15430
15431
15432
15433
15434
15435
15436
15437
15438
15439
15440
15441
15442
15443
15444
15445
15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504
15505
15506
15507
15508
15509
15510
15511
15512
15513
15514
15515
15516
15517
15518
15519
15520
15521
15522
15523
15524
15525
15526
15527
15528
15529
15530
15531
15532
15533
15534
15535
15536
15537
15538
15539
15540
15541
15542
15543
15544
15545
15546
15547
15548
15549
15550
15551
15552
15553
15554
15555
15556
15557
15558
15559
15560
15561
15562
15563
15564
15565
15566
15567
15568
15569
15570
15571
15572
15573
15574
15575
15576
15577
15578
15579
15580
15581
15582
15583
15584
15585
15586
15587
15588
15589
15590
15591
15592
15593
15594
15595
15596
15597
15598
15599
15600
15601
15602
15603
15604
15605
15606
15607
15608
15609
15610
15611
15612
15613
15614
15615
15616
15617
15618
15619
15620
15621
15622
15623
15624
15625
15626
15627
15628
15629
15630
15631
15632
15633
15634
15635
15636
15637
15638
15639
15640
15641
15642
15643
15644
15645
15646
15647
15648
15649
15650
15651
15652
15653
15654
15655
15656
15657
15658
15659
15660
15661
15662
15663
15664
15665
15666
15667
15668
15669
15670
15671
15672
15673
15674
15675
15676
15677
15678
15679
15680
15681
15682
15683
15684
15685
15686
15687
15688
15689
15690
15691
15692
15693
15694
15695
15696
15697
15698
15699
15700
15701
15702
15703
15704
15705
15706
15707
15708
15709
15710
15711
15712
15713
15714
15715
15716
15717
15718
15719
15720
15721
15722
15723
15724
15725
15726
15727
15728
15729
15730
15731
15732
15733
15734
15735
15736
15737
15738
15739
15740
15741
15742
15743
15744
15745
15746
15747
15748
15749
15750
15751
15752
15753
15754
15755
15756
15757
15758
15759
15760
15761
15762
15763
15764
15765
15766
15767
15768
15769
15770
15771
15772
15773
15774
15775
15776
15777
15778
15779
15780
15781
15782
15783
15784
15785
15786
15787
15788
15789
15790
15791
15792
15793
15794
15795
15796
15797
15798
15799
15800
15801
15802
15803
15804
15805
15806
15807
15808
15809
15810
15811
15812
15813
15814
15815
15816
15817
15818
15819
15820
15821
15822
15823
15824
15825
15826
15827
15828
15829
15830
15831
15832
15833
15834
15835
15836
15837
15838
15839
15840
15841
15842
15843
15844
15845
15846
15847
15848
15849
15850
15851
15852
15853
15854
15855
15856
15857
15858
15859
15860
15861
15862
15863
15864
15865
15866
15867
15868
15869
15870
15871
15872
15873
15874
15875
15876
15877
15878
15879
15880
15881
15882
15883
15884
15885
15886
15887
15888
15889
15890
15891
15892
15893
15894
15895
15896
15897
15898
15899
15900
15901
15902
15903
15904
15905
15906
15907
15908
15909
15910
15911
15912
15913
15914
15915
15916
15917
15918
15919
15920
15921
15922
15923
15924
15925
15926
15927
15928
15929
15930
15931
15932
15933
15934
15935
15936
15937
15938
15939
15940
15941
15942
15943
15944
15945
15946
15947
15948
15949
15950
15951
15952
15953
15954
15955
15956
15957
15958
15959
15960
15961
15962
15963
15964
15965
15966
15967
15968
15969
15970
15971
15972
15973
15974
15975
15976
15977
15978
15979
15980
15981
15982
15983
15984
15985
15986
15987
15988
15989
15990
15991
15992
15993
15994
15995
15996
15997
15998
15999
16000
16001
16002
16003
16004
16005
16006
16007
16008
16009
16010
16011
16012
16013
16014
16015
16016
16017
16018
16019
16020
16021
16022
16023
16024
16025
16026
16027
16028
16029
16030
16031
16032
16033
16034
16035
16036
16037
16038
16039
16040
16041
16042
16043
16044
16045
16046
16047
16048
16049
16050
16051
16052
16053
16054
16055
16056
16057
16058
16059
16060
16061
16062
16063
16064
16065
16066
16067
16068
16069
16070
16071
16072
16073
16074
16075
16076
16077
16078
16079
16080
16081
16082
16083
16084
16085
16086
16087
16088
16089
16090
16091
16092
16093
16094
16095
16096
16097
16098
16099
16100
16101
16102
16103
16104
16105
16106
16107
16108
16109
16110
16111
16112
16113
16114
16115
16116
16117
16118
16119
16120
16121
16122
16123
16124
16125
16126
16127
16128
16129
16130
16131
16132
16133
16134
16135
16136
16137
16138
16139
16140
16141
16142
16143
16144
16145
16146
16147
16148
16149
16150
16151
16152
16153
16154
16155
16156
16157
16158
16159
16160
16161
16162
16163
16164
16165
16166
16167
16168
16169
16170
16171
16172
16173
16174
16175
16176
16177
16178
16179
16180
16181
16182
16183
16184
16185
16186
16187
16188
16189
16190
16191
16192
16193
16194
16195
16196
16197
16198
16199
16200
16201
16202
16203
16204
16205
16206
16207
16208
16209
16210
16211
16212
16213
16214
16215
16216
16217
16218
16219
16220
16221
16222
16223
16224
16225
16226
16227
16228
16229
16230
16231
16232
16233
16234
16235
16236
16237
16238
16239
16240
16241
16242
16243
16244
16245
16246
16247
16248
16249
16250
16251
16252
16253
16254
16255
16256
16257
16258
16259
16260
16261
16262
16263
16264
16265
16266
16267
16268
16269
16270
16271
16272
16273
16274
16275
16276
16277
16278
16279
16280
16281
16282
16283
16284
16285
16286
16287
16288
16289
16290
16291
16292
16293
16294
16295
16296
16297
16298
16299
16300
16301
16302
16303
16304
16305
16306
16307
16308
16309
16310
16311
16312
16313
16314
16315
16316
16317
16318
16319
16320
16321
16322
16323
16324
16325
16326
16327
16328
16329
16330
16331
16332
16333
16334
16335
16336
16337
16338
16339
16340
16341
16342
16343
16344
16345
16346
16347
16348
16349
16350
16351
16352
16353
16354
16355
16356
16357
16358
16359
16360
16361
16362
16363
16364
16365
16366
16367
16368
16369
16370
16371
16372
16373
16374
16375
16376
16377
16378
16379
16380
16381
16382
16383
16384
16385
16386
16387
16388
16389
16390
16391
16392
16393
16394
16395
16396
16397
16398
16399
16400
16401
16402
16403
16404
16405
16406
16407
16408
16409
16410
16411
16412
16413
16414
16415
16416
16417
16418
16419
16420
16421
16422
16423
16424
16425
16426
16427
16428
16429
16430
16431
16432
16433
16434
16435
16436
16437
16438
16439
16440
16441
16442
16443
16444
16445
16446
16447
16448
16449
16450
16451
16452
16453
16454
16455
16456
16457
16458
16459
16460
16461
16462
16463
16464
16465
16466
16467
16468
16469
16470
16471
16472
16473
16474
16475
16476
16477
16478
16479
16480
16481
16482
16483
16484
16485
16486
16487
16488
16489
16490
16491
16492
16493
16494
16495
16496
16497
16498
16499
16500
16501
16502
16503
16504
16505
16506
16507
16508
16509
16510
16511
16512
16513
16514
16515
16516
16517
16518
16519
16520
16521
16522
16523
16524
16525
16526
16527
16528
16529
16530
16531
16532
16533
16534
16535
16536
16537
16538
16539
16540
16541
16542
16543
16544
16545
16546
16547
16548
16549
16550
16551
16552
16553
16554
16555
16556
16557
16558
16559
16560
16561
16562
16563
16564
16565
16566
16567
16568
16569
16570
16571
16572
16573
16574
16575
16576
16577
16578
16579
16580
16581
16582
16583
16584
16585
16586
16587
16588
16589
16590
16591
16592
16593
16594
16595
16596
16597
16598
16599
16600
16601
16602
16603
16604
16605
16606
16607
16608
16609
16610
16611
16612
16613
16614
16615
16616
16617
16618
16619
16620
16621
16622
16623
16624
16625
16626
16627
16628
16629
16630
16631
16632
16633
16634
16635
16636
16637
16638
16639
16640
16641
16642
16643
16644
16645
16646
16647
16648
16649
16650
16651
16652
16653
16654
16655
16656
16657
16658
16659
16660
16661
16662
16663
16664
16665
16666
16667
16668
16669
16670
16671
16672
16673
16674
16675
16676
16677
16678
16679
16680
16681
16682
16683
16684
16685
16686
16687
16688
16689
16690
16691
16692
16693
16694
16695
16696
16697
16698
16699
16700
16701
16702
16703
16704
16705
16706
16707
16708
16709
16710
16711
16712
16713
16714
16715
16716
16717
16718
16719
16720
16721
16722
16723
16724
16725
16726
16727
16728
16729
16730
16731
16732
16733
16734
16735
16736
16737
16738
16739
16740
16741
16742
16743
16744
16745
16746
16747
16748
16749
16750
16751
16752
16753
16754
16755
16756
16757
16758
16759
16760
16761
16762
16763
16764
16765
16766
16767
16768
16769
16770
16771
16772
16773
16774
16775
16776
16777
16778
16779
16780
16781
16782
16783
16784
16785
16786
16787
16788
16789
16790
16791
16792
16793
16794
16795
16796
16797
16798
16799
16800
16801
16802
16803
16804
16805
16806
16807
16808
16809
16810
16811
16812
16813
16814
16815
16816
16817
16818
16819
16820
16821
16822
16823
16824
16825
16826
16827
16828
16829
16830
16831
16832
16833
16834
16835
16836
16837
16838
16839
16840
16841
16842
16843
16844
16845
16846
16847
16848
16849
16850
16851
16852
16853
16854
16855
16856
16857
16858
16859
16860
16861
16862
16863
16864
16865
16866
16867
16868
16869
16870
16871
16872
16873
16874
16875
16876
16877
16878
16879
16880
16881
16882
16883
16884
16885
16886
16887
16888
16889
16890
16891
16892
16893
16894
16895
16896
16897
16898
16899
16900
16901
16902
16903
16904
16905
16906
16907
16908
16909
16910
16911
16912
16913
16914
16915
16916
16917
16918
16919
16920
16921
16922
16923
16924
16925
16926
16927
16928
16929
16930
16931
16932
16933
16934
16935
16936
16937
16938
16939
16940
16941
16942
16943
16944
16945
16946
16947
16948
16949
16950
16951
16952
16953
16954
16955
16956
16957
16958
16959
16960
16961
16962
16963
16964
16965
16966
16967
16968
16969
16970
16971
16972
16973
16974
16975
16976
16977
16978
16979
16980
16981
16982
16983
16984
16985
16986
16987
16988
16989
16990
16991
16992
16993
16994
16995
16996
16997
16998
16999
17000
17001
17002
17003
17004
17005
17006
17007
17008
17009
17010
17011
17012
17013
17014
17015
17016
17017
17018
17019
17020
17021
17022
17023
17024
17025
17026
17027
17028
17029
17030
17031
17032
17033
17034
17035
17036
17037
17038
17039
17040
17041
17042
17043
17044
17045
17046
17047
17048
17049
17050
17051
17052
17053
17054
17055
17056
17057
17058
17059
17060
17061
17062
17063
17064
17065
17066
17067
17068
17069
17070
17071
17072
17073
17074
17075
17076
17077
17078
17079
17080
17081
17082
17083
17084
17085
17086
17087
17088
17089
17090
17091
17092
17093
17094
17095
17096
17097
17098
17099
17100
17101
17102
17103
17104
17105
17106
17107
17108
17109
17110
17111
17112
17113
17114
17115
17116
17117
17118
17119
17120
17121
17122
17123
17124
17125
17126
17127
17128
17129
17130
17131
17132
17133
17134
17135
17136
17137
17138
17139
17140
17141
17142
17143
17144
17145
17146
17147
17148
17149
17150
17151
17152
17153
17154
17155
17156
17157
17158
17159
17160
17161
17162
17163
17164
17165
17166
17167
17168
17169
17170
17171
17172
17173
17174
17175
17176
17177
17178
17179
17180
17181
17182
17183
17184
17185
17186
17187
17188
17189
17190
17191
17192
17193
17194
17195
17196
17197
17198
17199
17200
17201
17202
17203
17204
17205
17206
17207
17208
17209
17210
17211
17212
17213
17214
17215
17216
17217
17218
17219
17220
17221
17222
17223
17224
17225
17226
17227
17228
17229
17230
17231
17232
17233
17234
17235
17236
17237
17238
17239
17240
17241
17242
17243
17244
17245
17246
17247
17248
17249
17250
17251
17252
17253
17254
17255
17256
17257
17258
17259
17260
17261
17262
17263
17264
17265
17266
17267
17268
17269
17270
17271
17272
17273
17274
17275
17276
17277
17278
17279
17280
17281
17282
17283
17284
17285
17286
17287
17288
17289
17290
17291
17292
17293
17294
17295
17296
17297
17298
17299
17300
17301
17302
17303
17304
17305
17306
17307
17308
17309
17310
17311
17312
17313
17314
17315
17316
17317
17318
17319
17320
17321
17322
17323
17324
17325
17326
17327
17328
17329
17330
17331
17332
17333
17334
17335
17336
17337
17338
17339
17340
17341
17342
17343
17344
17345
17346
17347
17348
17349
17350
17351
17352
17353
17354
17355
17356
17357
17358
17359
17360
17361
17362
17363
17364
17365
17366
17367
17368
17369
17370
17371
17372
17373
17374
17375
17376
17377
17378
17379
17380
17381
17382
17383
17384
17385
17386
17387
17388
17389
17390
17391
17392
17393
17394
17395
17396
17397
17398
17399
17400
17401
17402
17403
17404
17405
17406
17407
17408
17409
17410
17411
17412
17413
17414
17415
17416
17417
17418
17419
17420
17421
17422
17423
17424
17425
17426
17427
17428
17429
17430
17431
17432
17433
17434
17435
17436
17437
17438
17439
17440
17441
17442
17443
17444
17445
17446
17447
17448
17449
17450
17451
17452
17453
17454
17455
17456
17457
17458
17459
17460
17461
17462
17463
17464
17465
17466
17467
17468
17469
17470
17471
17472
17473
17474
17475
17476
17477
17478
17479
17480
17481
17482
17483
17484
17485
17486
17487
17488
17489
17490
17491
17492
17493
17494
17495
17496
17497
17498
17499
17500
17501
17502
17503
17504
17505
17506
17507
17508
17509
17510
17511
17512
17513
17514
17515
17516
17517
17518
17519
17520
17521
17522
17523
17524
17525
17526
17527
17528
17529
17530
17531
17532
17533
17534
17535
17536
17537
17538
17539
17540
17541
17542
17543
17544
17545
17546
17547
17548
17549
17550
17551
17552
17553
17554
17555
17556
17557
17558
17559
17560
17561
17562
17563
17564
17565
17566
17567
17568
17569
17570
17571
17572
17573
17574
17575
17576
17577
17578
17579
17580
17581
17582
17583
17584
17585
17586
17587
17588
17589
17590
17591
17592
17593
17594
17595
17596
17597
17598
17599
17600
17601
17602
17603
17604
17605
17606
17607
17608
17609
17610
17611
17612
17613
17614
17615
17616
17617
17618
17619
17620
17621
17622
17623
17624
17625
17626
17627
17628
17629
17630
17631
17632
17633
17634
17635
17636
17637
17638
17639
17640
17641
17642
17643
17644
17645
17646
17647
17648
17649
17650
17651
17652
17653
17654
17655
17656
17657
17658
17659
17660
17661
17662
17663
17664
17665
17666
17667
17668
17669
17670
17671
17672
17673
17674
17675
17676
17677
17678
17679
17680
17681
17682
17683
17684
17685
17686
17687
17688
17689
17690
17691
17692
17693
17694
17695
17696
17697
17698
17699
17700
17701
17702
17703
17704
17705
17706
17707
17708
17709
17710
17711
17712
17713
17714
17715
17716
17717
17718
17719
17720
17721
17722
17723
17724
17725
17726
17727
17728
17729
17730
17731
17732
17733
17734
17735
17736
17737
17738
17739
17740
17741
17742
17743
17744
17745
17746
17747
17748
17749
17750
17751
17752
17753
17754
17755
17756
17757
17758
17759
17760
17761
17762
17763
17764
17765
17766
17767
17768
17769
17770
17771
17772
17773
17774
17775
17776
17777
17778
17779
17780
17781
17782
17783
17784
17785
17786
17787
17788
17789
17790
17791
17792
17793
17794
17795
17796
17797
17798
17799
17800
17801
17802
17803
17804
17805
17806
17807
17808
17809
17810
17811
17812
17813
17814
17815
17816
17817
17818
17819
17820
17821
17822
17823
17824
17825
17826
17827
17828
17829
17830
17831
17832
17833
17834
17835
17836
17837
17838
17839
17840
17841
17842
17843
17844
17845
17846
17847
17848
17849
17850
17851
17852
17853
17854
17855
17856
17857
17858
17859
17860
17861
17862
17863
17864
17865
17866
17867
17868
17869
17870
17871
17872
17873
17874
17875
17876
17877
17878
17879
17880
17881
17882
17883
17884
17885
17886
17887
17888
17889
17890
17891
17892
17893
17894
17895
17896
17897
17898
17899
17900
17901
17902
17903
17904
17905
17906
17907
17908
17909
17910
17911
17912
17913
17914
17915
17916
17917
17918
17919
17920
17921
17922
17923
17924
17925
17926
17927
17928
17929
17930
17931
17932
17933
17934
17935
17936
17937
17938
17939
17940
17941
17942
17943
17944
17945
17946
17947
17948
17949
17950
17951
17952
17953
17954
17955
17956
17957
17958
17959
17960
17961
17962
17963
17964
17965
17966
17967
17968
17969
17970
17971
17972
17973
17974
17975
17976
17977
17978
17979
17980
17981
17982
17983
17984
17985
17986
17987
17988
17989
17990
17991
17992
17993
17994
17995
17996
17997
17998
17999
18000
18001
18002
18003
18004
18005
18006
18007
18008
18009
18010
18011
18012
18013
18014
18015
18016
18017
18018
18019
18020
18021
18022
18023
18024
18025
18026
18027
18028
18029
18030
18031
18032
18033
18034
18035
18036
18037
18038
18039
18040
18041
18042
18043
18044
18045
18046
18047
18048
18049
18050
18051
18052
18053
18054
18055
18056
18057
18058
18059
18060
18061
18062
18063
18064
18065
18066
18067
18068
18069
18070
18071
18072
18073
18074
18075
18076
18077
18078
18079
18080
18081
18082
18083
18084
18085
18086
18087
18088
18089
18090
18091
18092
18093
18094
18095
18096
18097
18098
18099
18100
18101
18102
18103
18104
18105
18106
18107
18108
18109
18110
18111
18112
18113
18114
18115
18116
18117
18118
18119
18120
18121
18122
18123
18124
18125
18126
18127
18128
18129
18130
18131
18132
18133
18134
18135
18136
18137
18138
18139
18140
18141
18142
18143
18144
18145
18146
18147
18148
18149
18150
18151
18152
18153
18154
18155
18156
18157
18158
18159
18160
18161
18162
18163
18164
18165
18166
18167
18168
18169
18170
18171
18172
18173
18174
18175
18176
18177
18178
18179
18180
18181
18182
18183
18184
18185
18186
18187
18188
18189
18190
18191
18192
18193
18194
18195
18196
18197
18198
18199
18200
18201
18202
18203
18204
18205
18206
18207
18208
18209
18210
18211
18212
18213
18214
18215
18216
18217
18218
18219
18220
18221
18222
18223
18224
18225
18226
18227
18228
18229
18230
18231
18232
18233
18234
18235
18236
18237
18238
18239
18240
18241
18242
18243
18244
18245
18246
18247
18248
18249
18250
18251
18252
18253
18254
18255
18256
18257
18258
18259
18260
18261
18262
18263
18264
18265
18266
18267
18268
18269
18270
18271
18272
18273
18274
18275
18276
18277
18278
18279
18280
18281
18282
18283
18284
18285
18286
18287
18288
18289
18290
18291
18292
18293
18294
18295
18296
18297
18298
18299
18300
18301
18302
18303
18304
18305
18306
18307
18308
18309
18310
18311
18312
18313
18314
18315
18316
18317
18318
18319
18320
18321
18322
18323
18324
18325
18326
18327
18328
18329
18330
18331
18332
18333
18334
18335
18336
18337
18338
18339
18340
18341
18342
18343
18344
18345
18346
18347
18348
18349
18350
18351
18352
18353
18354
18355
18356
18357
18358
18359
18360
18361
18362
18363
18364
18365
18366
18367
18368
18369
18370
18371
18372
18373
18374
18375
18376
18377
18378
18379
18380
18381
18382
18383
18384
18385
18386
18387
18388
18389
18390
18391
18392
18393
18394
18395
18396
18397
18398
18399
18400
18401
18402
18403
18404
18405
18406
18407
18408
18409
18410
18411
18412
18413
18414
18415
18416
18417
18418
18419
18420
18421
18422
18423
18424
18425
18426
18427
18428
18429
18430
18431
18432
18433
18434
18435
18436
18437
18438
18439
18440
18441
18442
18443
18444
18445
18446
18447
18448
18449
18450
18451
18452
18453
18454
18455
18456
18457
18458
18459
18460
18461
18462
18463
18464
18465
18466
18467
18468
18469
18470
18471
18472
18473
18474
18475
18476
18477
18478
18479
18480
18481
18482
18483
18484
18485
18486
18487
18488
18489
18490
18491
18492
18493
18494
18495
18496
18497
18498
18499
18500
18501
18502
18503
18504
18505
18506
18507
18508
18509
18510
18511
18512
18513
18514
18515
18516
18517
18518
18519
18520
18521
18522
18523
18524
18525
18526
18527
18528
18529
18530
18531
18532
18533
18534
18535
18536
18537
18538
18539
18540
18541
18542
18543
18544
18545
18546
18547
18548
18549
18550
18551
18552
18553
18554
18555
18556
18557
18558
18559
18560
18561
18562
18563
18564
18565
18566
18567
18568
18569
18570
18571
18572
18573
18574
18575
18576
18577
18578
18579
18580
18581
18582
18583
18584
18585
18586
18587
18588
18589
18590
18591
18592
18593
18594
18595
18596
18597
18598
18599
18600
18601
18602
18603
18604
18605
18606
18607
18608
18609
18610
18611
18612
18613
18614
18615
18616
18617
18618
18619
18620
18621
18622
18623
18624
18625
18626
18627
18628
18629
18630
18631
18632
18633
18634
18635
18636
18637
18638
18639
18640
18641
18642
18643
18644
18645
18646
18647
18648
18649
18650
18651
18652
18653
18654
18655
18656
18657
18658
18659
18660
18661
18662
18663
18664
18665
18666
18667
18668
18669
18670
18671
18672
18673
18674
18675
18676
18677
18678
18679
18680
18681
18682
18683
18684
18685
18686
18687
18688
18689
18690
18691
18692
18693
18694
18695
18696
18697
18698
18699
18700
18701
18702
18703
18704
18705
18706
18707
18708
18709
18710
18711
18712
18713
18714
18715
18716
18717
18718
18719
18720
18721
18722
18723
18724
18725
18726
18727
18728
18729
18730
18731
18732
18733
18734
18735
18736
18737
18738
18739
18740
18741
18742
18743
18744
18745
18746
18747
18748
18749
18750
18751
18752
18753
18754
18755
18756
18757
18758
18759
18760
18761
18762
18763
18764
18765
18766
18767
18768
18769
18770
18771
18772
18773
18774
18775
18776
18777
18778
18779
18780
18781
18782
18783
18784
18785
18786
18787
18788
18789
18790
18791
18792
18793
18794
18795
18796
18797
18798
18799
18800
18801
18802
18803
18804
18805
18806
18807
18808
18809
18810
18811
18812
18813
18814
18815
18816
18817
18818
18819
18820
18821
18822
18823
18824
18825
18826
18827
18828
18829
18830
18831
18832
18833
18834
18835
18836
18837
18838
18839
18840
18841
18842
18843
18844
18845
18846
18847
18848
18849
18850
18851
18852
18853
18854
18855
18856
18857
18858
18859
18860
18861
18862
18863
18864
18865
18866
18867
18868
18869
18870
18871
18872
18873
18874
18875
18876
18877
18878
18879
18880
18881
18882
18883
18884
18885
18886
18887
18888
18889
18890
18891
18892
18893
18894
18895
18896
18897
18898
18899
18900
18901
18902
18903
18904
18905
18906
18907
18908
18909
18910
18911
18912
18913
18914
18915
18916
18917
18918
18919
18920
18921
18922
18923
18924
18925
18926
18927
18928
18929
18930
18931
18932
18933
18934
18935
18936
18937
18938
18939
18940
18941
18942
18943
18944
18945
18946
18947
18948
18949
18950
18951
18952
18953
18954
18955
18956
18957
18958
18959
18960
18961
18962
18963
18964
18965
18966
18967
18968
18969
18970
18971
18972
18973
18974
18975
18976
18977
18978
18979
18980
18981
18982
18983
18984
18985
18986
18987
18988
18989
18990
18991
18992
18993
18994
18995
18996
18997
18998
18999
19000
19001
19002
19003
19004
19005
19006
19007
19008
19009
19010
19011
19012
19013
19014
19015
19016
19017
19018
19019
19020
19021
19022
19023
19024
19025
19026
19027
19028
19029
19030
19031
19032
19033
19034
19035
19036
19037
19038
19039
19040
19041
19042
19043
19044
19045
19046
19047
19048
19049
19050
19051
19052
19053
19054
19055
19056
19057
19058
19059
19060
19061
19062
19063
19064
19065
19066
19067
19068
19069
19070
19071
19072
19073
19074
19075
19076
19077
19078
19079
19080
19081
19082
19083
19084
19085
19086
19087
19088
19089
19090
19091
19092
19093
19094
19095
19096
19097
19098
19099
19100
19101
19102
19103
19104
19105
19106
19107
19108
19109
19110
19111
19112
19113
19114
19115
19116
19117
19118
19119
19120
19121
19122
19123
19124
19125
19126
19127
19128
19129
19130
19131
19132
19133
19134
19135
19136
19137
19138
19139
19140
19141
19142
19143
19144
19145
19146
19147
19148
19149
19150
19151
19152
19153
19154
19155
19156
19157
19158
19159
19160
19161
19162
19163
19164
19165
19166
19167
19168
19169
19170
19171
19172
19173
19174
19175
19176
19177
19178
19179
19180
19181
19182
19183
19184
19185
19186
19187
19188
19189
19190
19191
19192
19193
19194
19195
19196
19197
19198
19199
19200
19201
19202
19203
19204
19205
19206
19207
19208
19209
19210
19211
19212
19213
19214
19215
19216
19217
19218
19219
19220
19221
19222
19223
19224
19225
19226
19227
19228
19229
19230
19231
19232
19233
19234
19235
19236
19237
19238
19239
19240
19241
19242
19243
19244
19245
19246
19247
19248
19249
19250
19251
19252
19253
19254
19255
19256
19257
19258
19259
19260
19261
19262
19263
19264
19265
19266
19267
19268
19269
19270
19271
19272
19273
19274
19275
19276
19277
19278
19279
19280
19281
19282
19283
19284
19285
19286
19287
19288
19289
19290
19291
19292
19293
19294
19295
19296
19297
19298
19299
19300
19301
19302
19303
19304
19305
19306
19307
19308
19309
19310
19311
19312
19313
19314
19315
19316
19317
19318
19319
19320
19321
19322
19323
19324
19325
19326
19327
19328
19329
19330
19331
19332
19333
19334
19335
19336
19337
19338
19339
19340
19341
19342
19343
19344
19345
19346
19347
19348
19349
19350
19351
19352
19353
19354
19355
19356
19357
19358
19359
19360
19361
19362
19363
19364
19365
19366
19367
19368
19369
19370
19371
19372
19373
19374
19375
19376
19377
19378
19379
19380
19381
19382
19383
19384
19385
19386
19387
19388
19389
19390
19391
19392
19393
19394
19395
19396
19397
19398
19399
19400
19401
19402
19403
19404
19405
19406
19407
19408
19409
19410
19411
19412
19413
19414
19415
19416
19417
19418
19419
19420
19421
19422
19423
19424
19425
19426
19427
19428
19429
19430
19431
19432
19433
19434
19435
19436
19437
19438
19439
19440
19441
19442
19443
19444
19445
19446
19447
19448
19449
19450
19451
19452
19453
19454
19455
19456
19457
19458
19459
19460
19461
19462
19463
19464
19465
19466
19467
19468
19469
19470
19471
19472
19473
19474
19475
19476
19477
19478
19479
19480
19481
19482
19483
19484
19485
19486
19487
19488
19489
19490
19491
19492
19493
19494
19495
19496
19497
19498
19499
19500
19501
19502
19503
19504
19505
19506
19507
19508
19509
19510
19511
19512
19513
19514
19515
19516
19517
19518
19519
19520
19521
19522
19523
19524
19525
19526
19527
19528
19529
19530
19531
19532
19533
19534
19535
19536
19537
19538
19539
19540
19541
19542
19543
19544
19545
19546
19547
19548
19549
19550
19551
19552
19553
19554
19555
19556
19557
19558
19559
19560
19561
19562
19563
19564
19565
19566
19567
19568
19569
19570
19571
19572
19573
19574
19575
19576
19577
19578
19579
19580
19581
19582
19583
19584
19585
19586
19587
19588
19589
19590
19591
19592
19593
19594
19595
19596
19597
19598
19599
19600
19601
19602
19603
19604
19605
19606
19607
19608
19609
19610
19611
19612
19613
19614
19615
19616
19617
19618
19619
19620
19621
19622
19623
19624
19625
19626
19627
19628
19629
19630
19631
19632
19633
19634
19635
19636
19637
19638
19639
19640
19641
19642
19643
19644
19645
19646
19647
19648
19649
19650
19651
19652
19653
19654
19655
19656
19657
19658
19659
19660
19661
19662
19663
19664
19665
19666
19667
19668
19669
19670
19671
19672
19673
19674
19675
19676
19677
19678
19679
19680
19681
19682
19683
19684
19685
19686
19687
19688
19689
19690
19691
19692
19693
19694
19695
19696
19697
19698
19699
19700
19701
19702
19703
19704
19705
19706
19707
19708
19709
19710
19711
19712
19713
19714
19715
19716
19717
19718
19719
19720
19721
19722
19723
19724
19725
19726
19727
19728
19729
19730
19731
19732
19733
19734
19735
19736
19737
19738
19739
19740
19741
19742
19743
19744
19745
19746
19747
19748
19749
19750
19751
19752
19753
19754
19755
19756
19757
19758
19759
19760
19761
19762
19763
19764
19765
19766
19767
19768
19769
19770
19771
19772
19773
19774
19775
19776
19777
19778
19779
19780
19781
19782
19783
19784
19785
19786
19787
19788
19789
19790
19791
19792
19793
19794
19795
19796
19797
19798
19799
19800
19801
19802
19803
19804
19805
19806
19807
19808
19809
19810
19811
19812
19813
19814
19815
19816
19817
19818
19819
19820
19821
19822
19823
19824
19825
19826
19827
19828
19829
19830
19831
19832
19833
19834
19835
19836
19837
19838
19839
19840
19841
19842
19843
19844
19845
19846
19847
19848
19849
19850
19851
19852
19853
19854
19855
19856
19857
19858
19859
19860
19861
19862
19863
19864
19865
19866
19867
19868
19869
19870
19871
19872
19873
19874
19875
19876
19877
19878
19879
19880
19881
19882
19883
19884
19885
19886
19887
19888
19889
19890
19891
19892
19893
19894
19895
19896
19897
19898
19899
19900
19901
19902
19903
19904
19905
19906
19907
19908
19909
19910
19911
19912
19913
19914
19915
19916
19917
19918
19919
19920
19921
19922
19923
19924
19925
19926
19927
19928
19929
19930
19931
19932
19933
19934
19935
19936
19937
19938
19939
19940
19941
19942
19943
19944
19945
19946
19947
19948
19949
19950
19951
19952
19953
19954
19955
19956
19957
19958
19959
19960
19961
19962
19963
19964
19965
19966
19967
19968
19969
19970
19971
19972
19973
19974
19975
19976
19977
19978
19979
19980
19981
19982
19983
19984
19985
19986
19987
19988
19989
19990
19991
19992
19993
19994
19995
19996
19997
19998
19999
20000
20001
20002
20003
20004
20005
20006
20007
20008
20009
20010
20011
20012
20013
20014
20015
20016
20017
20018
20019
20020
20021
20022
20023
20024
20025
20026
20027
20028
20029
20030
20031
20032
20033
20034
20035
20036
20037
20038
20039
20040
20041
20042
20043
20044
20045
20046
20047
20048
20049
20050
20051
20052
20053
20054
20055
20056
20057
20058
20059
20060
20061
20062
20063
20064
20065
20066
20067
20068
20069
20070
20071
20072
20073
20074
20075
20076
20077
20078
20079
20080
20081
20082
20083
20084
20085
20086
20087
20088
20089
20090
20091
20092
20093
20094
20095
20096
20097
20098
20099
20100
20101
20102
20103
20104
20105
20106
20107
20108
20109
20110
20111
20112
20113
20114
20115
20116
20117
20118
20119
20120
20121
20122
20123
20124
20125
20126
20127
20128
20129
20130
20131
20132
20133
20134
20135
20136
20137
20138
20139
20140
20141
20142
20143
20144
20145
20146
20147
20148
20149
20150
20151
20152
20153
20154
20155
20156
20157
20158
20159
20160
20161
20162
20163
20164
20165
20166
20167
20168
20169
20170
20171
20172
20173
20174
20175
20176
20177
20178
20179
20180
20181
20182
20183
20184
20185
20186
20187
20188
20189
20190
20191
20192
20193
20194
20195
20196
20197
20198
20199
20200
20201
20202
20203
20204
20205
20206
20207
20208
20209
20210
20211
20212
20213
20214
20215
20216
20217
20218
20219
20220
20221
20222
20223
20224
20225
20226
20227
20228
20229
20230
20231
20232
20233
20234
20235
20236
20237
20238
20239
20240
20241
20242
20243
20244
20245
20246
20247
20248
20249
20250
20251
20252
20253
20254
20255
20256
20257
20258
20259
20260
20261
20262
20263
20264
20265
20266
20267
20268
20269
20270
20271
20272
20273
20274
20275
20276
20277
20278
20279
20280
20281
20282
20283
20284
20285
20286
20287
20288
20289
20290
20291
20292
20293
20294
20295
20296
20297
20298
20299
20300
20301
20302
20303
20304
20305
20306
20307
20308
20309
20310
20311
20312
20313
20314
20315
20316
20317
20318
20319
20320
20321
20322
20323
20324
20325
20326
20327
20328
20329
20330
20331
20332
20333
20334
20335
20336
20337
20338
20339
20340
20341
20342
20343
20344
20345
20346
20347
20348
20349
20350
20351
20352
20353
20354
20355
20356
20357
20358
20359
20360
20361
20362
20363
20364
20365
20366
20367
20368
20369
20370
20371
20372
20373
20374
20375
20376
20377
20378
20379
20380
20381
20382
20383
20384
20385
20386
20387
20388
20389
20390
20391
20392
20393
20394
20395
20396
20397
20398
20399
20400
20401
20402
20403
20404
20405
20406
20407
20408
20409
20410
20411
20412
20413
20414
20415
20416
20417
20418
20419
20420
20421
20422
20423
20424
20425
20426
20427
20428
20429
20430
20431
20432
20433
20434
20435
20436
20437
20438
20439
20440
20441
20442
20443
20444
20445
20446
20447
20448
20449
20450
20451
20452
20453
20454
20455
20456
20457
20458
20459
20460
20461
20462
20463
20464
20465
20466
20467
20468
20469
20470
20471
20472
20473
20474
20475
20476
20477
20478
20479
20480
20481
20482
20483
20484
20485
20486
20487
20488
20489
20490
20491
20492
20493
20494
20495
20496
20497
20498
20499
20500
20501
20502
20503
20504
20505
20506
20507
20508
20509
20510
20511
20512
20513
20514
20515
20516
20517
20518
20519
20520
20521
20522
20523
20524
20525
20526
20527
20528
20529
20530
20531
20532
20533
20534
20535
20536
20537
20538
20539
20540
20541
20542
20543
20544
20545
20546
20547
20548
20549
20550
20551
20552
20553
20554
20555
20556
20557
20558
20559
20560
20561
20562
20563
20564
20565
20566
20567
20568
20569
20570
20571
20572
20573
20574
20575
20576
20577
20578
20579
20580
20581
20582
20583
20584
20585
20586
20587
20588
20589
20590
20591
20592
20593
20594
20595
20596
20597
20598
20599
20600
20601
20602
20603
20604
20605
20606
20607
20608
20609
20610
20611
20612
20613
20614
20615
20616
20617
20618
20619
20620
20621
20622
20623
20624
20625
20626
20627
20628
20629
20630
20631
20632
20633
20634
20635
20636
20637
20638
20639
20640
20641
20642
20643
20644
20645
20646
20647
20648
20649
20650
20651
20652
20653
20654
20655
20656
20657
20658
20659
20660
20661
20662
20663
20664
20665
20666
20667
20668
20669
20670
20671
20672
20673
20674
20675
20676
20677
20678
20679
20680
20681
20682
20683
20684
20685
20686
20687
20688
20689
20690
20691
20692
20693
20694
20695
20696
20697
20698
20699
20700
20701
20702
20703
20704
20705
20706
20707
20708
20709
20710
20711
20712
20713
20714
20715
20716
20717
20718
20719
20720
20721
20722
20723
20724
20725
20726
20727
20728
20729
20730
20731
20732
20733
20734
20735
20736
20737
20738
20739
20740
20741
20742
20743
20744
20745
20746
20747
20748
20749
20750
20751
20752
20753
20754
20755
20756
20757
20758
20759
20760
20761
20762
20763
20764
20765
20766
20767
20768
20769
20770
20771
20772
20773
20774
20775
20776
20777
20778
20779
20780
20781
20782
20783
20784
20785
20786
20787
20788
20789
20790
20791
20792
20793
20794
20795
20796
20797
20798
20799
20800
20801
20802
20803
20804
20805
20806
20807
20808
20809
20810
20811
20812
20813
20814
20815
20816
20817
20818
20819
20820
20821
20822
20823
20824
20825
20826
20827
20828
20829
20830
20831
20832
20833
20834
20835
20836
20837
20838
20839
20840
20841
20842
20843
20844
20845
20846
20847
20848
20849
20850
20851
20852
20853
20854
20855
20856
20857
20858
20859
20860
20861
20862
20863
20864
20865
20866
20867
20868
20869
20870
20871
20872
20873
20874
20875
20876
20877
20878
20879
20880
20881
20882
20883
20884
20885
20886
20887
20888
20889
20890
20891
20892
20893
20894
20895
20896
20897
20898
20899
20900
20901
20902
20903
20904
20905
20906
20907
20908
20909
20910
20911
20912
20913
20914
20915
20916
20917
20918
20919
20920
20921
20922
20923
20924
20925
20926
20927
20928
20929
20930
20931
20932
20933
20934
20935
20936
20937
20938
20939
20940
20941
20942
20943
20944
20945
20946
20947
20948
20949
20950
20951
20952
20953
20954
20955
20956
20957
20958
20959
20960
20961
20962
20963
20964
20965
20966
20967
20968
20969
20970
20971
20972
20973
20974
20975
20976
20977
20978
20979
20980
20981
20982
20983
20984
20985
20986
20987
20988
20989
20990
20991
20992
20993
20994
20995
20996
20997
20998
20999
21000
21001
21002
21003
21004
21005
21006
21007
21008
21009
21010
21011
21012
21013
21014
21015
21016
21017
21018
21019
21020
21021
21022
21023
21024
21025
21026
21027
21028
21029
21030
21031
21032
21033
21034
21035
21036
21037
21038
21039
21040
21041
21042
21043
21044
21045
21046
21047
21048
21049
21050
21051
21052
21053
21054
21055
21056
21057
21058
21059
21060
21061
21062
21063
21064
21065
21066
21067
21068
21069
21070
21071
21072
21073
21074
21075
21076
21077
21078
21079
21080
21081
21082
21083
21084
21085
21086
21087
21088
21089
21090
21091
21092
21093
21094
21095
21096
21097
21098
21099
21100
21101
21102
21103
21104
21105
21106
21107
21108
21109
21110
21111
21112
21113
21114
21115
21116
21117
21118
21119
21120
21121
21122
21123
21124
21125
21126
21127
21128
21129
21130
21131
21132
21133
21134
21135
21136
21137
21138
21139
21140
21141
21142
21143
21144
21145
21146
21147
21148
21149
21150
21151
21152
21153
21154
21155
21156
21157
21158
21159
21160
21161
21162
21163
21164
21165
21166
21167
21168
21169
21170
21171
21172
21173
21174
21175
21176
21177
21178
21179
21180
21181
21182
21183
21184
21185
21186
21187
21188
21189
21190
21191
21192
21193
21194
21195
21196
21197
21198
21199
21200
21201
21202
21203
21204
21205
21206
21207
21208
21209
21210
21211
21212
21213
21214
21215
21216
21217
21218
21219
21220
21221
21222
21223
21224
21225
21226
21227
21228
21229
21230
21231
21232
21233
21234
21235
21236
21237
21238
21239
21240
21241
21242
21243
21244
21245
21246
21247
21248
21249
21250
21251
21252
21253
21254
21255
21256
21257
21258
21259
21260
21261
21262
21263
21264
21265
21266
21267
21268
21269
21270
21271
21272
21273
21274
21275
21276
21277
21278
21279
21280
21281
21282
21283
21284
21285
21286
21287
21288
21289
21290
21291
21292
21293
21294
21295
21296
21297
21298
21299
21300
21301
21302
21303
21304
21305
21306
21307
21308
21309
21310
21311
21312
21313
21314
21315
21316
21317
21318
21319
21320
21321
21322
21323
21324
21325
21326
21327
21328
21329
21330
21331
21332
21333
21334
21335
21336
21337
21338
21339
21340
21341
21342
21343
21344
21345
21346
21347
21348
21349
21350
21351
21352
21353
21354
21355
21356
21357
21358
21359
21360
21361
21362
21363
21364
21365
21366
21367
21368
21369
21370
21371
21372
21373
21374
21375
21376
21377
21378
21379
21380
21381
21382
21383
21384
21385
21386
21387
21388
21389
21390
21391
21392
21393
21394
21395
21396
21397
21398
21399
21400
21401
21402
21403
21404
21405
21406
21407
21408
21409
21410
21411
21412
21413
21414
21415
21416
21417
21418
21419
21420
21421
21422
21423
21424
21425
21426
21427
21428
21429
21430
21431
21432
21433
21434
21435
21436
21437
21438
21439
21440
21441
21442
21443
21444
21445
21446
21447
21448
21449
21450
21451
21452
21453
21454
21455
21456
21457
21458
21459
21460
21461
21462
21463
21464
21465
21466
21467
21468
21469
21470
21471
21472
21473
21474
21475
21476
21477
21478
21479
21480
21481
21482
21483
21484
21485
21486
21487
21488
21489
21490
21491
21492
21493
21494
21495
21496
21497
21498
21499
21500
21501
21502
21503
21504
21505
21506
21507
21508
21509
21510
21511
21512
21513
21514
21515
21516
21517
21518
21519
21520
21521
21522
21523
21524
21525
21526
21527
21528
21529
21530
21531
21532
21533
21534
21535
21536
21537
21538
21539
21540
21541
21542
21543
21544
21545
21546
21547
21548
21549
21550
21551
21552
21553
21554
21555
21556
21557
21558
21559
21560
21561
21562
21563
21564
21565
21566
21567
21568
21569
21570
21571
21572
21573
21574
21575
21576
21577
21578
21579
21580
21581
21582
21583
21584
21585
21586
21587
21588
21589
21590
21591
21592
21593
21594
21595
21596
21597
21598
21599
21600
21601
21602
21603
21604
21605
21606
21607
21608
21609
21610
21611
21612
21613
21614
21615
21616
21617
21618
21619
21620
21621
21622
21623
21624
21625
21626
21627
21628
21629
21630
21631
21632
21633
21634
21635
21636
21637
21638
21639
21640
21641
21642
21643
21644
21645
21646
21647
21648
21649
21650
21651
21652
21653
21654
21655
21656
21657
21658
21659
21660
21661
21662
21663
21664
21665
21666
21667
21668
21669
21670
21671
21672
21673
21674
21675
21676
21677
21678
21679
21680
21681
21682
21683
21684
21685
21686
21687
21688
21689
21690
21691
21692
21693
21694
21695
21696
21697
21698
21699
21700
21701
21702
21703
21704
21705
21706
21707
21708
21709
21710
21711
21712
21713
21714
21715
21716
21717
21718
21719
21720
21721
21722
21723
21724
21725
21726
21727
21728
21729
21730
21731
21732
21733
21734
21735
21736
21737
21738
21739
21740
21741
21742
21743
21744
21745
21746
21747
21748
21749
21750
21751
21752
21753
21754
21755
21756
21757
21758
21759
21760
21761
21762
21763
21764
21765
21766
21767
21768
21769
21770
21771
21772
21773
21774
21775
21776
21777
21778
21779
21780
21781
21782
21783
21784
21785
21786
21787
21788
21789
21790
21791
21792
21793
21794
21795
21796
21797
21798
21799
21800
21801
21802
21803
21804
21805
21806
21807
21808
21809
21810
21811
21812
21813
21814
21815
21816
21817
21818
21819
21820
21821
21822
21823
21824
21825
21826
21827
21828
21829
21830
21831
21832
21833
21834
21835
21836
21837
21838
21839
21840
21841
21842
21843
21844
21845
21846
21847
21848
21849
21850
21851
21852
21853
21854
21855
21856
21857
21858
21859
21860
21861
21862
21863
21864
21865
21866
21867
21868
21869
21870
21871
21872
21873
21874
21875
21876
21877
21878
21879
21880
21881
21882
21883
21884
21885
21886
21887
21888
21889
21890
21891
21892
21893
21894
21895
21896
21897
21898
21899
21900
21901
21902
21903
21904
21905
21906
21907
21908
21909
21910
21911
21912
21913
21914
21915
21916
21917
21918
21919
21920
21921
21922
21923
21924
21925
21926
21927
21928
21929
21930
21931
21932
21933
21934
21935
21936
21937
21938
21939
21940
21941
21942
21943
21944
21945
21946
21947
21948
21949
21950
21951
21952
21953
21954
21955
21956
21957
21958
21959
21960
21961
21962
21963
21964
21965
21966
21967
21968
21969
21970
21971
21972
21973
21974
21975
21976
21977
21978
21979
21980
21981
21982
21983
21984
21985
21986
21987
21988
21989
21990
21991
21992
21993
21994
21995
21996
21997
21998
21999
22000
22001
22002
22003
22004
22005
22006
22007
22008
22009
22010
22011
22012
22013
22014
22015
22016
22017
22018
22019
22020
22021
22022
22023
22024
22025
22026
22027
22028
22029
22030
22031
22032
22033
22034
22035
22036
22037
22038
22039
22040
22041
22042
22043
22044
22045
22046
22047
22048
22049
22050
22051
22052
22053
22054
22055
22056
22057
22058
22059
22060
22061
22062
22063
22064
22065
22066
22067
22068
22069
22070
22071
22072
22073
22074
22075
22076
22077
22078
22079
22080
22081
22082
22083
22084
22085
22086
22087
22088
22089
22090
22091
22092
22093
22094
22095
22096
22097
22098
22099
22100
22101
22102
22103
22104
22105
22106
22107
22108
22109
22110
22111
22112
22113
22114
22115
22116
22117
22118
22119
22120
22121
22122
22123
22124
22125
22126
22127
22128
22129
22130
22131
22132
22133
22134
22135
22136
22137
22138
22139
22140
22141
22142
22143
22144
22145
22146
22147
22148
22149
22150
22151
22152
22153
22154
22155
22156
22157
22158
22159
22160
22161
22162
22163
22164
22165
22166
22167
22168
22169
22170
22171
22172
22173
22174
22175
22176
22177
22178
22179
22180
22181
22182
22183
22184
22185
22186
22187
22188
22189
22190
22191
22192
22193
22194
22195
22196
22197
22198
22199
22200
22201
22202
22203
22204
22205
22206
22207
22208
22209
22210
22211
22212
22213
22214
22215
22216
22217
22218
22219
22220
22221
22222
22223
22224
22225
22226
22227
22228
22229
22230
22231
22232
22233
22234
22235
22236
22237
22238
22239
22240
22241
22242
22243
22244
22245
22246
22247
22248
22249
22250
22251
22252
22253
22254
22255
22256
22257
22258
22259
22260
22261
22262
22263
22264
22265
22266
22267
22268
22269
22270
22271
22272
22273
22274
22275
22276
22277
22278
22279
22280
22281
22282
22283
22284
22285
22286
22287
22288
22289
22290
22291
22292
22293
22294
22295
22296
22297
22298
22299
22300
22301
22302
22303
22304
22305
22306
22307
22308
22309
22310
22311
22312
22313
22314
22315
22316
22317
22318
22319
22320
22321
22322
22323
22324
22325
22326
22327
22328
22329
22330
22331
22332
22333
22334
22335
22336
22337
22338
22339
22340
22341
22342
22343
22344
22345
22346
22347
22348
22349
22350
22351
22352
22353
22354
22355
22356
22357
22358
22359
22360
22361
22362
22363
22364
22365
22366
22367
22368
22369
22370
22371
22372
22373
22374
22375
22376
22377
22378
22379
22380
22381
22382
22383
22384
22385
22386
22387
22388
22389
22390
22391
22392
22393
22394
22395
22396
22397
22398
22399
22400
22401
22402
22403
22404
22405
22406
22407
22408
22409
22410
22411
22412
22413
22414
22415
22416
22417
22418
22419
22420
22421
22422
22423
22424
22425
22426
22427
22428
22429
22430
22431
22432
22433
22434
22435
22436
22437
22438
22439
22440
22441
22442
22443
22444
22445
22446
22447
22448
22449
22450
22451
22452
22453
22454
22455
22456
22457
22458
22459
22460
22461
22462
22463
22464
22465
22466
22467
22468
22469
22470
22471
22472
22473
22474
22475
22476
22477
22478
22479
22480
22481
22482
22483
22484
22485
22486
22487
22488
22489
22490
22491
22492
22493
22494
22495
22496
22497
22498
22499
22500
22501
22502
22503
22504
22505
22506
22507
22508
22509
22510
22511
22512
22513
22514
22515
22516
22517
22518
22519
22520
22521
22522
22523
22524
22525
22526
22527
22528
22529
22530
22531
22532
22533
22534
22535
22536
22537
22538
22539
22540
22541
22542
22543
22544
22545
22546
22547
22548
22549
22550
22551
22552
22553
22554
22555
22556
22557
22558
22559
22560
22561
22562
22563
22564
22565
22566
22567
22568
22569
22570
22571
22572
22573
22574
22575
22576
22577
22578
22579
22580
22581
22582
22583
22584
22585
22586
22587
22588
22589
22590
22591
22592
22593
22594
22595
22596
22597
22598
22599
22600
22601
22602
22603
22604
22605
22606
22607
22608
22609
22610
22611
22612
22613
22614
22615
22616
22617
22618
22619
22620
22621
22622
22623
22624
22625
22626
22627
22628
22629
22630
22631
22632
22633
22634
22635
22636
22637
22638
22639
22640
22641
22642
22643
22644
22645
22646
22647
22648
22649
22650
22651
22652
22653
22654
22655
22656
22657
22658
22659
22660
22661
22662
22663
22664
22665
22666
22667
22668
22669
22670
22671
22672
22673
22674
22675
22676
22677
22678
22679
22680
22681
22682
22683
22684
22685
22686
22687
22688
22689
22690
22691
22692
22693
22694
22695
22696
22697
22698
22699
22700
22701
22702
22703
22704
22705
22706
22707
22708
22709
22710
22711
22712
22713
22714
22715
22716
22717
22718
22719
22720
22721
22722
22723
22724
22725
22726
22727
22728
22729
22730
22731
22732
22733
22734
22735
22736
22737
22738
22739
22740
22741
22742
22743
22744
22745
22746
22747
22748
22749
22750
22751
22752
22753
22754
22755
22756
22757
22758
22759
22760
22761
22762
22763
22764
22765
22766
22767
22768
22769
22770
22771
22772
22773
22774
22775
22776
22777
22778
22779
22780
22781
22782
22783
22784
22785
22786
22787
22788
22789
22790
22791
22792
22793
22794
22795
22796
22797
22798
22799
22800
22801
22802
22803
22804
22805
22806
22807
22808
22809
22810
22811
22812
22813
22814
22815
22816
22817
22818
22819
22820
22821
22822
22823
22824
22825
22826
22827
22828
22829
22830
22831
22832
22833
22834
22835
22836
22837
22838
22839
22840
22841
22842
22843
22844
22845
22846
22847
22848
22849
22850
22851
22852
22853
22854
22855
22856
22857
22858
22859
22860
22861
22862
22863
22864
22865
22866
22867
22868
22869
22870
22871
22872
22873
22874
22875
22876
22877
22878
22879
22880
22881
22882
22883
22884
22885
22886
22887
22888
22889
22890
22891
22892
22893
22894
22895
22896
22897
22898
22899
22900
22901
22902
22903
22904
22905
22906
22907
22908
22909
22910
22911
22912
22913
22914
22915
22916
22917
22918
22919
22920
22921
22922
22923
22924
22925
22926
22927
22928
22929
22930
22931
22932
22933
22934
22935
22936
22937
22938
22939
22940
22941
22942
22943
22944
22945
22946
22947
22948
22949
22950
22951
22952
22953
22954
22955
22956
22957
22958
22959
22960
22961
22962
22963
22964
22965
22966
22967
22968
22969
22970
22971
22972
22973
22974
22975
22976
22977
22978
22979
22980
22981
22982
22983
22984
22985
22986
22987
22988
22989
22990
22991
22992
22993
22994
22995
22996
22997
22998
22999
23000
23001
23002
23003
23004
23005
23006
23007
23008
23009
23010
23011
23012
23013
23014
23015
23016
23017
23018
23019
23020
23021
23022
23023
23024
23025
23026
23027
23028
23029
23030
23031
23032
23033
23034
23035
23036
23037
23038
23039
23040
23041
23042
23043
23044
23045
23046
23047
23048
23049
23050
23051
23052
23053
23054
23055
23056
23057
23058
23059
23060
23061
23062
23063
23064
23065
23066
23067
23068
23069
23070
23071
23072
23073
23074
23075
23076
23077
23078
23079
23080
23081
23082
23083
23084
23085
23086
23087
23088
23089
23090
23091
23092
23093
23094
23095
23096
23097
23098
23099
23100
23101
23102
23103
23104
23105
23106
23107
23108
23109
23110
23111
23112
23113
23114
23115
23116
23117
23118
23119
23120
23121
23122
23123
23124
23125
23126
23127
23128
23129
23130
23131
23132
23133
23134
23135
23136
23137
23138
23139
23140
23141
23142
23143
23144
23145
23146
23147
23148
23149
23150
23151
23152
23153
23154
23155
23156
23157
23158
23159
23160
23161
23162
23163
23164
23165
23166
23167
23168
23169
23170
23171
23172
23173
23174
23175
23176
23177
23178
23179
23180
23181
23182
23183
23184
23185
23186
23187
23188
23189
23190
23191
23192
23193
23194
23195
23196
23197
23198
23199
23200
23201
23202
23203
23204
23205
23206
23207
23208
23209
23210
23211
23212
23213
23214
23215
23216
23217
23218
23219
23220
23221
23222
23223
23224
23225
23226
23227
23228
23229
23230
23231
23232
23233
23234
23235
23236
23237
23238
23239
23240
23241
23242
23243
23244
23245
23246
23247
23248
23249
23250
23251
23252
23253
23254
23255
23256
23257
23258
23259
23260
23261
23262
23263
23264
23265
23266
23267
23268
23269
23270
23271
23272
23273
23274
23275
23276
23277
23278
23279
23280
23281
23282
23283
23284
23285
23286
23287
23288
23289
23290
23291
23292
23293
23294
23295
23296
23297
23298
23299
23300
23301
23302
23303
23304
23305
23306
23307
23308
23309
23310
23311
23312
23313
23314
23315
23316
23317
23318
23319
23320
23321
23322
23323
23324
23325
23326
23327
23328
23329
23330
23331
23332
23333
23334
23335
23336
23337
23338
23339
23340
23341
23342
23343
23344
23345
23346
23347
23348
23349
23350
23351
23352
23353
23354
23355
23356
23357
23358
23359
23360
23361
23362
23363
23364
23365
23366
23367
23368
23369
23370
23371
23372
23373
23374
23375
23376
23377
23378
23379
23380
23381
23382
23383
23384
23385
23386
23387
23388
23389
23390
23391
23392
23393
23394
23395
23396
23397
23398
23399
23400
23401
23402
23403
23404
23405
23406
23407
23408
23409
23410
23411
23412
23413
23414
23415
23416
23417
23418
23419
23420
23421
23422
23423
23424
23425
23426
23427
23428
23429
23430
23431
23432
23433
23434
23435
23436
23437
23438
23439
23440
23441
23442
23443
23444
23445
23446
23447
23448
23449
23450
23451
23452
23453
23454
23455
23456
23457
23458
23459
23460
23461
23462
23463
23464
23465
23466
23467
23468
23469
23470
23471
23472
23473
23474
23475
23476
23477
23478
23479
23480
23481
23482
23483
23484
23485
23486
23487
23488
23489
23490
23491
23492
23493
23494
23495
23496
23497
23498
23499
23500
23501
23502
23503
23504
23505
23506
23507
23508
23509
23510
23511
23512
23513
23514
23515
23516
23517
23518
23519
23520
23521
23522
23523
23524
23525
23526
23527
23528
23529
23530
23531
23532
23533
23534
23535
23536
23537
23538
23539
23540
23541
23542
23543
23544
23545
23546
23547
23548
23549
23550
23551
23552
23553
23554
23555
23556
23557
23558
23559
23560
23561
23562
23563
23564
23565
23566
23567
23568
23569
23570
23571
23572
23573
23574
23575
23576
23577
23578
23579
23580
23581
23582
23583
23584
23585
23586
23587
23588
23589
23590
23591
23592
23593
23594
23595
23596
23597
23598
23599
23600
23601
23602
23603
23604
23605
23606
23607
23608
23609
23610
23611
23612
23613
23614
23615
23616
23617
23618
23619
23620
23621
23622
23623
23624
23625
23626
23627
23628
23629
23630
23631
23632
23633
23634
23635
23636
23637
23638
23639
23640
23641
23642
23643
23644
23645
23646
23647
23648
23649
23650
23651
23652
23653
23654
23655
23656
23657
23658
23659
23660
23661
23662
23663
23664
23665
23666
23667
23668
23669
23670
23671
23672
23673
23674
23675
23676
23677
23678
23679
23680
23681
23682
23683
23684
23685
23686
23687
23688
23689
23690
23691
23692
23693
23694
23695
23696
23697
23698
23699
23700
23701
23702
23703
23704
23705
23706
23707
23708
23709
23710
23711
23712
23713
23714
23715
23716
23717
23718
23719
23720
23721
23722
23723
23724
23725
23726
23727
23728
23729
23730
23731
23732
23733
23734
23735
23736
23737
23738
23739
23740
23741
23742
23743
23744
23745
23746
23747
23748
23749
23750
23751
23752
23753
23754
23755
23756
23757
23758
23759
23760
23761
23762
23763
23764
23765
23766
23767
23768
23769
23770
23771
23772
23773
23774
23775
23776
23777
23778
23779
23780
23781
23782
23783
23784
23785
23786
23787
23788
23789
23790
23791
23792
23793
23794
23795
23796
23797
23798
23799
23800
23801
23802
23803
23804
23805
23806
23807
23808
23809
23810
23811
23812
23813
23814
23815
23816
23817
23818
23819
23820
23821
23822
23823
23824
23825
23826
23827
23828
23829
23830
23831
23832
23833
23834
23835
23836
23837
23838
23839
23840
23841
23842
23843
23844
23845
23846
23847
23848
23849
23850
23851
23852
23853
23854
23855
23856
23857
23858
23859
23860
23861
23862
23863
23864
23865
23866
23867
23868
23869
23870
23871
23872
23873
23874
23875
23876
23877
23878
23879
23880
23881
23882
23883
23884
23885
23886
23887
23888
23889
23890
23891
23892
23893
23894
23895
23896
23897
23898
23899
23900
23901
23902
23903
23904
23905
23906
23907
23908
23909
23910
23911
23912
23913
23914
23915
23916
23917
23918
23919
23920
23921
23922
23923
23924
23925
23926
23927
23928
23929
23930
23931
23932
23933
23934
23935
23936
23937
23938
23939
23940
23941
23942
23943
23944
23945
23946
23947
23948
23949
23950
23951
23952
23953
23954
23955
23956
23957
23958
23959
23960
23961
23962
23963
23964
23965
23966
23967
23968
23969
23970
23971
23972
23973
23974
23975
23976
23977
23978
23979
23980
23981
23982
23983
23984
23985
23986
23987
23988
23989
23990
23991
23992
23993
23994
23995
23996
23997
23998
23999
24000
24001
24002
24003
24004
24005
24006
24007
24008
24009
24010
24011
24012
24013
24014
24015
24016
24017
24018
24019
24020
24021
24022
24023
24024
24025
24026
24027
24028
24029
24030
24031
24032
24033
24034
24035
24036
24037
24038
24039
24040
24041
24042
24043
24044
24045
24046
24047
24048
24049
24050
24051
24052
24053
24054
24055
24056
24057
24058
24059
24060
24061
24062
24063
24064
24065
24066
24067
24068
24069
24070
24071
24072
24073
24074
24075
24076
24077
24078
24079
24080
24081
24082
24083
24084
24085
24086
24087
24088
24089
24090
24091
24092
24093
24094
24095
24096
24097
24098
24099
24100
24101
24102
24103
24104
24105
24106
24107
24108
24109
24110
24111
24112
24113
24114
24115
24116
24117
24118
24119
24120
24121
24122
24123
24124
24125
24126
24127
24128
24129
24130
24131
24132
24133
24134
24135
24136
24137
24138
24139
24140
24141
24142
24143
24144
24145
24146
24147
24148
24149
24150
24151
24152
24153
24154
24155
24156
24157
24158
24159
24160
24161
24162
24163
24164
24165
24166
24167
24168
24169
24170
24171
24172
24173
24174
24175
24176
24177
24178
24179
24180
24181
24182
24183
24184
24185
24186
24187
24188
24189
24190
24191
24192
24193
24194
24195
24196
24197
24198
24199
24200
24201
24202
24203
24204
24205
24206
24207
24208
24209
24210
24211
24212
24213
24214
24215
24216
24217
24218
24219
24220
24221
24222
24223
24224
24225
24226
24227
24228
24229
24230
24231
24232
24233
24234
24235
24236
24237
24238
24239
24240
24241
24242
24243
24244
24245
24246
24247
24248
24249
24250
24251
24252
24253
24254
24255
24256
24257
24258
24259
24260
24261
24262
24263
24264
24265
24266
24267
24268
24269
24270
24271
24272
24273
24274
24275
24276
24277
24278
24279
24280
24281
24282
24283
24284
24285
24286
24287
24288
24289
24290
24291
24292
24293
24294
24295
24296
24297
24298
24299
24300
24301
24302
24303
24304
24305
24306
24307
24308
24309
24310
24311
24312
24313
24314
24315
24316
24317
24318
24319
24320
24321
24322
24323
24324
24325
24326
24327
24328
24329
24330
24331
24332
24333
24334
24335
24336
24337
24338
24339
24340
24341
24342
24343
24344
24345
24346
24347
24348
24349
24350
24351
24352
24353
24354
24355
24356
24357
24358
24359
24360
24361
24362
24363
24364
24365
24366
24367
24368
24369
24370
24371
24372
24373
24374
24375
24376
24377
24378
24379
24380
24381
24382
24383
24384
24385
24386
24387
24388
24389
24390
24391
24392
24393
24394
24395
24396
24397
24398
24399
24400
24401
24402
24403
24404
24405
24406
24407
24408
24409
24410
24411
24412
24413
24414
24415
24416
24417
24418
24419
24420
24421
24422
24423
24424
24425
24426
24427
24428
24429
24430
24431
24432
24433
24434
24435
24436
24437
24438
24439
24440
24441
24442
24443
24444
24445
24446
24447
24448
24449
24450
24451
24452
24453
24454
24455
24456
24457
24458
24459
24460
24461
24462
24463
24464
24465
24466
24467
24468
24469
24470
24471
24472
24473
24474
24475
24476
24477
24478
24479
24480
24481
24482
24483
24484
24485
24486
24487
24488
24489
24490
24491
24492
24493
24494
24495
24496
24497
24498
24499
24500
24501
24502
24503
24504
24505
24506
24507
24508
24509
24510
24511
24512
24513
24514
24515
24516
24517
24518
24519
24520
24521
24522
24523
24524
24525
24526
24527
24528
24529
24530
24531
24532
24533
24534
24535
24536
24537
24538
24539
24540
24541
24542
24543
24544
24545
24546
24547
24548
24549
24550
24551
24552
24553
24554
24555
24556
24557
24558
24559
24560
24561
24562
24563
24564
24565
24566
24567
24568
24569
24570
24571
24572
24573
24574
24575
24576
24577
24578
24579
24580
24581
24582
24583
24584
24585
24586
24587
24588
24589
24590
24591
24592
24593
24594
24595
24596
24597
24598
24599
24600
24601
24602
24603
24604
24605
24606
24607
24608
24609
24610
24611
24612
24613
24614
24615
24616
24617
24618
24619
24620
24621
24622
24623
24624
24625
24626
24627
24628
24629
24630
24631
24632
24633
24634
24635
24636
24637
24638
24639
24640
24641
24642
24643
24644
24645
24646
24647
24648
24649
24650
24651
24652
24653
24654
24655
24656
24657
24658
24659
24660
24661
24662
24663
24664
24665
24666
24667
24668
24669
24670
24671
24672
24673
24674
24675
24676
24677
24678
24679
24680
24681
24682
24683
24684
24685
24686
24687
24688
24689
24690
24691
24692
24693
24694
24695
24696
24697
24698
24699
24700
24701
24702
24703
24704
24705
24706
24707
24708
24709
24710
24711
24712
24713
24714
24715
24716
24717
24718
24719
24720
24721
24722
24723
24724
24725
24726
24727
24728
24729
24730
24731
24732
24733
24734
24735
24736
24737
24738
24739
24740
24741
24742
24743
24744
24745
24746
24747
24748
24749
24750
24751
24752
24753
24754
24755
24756
24757
24758
24759
24760
24761
24762
24763
24764
24765
24766
24767
24768
24769
24770
24771
24772
24773
24774
24775
24776
24777
24778
24779
24780
24781
24782
24783
24784
24785
24786
24787
24788
24789
24790
24791
24792
24793
24794
24795
24796
24797
24798
24799
24800
24801
24802
24803
24804
24805
24806
24807
24808
24809
24810
24811
24812
24813
24814
24815
24816
24817
24818
24819
24820
24821
24822
24823
24824
24825
24826
24827
24828
24829
24830
24831
24832
24833
24834
24835
24836
24837
24838
24839
24840
24841
24842
24843
24844
24845
24846
24847
24848
24849
24850
24851
24852
24853
24854
24855
24856
24857
24858
24859
24860
24861
24862
24863
24864
24865
24866
24867
24868
24869
24870
24871
24872
24873
24874
24875
24876
24877
24878
24879
24880
24881
24882
24883
24884
24885
24886
24887
24888
24889
24890
24891
24892
24893
24894
24895
24896
24897
24898
24899
24900
24901
24902
24903
24904
24905
24906
24907
24908
24909
24910
24911
24912
24913
24914
24915
24916
24917
24918
24919
24920
24921
24922
24923
24924
24925
24926
24927
24928
24929
24930
24931
24932
24933
24934
24935
24936
24937
24938
24939
24940
24941
24942
24943
24944
24945
24946
24947
24948
24949
24950
24951
24952
24953
24954
24955
24956
24957
24958
24959
24960
24961
24962
24963
24964
24965
24966
24967
24968
24969
24970
24971
24972
24973
24974
24975
24976
24977
24978
24979
24980
24981
24982
24983
24984
24985
24986
24987
24988
24989
24990
24991
24992
24993
24994
24995
24996
24997
24998
24999
25000
25001
25002
25003
25004
25005
25006
25007
25008
25009
25010
25011
25012
25013
25014
25015
25016
25017
25018
25019
25020
25021
25022
25023
25024
25025
25026
25027
25028
25029
25030
25031
25032
25033
25034
25035
25036
25037
25038
25039
25040
25041
25042
25043
25044
25045
25046
25047
25048
25049
25050
25051
25052
25053
25054
25055
25056
25057
25058
25059
25060
25061
25062
25063
25064
25065
25066
25067
25068
25069
25070
25071
25072
25073
25074
25075
25076
25077
25078
25079
25080
25081
25082
25083
25084
25085
25086
25087
25088
25089
25090
25091
25092
25093
25094
25095
25096
25097
25098
25099
25100
25101
25102
25103
25104
25105
25106
25107
25108
25109
25110
25111
25112
25113
25114
25115
25116
25117
25118
25119
25120
25121
25122
25123
25124
25125
25126
25127
25128
25129
25130
25131
25132
25133
25134
25135
25136
25137
25138
25139
25140
25141
25142
25143
25144
25145
25146
25147
25148
25149
25150
25151
25152
25153
25154
25155
25156
25157
25158
25159
25160
25161
25162
25163
25164
25165
25166
25167
25168
25169
25170
25171
25172
25173
25174
25175
25176
25177
25178
25179
25180
25181
25182
25183
25184
25185
25186
25187
25188
25189
25190
25191
25192
25193
25194
25195
25196
25197
25198
25199
25200
25201
25202
25203
25204
25205
25206
25207
25208
25209
25210
25211
25212
25213
25214
25215
25216
25217
25218
25219
25220
25221
25222
25223
25224
25225
25226
25227
25228
25229
25230
25231
25232
25233
25234
25235
25236
25237
25238
25239
25240
25241
25242
25243
25244
25245
25246
25247
25248
25249
25250
25251
25252
25253
25254
25255
25256
25257
25258
25259
25260
25261
25262
25263
25264
25265
25266
25267
25268
25269
25270
25271
25272
25273
25274
25275
25276
25277
25278
25279
25280
25281
25282
25283
25284
25285
25286
25287
25288
25289
25290
25291
25292
25293
25294
25295
25296
25297
25298
25299
25300
25301
25302
25303
25304
25305
25306
25307
25308
25309
25310
25311
25312
25313
25314
25315
25316
25317
25318
25319
25320
25321
25322
25323
25324
25325
25326
25327
25328
25329
25330
25331
25332
25333
25334
25335
25336
25337
25338
25339
25340
25341
25342
25343
25344
25345
25346
25347
25348
25349
25350
25351
25352
25353
25354
25355
25356
25357
25358
25359
25360
25361
25362
25363
25364
25365
25366
25367
25368
25369
25370
25371
25372
25373
25374
25375
25376
25377
25378
25379
25380
25381
25382
25383
25384
25385
25386
25387
25388
25389
25390
25391
25392
25393
25394
25395
25396
25397
25398
25399
25400
25401
25402
25403
25404
25405
25406
25407
25408
25409
25410
25411
25412
25413
25414
25415
25416
25417
25418
25419
25420
25421
25422
25423
25424
25425
25426
25427
25428
25429
25430
25431
25432
25433
25434
25435
25436
25437
25438
25439
25440
25441
25442
25443
25444
25445
25446
25447
25448
25449
25450
25451
25452
25453
25454
25455
25456
25457
25458
25459
25460
25461
25462
25463
25464
25465
25466
25467
25468
25469
25470
25471
25472
25473
25474
25475
25476
25477
25478
25479
25480
25481
25482
25483
25484
25485
25486
25487
25488
25489
25490
25491
25492
25493
25494
25495
25496
25497
25498
25499
25500
25501
25502
25503
25504
25505
25506
25507
25508
25509
25510
25511
25512
25513
25514
25515
25516
25517
25518
25519
25520
25521
25522
25523
25524
25525
25526
25527
25528
25529
25530
25531
25532
25533
25534
25535
25536
25537
25538
25539
25540
25541
25542
25543
25544
25545
25546
25547
25548
25549
25550
25551
25552
25553
25554
25555
25556
25557
25558
25559
25560
25561
25562
25563
25564
25565
25566
25567
25568
25569
25570
25571
25572
25573
25574
25575
25576
25577
25578
25579
25580
25581
25582
25583
25584
25585
25586
25587
25588
25589
25590
25591
25592
25593
25594
25595
25596
25597
25598
25599
25600
25601
25602
25603
25604
25605
25606
25607
25608
25609
25610
25611
25612
25613
25614
25615
25616
25617
25618
25619
25620
25621
25622
25623
25624
25625
25626
25627
25628
25629
25630
25631
25632
25633
25634
25635
25636
25637
25638
25639
25640
25641
25642
25643
25644
25645
25646
25647
25648
25649
25650
25651
25652
25653
25654
25655
25656
25657
25658
25659
25660
25661
25662
25663
25664
25665
25666
25667
25668
25669
25670
25671
25672
25673
25674
25675
25676
25677
25678
25679
25680
25681
25682
25683
25684
25685
25686
25687
25688
25689
25690
25691
25692
25693
25694
25695
25696
25697
25698
25699
25700
25701
25702
25703
25704
25705
25706
25707
25708
25709
25710
25711
25712
25713
25714
25715
25716
25717
25718
25719
25720
25721
25722
25723
25724
25725
25726
25727
25728
25729
25730
25731
25732
25733
25734
25735
25736
25737
25738
25739
25740
25741
25742
25743
25744
25745
25746
25747
25748
25749
25750
25751
25752
25753
25754
25755
25756
25757
25758
25759
25760
25761
25762
25763
25764
25765
25766
25767
25768
25769
25770
25771
25772
25773
25774
25775
25776
25777
25778
25779
25780
25781
25782
25783
25784
25785
25786
25787
25788
25789
25790
25791
25792
25793
25794
25795
25796
25797
25798
25799
25800
25801
25802
25803
25804
25805
25806
25807
25808
25809
25810
25811
25812
25813
25814
25815
25816
25817
25818
25819
25820
25821
25822
25823
25824
25825
25826
25827
25828
25829
25830
25831
25832
25833
25834
25835
25836
25837
25838
25839
25840
25841
25842
25843
25844
25845
25846
25847
25848
25849
25850
25851
25852
25853
25854
25855
25856
25857
25858
25859
25860
25861
25862
25863
25864
25865
25866
25867
25868
25869
25870
25871
25872
25873
25874
25875
25876
25877
25878
25879
25880
25881
25882
25883
25884
25885
25886
25887
25888
25889
25890
25891
25892
25893
25894
25895
25896
25897
25898
25899
25900
25901
25902
25903
25904
25905
25906
25907
25908
25909
25910
25911
25912
25913
25914
25915
25916
25917
25918
25919
25920
25921
25922
25923
25924
25925
25926
25927
25928
25929
25930
25931
25932
25933
25934
25935
25936
25937
25938
25939
25940
25941
25942
25943
25944
25945
25946
25947
25948
25949
25950
25951
25952
25953
25954
25955
25956
25957
25958
25959
25960
25961
25962
25963
25964
25965
25966
25967
25968
25969
25970
25971
25972
25973
25974
25975
25976
25977
25978
25979
25980
25981
25982
25983
25984
25985
25986
25987
25988
25989
25990
25991
25992
25993
25994
25995
25996
25997
25998
25999
26000
26001
26002
26003
26004
26005
26006
26007
26008
26009
26010
26011
26012
26013
26014
26015
26016
26017
26018
26019
26020
26021
26022
26023
26024
26025
26026
26027
26028
26029
26030
26031
26032
26033
26034
26035
26036
26037
26038
26039
26040
26041
26042
26043
26044
26045
26046
26047
26048
26049
26050
26051
26052
26053
26054
26055
26056
26057
26058
26059
26060
26061
26062
26063
26064
26065
26066
26067
26068
26069
26070
26071
26072
26073
26074
26075
26076
26077
26078
26079
26080
26081
26082
26083
26084
26085
26086
26087
26088
26089
26090
26091
26092
26093
26094
26095
26096
26097
26098
26099
26100
26101
26102
26103
26104
26105
26106
26107
26108
26109
26110
26111
26112
26113
26114
26115
26116
26117
26118
26119
26120
26121
26122
26123
26124
26125
26126
26127
26128
26129
26130
26131
26132
26133
26134
26135
26136
26137
26138
26139
26140
26141
26142
26143
26144
26145
26146
26147
26148
26149
26150
26151
26152
26153
26154
26155
26156
26157
26158
26159
26160
26161
26162
26163
26164
26165
26166
26167
26168
26169
26170
26171
26172
26173
26174
26175
26176
26177
26178
26179
26180
26181
26182
26183
26184
26185
26186
26187
26188
26189
26190
26191
26192
26193
26194
26195
26196
26197
26198
26199
26200
26201
26202
26203
26204
26205
26206
26207
26208
26209
26210
26211
26212
26213
26214
26215
26216
26217
26218
26219
26220
26221
26222
26223
26224
26225
26226
26227
26228
26229
26230
26231
26232
26233
26234
26235
26236
26237
26238
26239
26240
26241
26242
26243
26244
26245
26246
26247
26248
26249
26250
26251
26252
26253
26254
26255
26256
26257
26258
26259
26260
26261
26262
26263
26264
26265
26266
26267
26268
26269
26270
26271
26272
26273
26274
26275
26276
26277
26278
26279
26280
26281
26282
26283
26284
26285
26286
26287
26288
26289
26290
26291
26292
26293
26294
26295
26296
26297
26298
26299
26300
26301
26302
26303
26304
26305
26306
26307
26308
26309
26310
26311
26312
26313
26314
26315
26316
26317
26318
26319
26320
26321
26322
26323
26324
26325
26326
26327
26328
26329
26330
26331
26332
26333
26334
26335
26336
26337
26338
26339
26340
26341
26342
26343
26344
26345
26346
26347
26348
26349
26350
26351
26352
26353
26354
26355
26356
26357
26358
26359
26360
26361
26362
26363
26364
26365
26366
26367
26368
26369
26370
26371
26372
26373
26374
26375
26376
26377
26378
26379
26380
26381
26382
26383
26384
26385
26386
26387
26388
26389
26390
26391
26392
26393
26394
26395
26396
26397
26398
26399
26400
26401
26402
26403
26404
26405
26406
26407
26408
26409
26410
26411
26412
26413
26414
26415
26416
26417
26418
26419
26420
26421
26422
26423
26424
26425
26426
26427
26428
26429
26430
26431
26432
26433
26434
26435
26436
26437
26438
26439
26440
26441
26442
26443
26444
26445
26446
26447
26448
26449
26450
26451
26452
26453
26454
26455
26456
26457
26458
26459
26460
26461
26462
26463
26464
26465
26466
26467
26468
26469
26470
26471
26472
26473
26474
26475
26476
26477
26478
26479
26480
26481
26482
26483
26484
26485
26486
26487
26488
26489
26490
26491
26492
26493
26494
26495
26496
26497
26498
26499
26500
26501
26502
26503
26504
26505
26506
26507
26508
26509
26510
26511
26512
26513
26514
26515
26516
26517
26518
26519
26520
26521
26522
26523
26524
26525
26526
26527
26528
26529
26530
26531
26532
26533
26534
26535
26536
26537
26538
26539
26540
26541
26542
26543
26544
26545
26546
26547
26548
26549
26550
26551
26552
26553
26554
26555
26556
26557
26558
26559
26560
26561
26562
26563
26564
26565
26566
26567
26568
26569
26570
26571
26572
26573
26574
26575
26576
26577
26578
26579
26580
26581
26582
26583
26584
26585
26586
26587
26588
26589
26590
26591
26592
26593
26594
26595
26596
26597
26598
26599
26600
26601
26602
26603
26604
26605
26606
26607
26608
26609
26610
26611
26612
26613
26614
26615
26616
26617
26618
26619
26620
26621
26622
26623
26624
26625
26626
26627
26628
26629
26630
26631
26632
26633
26634
26635
26636
26637
26638
26639
26640
26641
26642
26643
26644
26645
26646
26647
26648
26649
26650
26651
26652
26653
26654
26655
26656
26657
26658
26659
26660
26661
26662
26663
26664
26665
26666
26667
26668
26669
26670
26671
26672
26673
26674
26675
26676
26677
26678
26679
26680
26681
26682
26683
26684
26685
26686
26687
26688
26689
26690
26691
26692
26693
26694
26695
26696
26697
26698
26699
26700
26701
26702
26703
26704
26705
26706
26707
26708
26709
26710
26711
26712
26713
26714
26715
26716
26717
26718
26719
26720
26721
26722
26723
26724
26725
26726
26727
26728
26729
26730
26731
26732
26733
26734
26735
26736
26737
26738
26739
26740
26741
26742
26743
26744
26745
26746
26747
26748
26749
26750
26751
26752
26753
26754
26755
26756
26757
26758
26759
26760
26761
26762
26763
26764
26765
26766
26767
26768
26769
26770
26771
26772
26773
26774
26775
26776
26777
26778
26779
26780
26781
26782
26783
26784
26785
26786
26787
26788
26789
26790
26791
26792
26793
26794
26795
26796
26797
26798
26799
26800
26801
26802
26803
26804
26805
26806
26807
26808
26809
26810
26811
26812
26813
26814
26815
26816
26817
26818
26819
26820
26821
26822
26823
26824
26825
26826
26827
26828
26829
26830
26831
26832
26833
26834
26835
26836
26837
26838
26839
26840
26841
26842
26843
26844
26845
26846
26847
26848
26849
26850
26851
26852
26853
26854
26855
26856
26857
26858
26859
26860
26861
26862
26863
26864
26865
26866
26867
26868
26869
26870
26871
26872
26873
26874
26875
26876
26877
26878
26879
26880
26881
26882
26883
26884
26885
26886
26887
26888
26889
26890
26891
26892
26893
26894
26895
26896
26897
26898
26899
26900
26901
26902
26903
26904
26905
26906
26907
26908
26909
26910
26911
26912
26913
26914
26915
26916
26917
26918
26919
26920
26921
26922
26923
26924
26925
26926
26927
26928
26929
26930
26931
26932
26933
26934
26935
26936
26937
26938
26939
26940
26941
26942
26943
26944
26945
26946
26947
26948
26949
26950
26951
26952
26953
26954
26955
26956
26957
26958
26959
26960
26961
26962
26963
26964
26965
26966
26967
26968
26969
26970
26971
26972
26973
26974
26975
26976
26977
26978
26979
26980
26981
26982
26983
26984
26985
26986
26987
26988
26989
26990
26991
26992
26993
26994
26995
26996
26997
26998
26999
27000
27001
27002
27003
27004
27005
27006
27007
27008
27009
27010
27011
27012
27013
27014
27015
27016
27017
27018
27019
27020
27021
27022
27023
27024
27025
27026
27027
27028
27029
27030
27031
27032
27033
27034
27035
27036
27037
27038
27039
27040
27041
27042
27043
27044
27045
27046
27047
27048
27049
27050
27051
27052
27053
27054
27055
27056
27057
27058
27059
27060
27061
27062
27063
27064
27065
27066
27067
27068
27069
27070
27071
27072
27073
27074
27075
27076
27077
27078
27079
27080
27081
27082
27083
27084
27085
27086
27087
27088
27089
27090
27091
27092
27093
27094
27095
27096
27097
27098
27099
27100
27101
27102
27103
27104
27105
27106
27107
27108
27109
27110
27111
27112
27113
27114
27115
27116
27117
27118
27119
27120
27121
27122
27123
27124
27125
27126
27127
27128
27129
27130
27131
27132
27133
27134
27135
27136
27137
27138
27139
27140
27141
27142
27143
27144
27145
27146
27147
27148
27149
27150
27151
27152
27153
27154
27155
27156
27157
27158
27159
27160
27161
27162
27163
27164
27165
27166
27167
27168
27169
27170
27171
27172
27173
27174
27175
27176
27177
27178
27179
27180
27181
27182
27183
27184
27185
27186
27187
27188
27189
27190
27191
27192
27193
27194
27195
27196
27197
27198
27199
27200
27201
27202
27203
27204
27205
27206
27207
27208
27209
27210
27211
27212
27213
27214
27215
27216
27217
27218
27219
27220
27221
27222
27223
27224
27225
27226
27227
27228
27229
27230
27231
27232
27233
27234
27235
27236
27237
27238
27239
27240
27241
27242
27243
27244
27245
27246
27247
27248
27249
27250
27251
27252
27253
27254
27255
27256
27257
27258
27259
27260
27261
27262
27263
27264
27265
27266
27267
27268
27269
27270
27271
27272
27273
27274
27275
27276
27277
27278
27279
27280
27281
27282
27283
27284
27285
27286
27287
27288
27289
27290
27291
27292
27293
27294
27295
27296
27297
27298
27299
27300
27301
27302
27303
27304
27305
27306
27307
27308
27309
27310
27311
27312
27313
27314
27315
27316
27317
27318
27319
27320
27321
27322
27323
27324
27325
27326
27327
27328
27329
27330
27331
27332
27333
27334
27335
27336
27337
27338
27339
27340
27341
27342
27343
27344
27345
27346
27347
27348
27349
27350
27351
27352
27353
27354
27355
27356
27357
27358
27359
27360
27361
27362
27363
27364
27365
27366
27367
27368
27369
27370
27371
27372
27373
27374
27375
27376
27377
27378
27379
27380
27381
27382
27383
27384
27385
27386
27387
27388
27389
27390
27391
27392
27393
27394
27395
27396
27397
27398
27399
27400
27401
27402
27403
27404
27405
27406
27407
27408
27409
27410
27411
27412
27413
27414
27415
27416
27417
27418
27419
27420
27421
27422
27423
27424
27425
27426
27427
27428
27429
27430
27431
27432
27433
27434
27435
27436
27437
27438
27439
27440
27441
27442
27443
27444
27445
27446
27447
27448
27449
27450
27451
27452
27453
27454
27455
27456
27457
27458
27459
27460
27461
27462
27463
27464
27465
27466
27467
27468
27469
27470
27471
27472
27473
27474
27475
27476
27477
27478
27479
27480
27481
27482
27483
27484
27485
27486
27487
27488
27489
27490
27491
27492
27493
27494
27495
27496
27497
27498
27499
27500
27501
27502
27503
27504
27505
27506
27507
27508
27509
27510
27511
27512
27513
27514
27515
27516
27517
27518
27519
27520
27521
27522
27523
27524
27525
27526
27527
27528
27529
27530
27531
27532
27533
27534
27535
27536
27537
27538
27539
27540
27541
27542
27543
27544
27545
27546
27547
27548
27549
27550
27551
27552
27553
27554
27555
27556
27557
27558
27559
27560
27561
27562
27563
27564
27565
27566
27567
27568
27569
27570
27571
27572
27573
27574
27575
27576
27577
27578
27579
27580
27581
27582
27583
27584
27585
27586
27587
27588
27589
27590
27591
27592
27593
27594
27595
27596
27597
27598
27599
27600
27601
27602
27603
27604
27605
27606
27607
27608
27609
27610
27611
27612
27613
27614
27615
27616
27617
27618
27619
27620
27621
27622
27623
27624
27625
27626
27627
27628
27629
27630
27631
27632
27633
27634
27635
27636
27637
27638
27639
27640
27641
27642
27643
27644
27645
27646
27647
27648
27649
27650
27651
27652
27653
27654
27655
27656
27657
27658
27659
27660
27661
27662
27663
27664
27665
27666
27667
27668
27669
27670
27671
27672
27673
27674
27675
27676
27677
27678
27679
27680
27681
27682
27683
27684
27685
27686
27687
27688
27689
27690
27691
27692
27693
27694
27695
27696
27697
27698
27699
27700
27701
27702
27703
27704
27705
27706
27707
27708
27709
27710
27711
27712
27713
27714
27715
27716
27717
27718
27719
27720
27721
27722
27723
27724
27725
27726
27727
27728
27729
27730
27731
27732
27733
27734
27735
27736
27737
27738
27739
27740
27741
27742
27743
27744
27745
27746
27747
27748
27749
27750
27751
27752
27753
27754
27755
27756
27757
27758
27759
27760
27761
27762
27763
27764
27765
27766
27767
27768
27769
27770
27771
27772
27773
27774
27775
27776
27777
27778
27779
27780
27781
27782
27783
27784
27785
27786
27787
27788
27789
27790
27791
27792
27793
27794
27795
27796
27797
27798
27799
27800
27801
27802
27803
27804
27805
27806
27807
27808
27809
27810
27811
27812
27813
27814
27815
27816
27817
27818
27819
27820
27821
27822
27823
27824
27825
27826
27827
27828
27829
27830
27831
27832
27833
27834
27835
27836
27837
27838
27839
27840
27841
27842
27843
27844
27845
27846
27847
27848
27849
27850
27851
27852
27853
27854
27855
27856
27857
27858
27859
27860
27861
27862
27863
27864
27865
27866
27867
27868
27869
27870
27871
27872
27873
27874
27875
27876
27877
27878
27879
27880
27881
27882
27883
27884
27885
27886
27887
27888
27889
27890
27891
27892
27893
27894
27895
27896
27897
27898
27899
27900
27901
27902
27903
27904
27905
27906
27907
27908
27909
27910
27911
27912
27913
27914
27915
27916
27917
27918
27919
27920
27921
27922
27923
27924
27925
27926
27927
27928
27929
27930
27931
27932
27933
27934
27935
27936
27937
27938
27939
27940
27941
27942
27943
27944
27945
27946
27947
27948
27949
27950
27951
27952
27953
27954
27955
27956
27957
27958
27959
27960
27961
27962
27963
27964
27965
27966
27967
27968
27969
27970
27971
27972
27973
27974
27975
27976
27977
27978
27979
27980
27981
27982
27983
27984
27985
27986
27987
27988
27989
27990
27991
27992
27993
27994
27995
27996
27997
27998
27999
28000
28001
28002
28003
28004
28005
28006
28007
28008
28009
28010
28011
28012
28013
28014
28015
28016
28017
28018
28019
28020
28021
28022
28023
28024
28025
28026
28027
28028
28029
28030
28031
28032
28033
28034
28035
28036
28037
28038
28039
28040
28041
28042
28043
28044
28045
28046
28047
28048
28049
28050
28051
28052
28053
28054
28055
28056
28057
28058
28059
28060
28061
28062
28063
28064
28065
28066
28067
28068
28069
28070
28071
28072
28073
28074
28075
28076
28077
28078
28079
28080
28081
28082
28083
28084
28085
28086
28087
28088
28089
28090
28091
28092
28093
28094
28095
28096
28097
28098
28099
28100
28101
28102
28103
28104
28105
28106
28107
28108
28109
28110
28111
28112
28113
28114
28115
28116
28117
28118
28119
28120
28121
28122
28123
28124
28125
28126
28127
28128
28129
28130
28131
28132
28133
28134
28135
28136
28137
28138
28139
28140
28141
28142
28143
28144
28145
28146
28147
28148
28149
28150
28151
28152
28153
28154
28155
28156
28157
28158
28159
28160
28161
28162
28163
28164
28165
28166
28167
28168
28169
28170
28171
28172
28173
28174
28175
28176
28177
28178
28179
28180
28181
28182
28183
28184
28185
28186
28187
28188
28189
28190
28191
28192
28193
28194
28195
28196
28197
28198
28199
28200
28201
28202
28203
28204
28205
28206
28207
28208
28209
28210
28211
28212
28213
28214
28215
28216
28217
28218
28219
28220
28221
28222
28223
28224
28225
28226
28227
28228
28229
28230
28231
28232
28233
28234
28235
28236
28237
28238
28239
28240
28241
28242
28243
28244
28245
28246
28247
28248
28249
28250
28251
28252
28253
28254
28255
28256
28257
28258
28259
28260
28261
28262
28263
28264
28265
28266
28267
28268
28269
28270
28271
28272
28273
28274
28275
28276
28277
28278
28279
28280
28281
28282
28283
28284
28285
28286
28287
28288
28289
28290
28291
28292
28293
28294
28295
28296
28297
28298
28299
28300
28301
28302
28303
28304
28305
28306
28307
28308
28309
28310
28311
28312
28313
28314
28315
28316
28317
28318
28319
28320
28321
28322
28323
28324
28325
28326
28327
28328
28329
28330
28331
28332
28333
28334
28335
28336
28337
28338
28339
28340
28341
28342
28343
28344
28345
28346
28347
28348
28349
28350
28351
28352
28353
28354
28355
28356
28357
28358
28359
28360
28361
28362
28363
28364
28365
28366
28367
28368
28369
28370
28371
28372
28373
28374
28375
28376
28377
28378
28379
28380
28381
28382
28383
28384
28385
28386
28387
28388
28389
28390
28391
28392
28393
28394
28395
28396
28397
28398
28399
28400
28401
28402
28403
28404
28405
28406
28407
28408
28409
28410
28411
28412
28413
28414
28415
28416
28417
28418
28419
28420
28421
28422
28423
28424
28425
28426
28427
28428
28429
28430
28431
28432
28433
28434
28435
28436
28437
28438
28439
28440
28441
28442
28443
28444
28445
28446
28447
28448
28449
28450
28451
28452
28453
28454
28455
28456
28457
28458
28459
28460
28461
28462
28463
28464
28465
28466
28467
28468
28469
28470
28471
28472
28473
28474
28475
28476
28477
28478
28479
28480
28481
28482
28483
28484
28485
28486
28487
28488
28489
28490
28491
28492
28493
28494
28495
28496
28497
28498
28499
28500
28501
28502
28503
28504
28505
28506
28507
28508
28509
28510
28511
28512
28513
28514
28515
28516
28517
28518
28519
28520
28521
28522
28523
28524
28525
28526
28527
28528
28529
28530
28531
28532
28533
28534
28535
28536
28537
28538
28539
28540
28541
28542
28543
28544
28545
28546
28547
28548
28549
28550
28551
28552
28553
28554
28555
28556
28557
28558
28559
28560
28561
28562
28563
28564
28565
28566
28567
28568
28569
28570
28571
28572
28573
28574
28575
28576
28577
28578
28579
28580
28581
28582
28583
28584
28585
28586
28587
28588
28589
28590
28591
28592
28593
28594
28595
28596
28597
28598
28599
28600
28601
28602
28603
28604
28605
28606
28607
28608
28609
28610
28611
28612
28613
28614
28615
28616
28617
28618
28619
28620
28621
28622
28623
28624
28625
28626
28627
28628
28629
28630
28631
28632
28633
28634
28635
28636
28637
28638
28639
28640
28641
28642
28643
28644
28645
28646
28647
28648
28649
28650
28651
28652
28653
28654
28655
28656
28657
28658
28659
28660
28661
28662
28663
28664
28665
28666
28667
28668
28669
28670
28671
28672
28673
28674
28675
28676
28677
28678
28679
28680
28681
28682
28683
28684
28685
28686
28687
28688
28689
28690
28691
28692
28693
28694
28695
28696
28697
28698
28699
28700
28701
28702
28703
28704
28705
28706
28707
28708
28709
28710
28711
28712
28713
28714
28715
28716
28717
28718
28719
28720
28721
28722
28723
28724
28725
28726
28727
28728
28729
28730
28731
28732
28733
28734
28735
28736
28737
28738
28739
28740
28741
28742
28743
28744
28745
28746
28747
28748
28749
28750
28751
28752
28753
28754
28755
28756
28757
28758
28759
28760
28761
28762
28763
28764
28765
28766
28767
28768
28769
28770
28771
28772
28773
28774
28775
28776
28777
28778
28779
28780
28781
28782
28783
28784
28785
28786
28787
28788
28789
28790
28791
28792
28793
28794
28795
28796
28797
28798
28799
28800
28801
28802
28803
28804
28805
28806
28807
28808
28809
28810
28811
28812
28813
28814
28815
28816
28817
28818
28819
28820
28821
28822
28823
28824
28825
28826
28827
28828
28829
28830
28831
28832
28833
28834
28835
28836
28837
28838
28839
28840
28841
28842
28843
28844
28845
28846
28847
28848
28849
28850
28851
28852
28853
28854
28855
28856
28857
28858
28859
28860
28861
28862
28863
28864
28865
28866
28867
28868
28869
28870
28871
28872
28873
28874
28875
28876
28877
28878
28879
28880
28881
28882
28883
28884
28885
28886
28887
28888
28889
28890
28891
28892
28893
28894
28895
28896
28897
28898
28899
28900
28901
28902
28903
28904
28905
28906
28907
28908
28909
28910
28911
28912
28913
28914
28915
28916
28917
28918
28919
28920
28921
28922
28923
28924
28925
28926
28927
28928
28929
28930
28931
28932
28933
28934
28935
28936
28937
28938
28939
28940
28941
28942
28943
28944
28945
28946
28947
28948
28949
28950
28951
28952
28953
28954
28955
28956
28957
28958
28959
28960
28961
28962
28963
28964
28965
28966
28967
28968
28969
28970
28971
28972
28973
28974
28975
28976
28977
28978
28979
28980
28981
28982
28983
28984
28985
28986
28987
28988
28989
28990
28991
28992
28993
28994
28995
28996
28997
28998
28999
29000
29001
29002
29003
29004
29005
29006
29007
29008
29009
29010
29011
29012
29013
29014
29015
29016
29017
29018
29019
29020
29021
29022
29023
29024
29025
29026
29027
29028
29029
29030
29031
29032
29033
29034
29035
29036
29037
29038
29039
29040
29041
29042
29043
29044
29045
29046
29047
29048
29049
29050
29051
29052
29053
29054
29055
29056
29057
29058
29059
29060
29061
29062
29063
29064
29065
29066
29067
29068
29069
29070
29071
29072
29073
29074
29075
29076
29077
29078
29079
29080
29081
29082
29083
29084
29085
29086
29087
29088
29089
29090
29091
29092
29093
29094
29095
29096
29097
29098
29099
29100
29101
29102
29103
29104
29105
29106
29107
29108
29109
29110
29111
29112
29113
29114
29115
29116
29117
29118
29119
29120
29121
29122
29123
29124
29125
29126
29127
29128
29129
29130
29131
29132
29133
29134
29135
29136
29137
29138
29139
29140
29141
29142
29143
29144
29145
29146
29147
29148
29149
29150
29151
29152
29153
29154
29155
29156
29157
29158
29159
29160
29161
29162
29163
29164
29165
29166
29167
29168
29169
29170
29171
29172
29173
29174
29175
29176
29177
29178
29179
29180
29181
29182
29183
29184
29185
29186
29187
29188
29189
29190
29191
29192
29193
29194
29195
29196
29197
29198
29199
29200
29201
29202
29203
29204
29205
29206
29207
29208
29209
29210
29211
29212
29213
29214
29215
29216
29217
29218
29219
29220
29221
29222
29223
29224
29225
29226
29227
29228
29229
29230
29231
29232
29233
29234
29235
29236
29237
29238
29239
29240
29241
29242
29243
29244
29245
29246
29247
29248
29249
29250
29251
29252
29253
29254
29255
29256
29257
29258
29259
29260
29261
29262
29263
29264
29265
29266
29267
29268
29269
29270
29271
29272
29273
29274
29275
29276
29277
29278
29279
29280
29281
29282
29283
29284
29285
29286
29287
29288
29289
29290
29291
29292
29293
29294
29295
29296
29297
29298
29299
29300
29301
29302
29303
29304
29305
29306
29307
29308
29309
29310
29311
29312
29313
29314
29315
29316
29317
29318
29319
29320
29321
29322
29323
29324
29325
29326
29327
29328
29329
29330
29331
29332
29333
29334
29335
29336
29337
29338
29339
29340
29341
29342
29343
29344
29345
29346
29347
29348
29349
29350
29351
29352
29353
29354
29355
29356
29357
29358
29359
29360
29361
29362
29363
29364
29365
29366
29367
29368
29369
29370
29371
29372
29373
29374
29375
29376
29377
29378
29379
29380
29381
29382
29383
29384
29385
29386
29387
29388
29389
29390
29391
29392
29393
29394
29395
29396
29397
29398
29399
29400
29401
29402
29403
29404
29405
29406
29407
29408
29409
29410
29411
29412
29413
29414
29415
29416
29417
29418
29419
29420
29421
29422
29423
29424
29425
29426
29427
29428
29429
29430
29431
29432
29433
29434
29435
29436
29437
29438
29439
29440
29441
29442
29443
29444
29445
29446
29447
29448
29449
29450
29451
29452
29453
29454
29455
29456
29457
29458
29459
29460
29461
29462
29463
29464
29465
29466
29467
29468
29469
29470
29471
29472
29473
29474
29475
29476
29477
29478
29479
29480
29481
29482
29483
29484
29485
29486
29487
29488
29489
29490
29491
29492
29493
29494
29495
29496
29497
29498
29499
29500
29501
29502
29503
29504
29505
29506
/*!
* ONNX Runtime Web v1.14.0
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
(function webpackUniversalModuleDefinition(root, factory) {
	if(typeof exports === 'object' && typeof module === 'object')
		module.exports = factory();
	else if(typeof define === 'function' && define.amd)
		define([], factory);
	else if(typeof exports === 'object')
		exports["ort"] = factory();
	else
		root["ort"] = factory();
})(self, () => {
return /******/ (() => { // webpackBootstrap
/******/ 	var __webpack_modules__ = ({

/***/ "../common/dist/lib/backend-impl.js":
/*!******************************************!*\
  !*** ../common/dist/lib/backend-impl.js ***!
  \******************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "registerBackend": () => (/* binding */ registerBackend),
/* harmony export */   "resolveBackend": () => (/* binding */ resolveBackend)
/* harmony export */ });
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
const backends = {};
const backendsSortedByPriority = [];
/**
 * Register a backend.
 *
 * @param name - the name as a key to lookup as an execution provider.
 * @param backend - the backend object.
 * @param priority - an integer indicating the priority of the backend. Higher number means higher priority. if priority
 * < 0, it will be considered as a 'beta' version and will not be used as a fallback backend by default.
 *
 * @internal
 */
const registerBackend = (name, backend, priority) => {
    if (backend && typeof backend.init === 'function' && typeof backend.createSessionHandler === 'function') {
        const currentBackend = backends[name];
        if (currentBackend === undefined) {
            backends[name] = { backend, priority };
        }
        else if (currentBackend.priority > priority) {
            // same name is already registered with a higher priority. skip registeration.
            return;
        }
        else if (currentBackend.priority === priority) {
            if (currentBackend.backend !== backend) {
                throw new Error(`cannot register backend "${name}" using priority ${priority}`);
            }
        }
        if (priority >= 0) {
            const i = backendsSortedByPriority.indexOf(name);
            if (i !== -1) {
                backendsSortedByPriority.splice(i, 1);
            }
            for (let i = 0; i < backendsSortedByPriority.length; i++) {
                if (backends[backendsSortedByPriority[i]].priority <= priority) {
                    backendsSortedByPriority.splice(i, 0, name);
                    return;
                }
            }
            backendsSortedByPriority.push(name);
        }
        return;
    }
    throw new TypeError('not a valid backend');
};
/**
 * Resolve backend by specified hints.
 *
 * @param backendHints - a list of execution provider names to lookup. If omitted use registered backends as list.
 * @returns a promise that resolves to the backend.
 *
 * @internal
 */
const resolveBackend = async (backendHints) => {
    const backendNames = backendHints.length === 0 ? backendsSortedByPriority : backendHints;
    const errors = [];
    for (const backendName of backendNames) {
        const backendInfo = backends[backendName];
        if (backendInfo) {
            if (backendInfo.initialized) {
                return backendInfo.backend;
            }
            else if (backendInfo.aborted) {
                continue; // current backend is unavailable; try next
            }
            const isInitializing = !!backendInfo.initPromise;
            try {
                if (!isInitializing) {
                    backendInfo.initPromise = backendInfo.backend.init();
                }
                await backendInfo.initPromise;
                backendInfo.initialized = true;
                return backendInfo.backend;
            }
            catch (e) {
                if (!isInitializing) {
                    errors.push({ name: backendName, err: e });
                }
                backendInfo.aborted = true;
            }
            finally {
                delete backendInfo.initPromise;
            }
        }
    }
    throw new Error(`no available backend found. ERR: ${errors.map(e => `[${e.name}] ${e.err}`).join(', ')}`);
};
//# sourceMappingURL=backend-impl.js.map

/***/ }),

/***/ "../common/dist/lib/backend.js":
/*!*************************************!*\
  !*** ../common/dist/lib/backend.js ***!
  \*************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "registerBackend": () => (/* reexport safe */ _backend_impl__WEBPACK_IMPORTED_MODULE_0__.registerBackend)
/* harmony export */ });
/* harmony import */ var _backend_impl__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./backend-impl */ "../common/dist/lib/backend-impl.js");
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

//# sourceMappingURL=backend.js.map

/***/ }),

/***/ "../common/dist/lib/env-impl.js":
/*!**************************************!*\
  !*** ../common/dist/lib/env-impl.js ***!
  \**************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "EnvImpl": () => (/* binding */ EnvImpl)
/* harmony export */ });
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
class EnvImpl {
    constructor() {
        this.wasm = {};
        this.webgl = {};
        this.logLevelInternal = 'warning';
    }
    // TODO standadize the getter and setter convention in env for other fields.
    set logLevel(value) {
        if (value === undefined) {
            return;
        }
        if (typeof value !== 'string' || ['verbose', 'info', 'warning', 'error', 'fatal'].indexOf(value) === -1) {
            throw new Error(`Unsupported logging level: ${value}`);
        }
        this.logLevelInternal = value;
    }
    get logLevel() {
        return this.logLevelInternal;
    }
}
//# sourceMappingURL=env-impl.js.map

/***/ }),

/***/ "../common/dist/lib/env.js":
/*!*********************************!*\
  !*** ../common/dist/lib/env.js ***!
  \*********************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "env": () => (/* binding */ env)
/* harmony export */ });
/* harmony import */ var _env_impl__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./env-impl */ "../common/dist/lib/env-impl.js");
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

/**
 * Represent a set of flags as a global singleton.
 */
const env = new _env_impl__WEBPACK_IMPORTED_MODULE_0__.EnvImpl();
//# sourceMappingURL=env.js.map

/***/ }),

/***/ "../common/dist/lib/index.js":
/*!***********************************!*\
  !*** ../common/dist/lib/index.js ***!
  \***********************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "InferenceSession": () => (/* reexport safe */ _inference_session__WEBPACK_IMPORTED_MODULE_2__.InferenceSession),
/* harmony export */   "Tensor": () => (/* reexport safe */ _tensor__WEBPACK_IMPORTED_MODULE_3__.Tensor),
/* harmony export */   "env": () => (/* reexport safe */ _env__WEBPACK_IMPORTED_MODULE_1__.env),
/* harmony export */   "registerBackend": () => (/* reexport safe */ _backend__WEBPACK_IMPORTED_MODULE_0__.registerBackend)
/* harmony export */ });
/* harmony import */ var _backend__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./backend */ "../common/dist/lib/backend.js");
/* harmony import */ var _env__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./env */ "../common/dist/lib/env.js");
/* harmony import */ var _inference_session__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./inference-session */ "../common/dist/lib/inference-session.js");
/* harmony import */ var _tensor__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./tensor */ "../common/dist/lib/tensor.js");
/* harmony import */ var _onnx_value__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./onnx-value */ "../common/dist/lib/onnx-value.js");
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
/**
 * # ONNX Runtime JavaScript API
 *
 * ONNX Runtime JavaScript API is a unified API for all JavaScript usages, including the following NPM packages:
 *
 * - [onnxruntime-node](https://www.npmjs.com/package/onnxruntime-node)
 * - [onnxruntime-web](https://www.npmjs.com/package/onnxruntime-web)
 * - [onnxruntime-react-native](https://www.npmjs.com/package/onnxruntime-react-native)
 *
 * See also:
 * - [Get Started](https://onnxruntime.ai/docs/get-started/with-javascript.html)
 * - [Inference examples](https://github.com/microsoft/onnxruntime-inference-examples/tree/main/js)
 *
 * @packageDocumentation
 */





//# sourceMappingURL=index.js.map

/***/ }),

/***/ "../common/dist/lib/inference-session-impl.js":
/*!****************************************************!*\
  !*** ../common/dist/lib/inference-session-impl.js ***!
  \****************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "InferenceSession": () => (/* binding */ InferenceSession)
/* harmony export */ });
/* harmony import */ var _backend_impl__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./backend-impl */ "../common/dist/lib/backend-impl.js");
/* harmony import */ var _tensor__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./tensor */ "../common/dist/lib/tensor.js");
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.


class InferenceSession {
    constructor(handler) {
        this.handler = handler;
    }
    async run(feeds, arg1, arg2) {
        const fetches = {};
        let options = {};
        // check inputs
        if (typeof feeds !== 'object' || feeds === null || feeds instanceof _tensor__WEBPACK_IMPORTED_MODULE_1__.Tensor || Array.isArray(feeds)) {
            throw new TypeError('\'feeds\' must be an object that use input names as keys and OnnxValue as corresponding values.');
        }
        let isFetchesEmpty = true;
        // determine which override is being used
        if (typeof arg1 === 'object') {
            if (arg1 === null) {
                throw new TypeError('Unexpected argument[1]: cannot be null.');
            }
            if (arg1 instanceof _tensor__WEBPACK_IMPORTED_MODULE_1__.Tensor) {
                throw new TypeError('\'fetches\' cannot be a Tensor');
            }
            if (Array.isArray(arg1)) {
                if (arg1.length === 0) {
                    throw new TypeError('\'fetches\' cannot be an empty array.');
                }
                isFetchesEmpty = false;
                // output names
                for (const name of arg1) {
                    if (typeof name !== 'string') {
                        throw new TypeError('\'fetches\' must be a string array or an object.');
                    }
                    if (this.outputNames.indexOf(name) === -1) {
                        throw new RangeError(`'fetches' contains invalid output name: ${name}.`);
                    }
                    fetches[name] = null;
                }
                if (typeof arg2 === 'object' && arg2 !== null) {
                    options = arg2;
                }
                else if (typeof arg2 !== 'undefined') {
                    throw new TypeError('\'options\' must be an object.');
                }
            }
            else {
                // decide whether arg1 is fetches or options
                // if any output name is present and its value is valid OnnxValue, we consider it fetches
                let isFetches = false;
                const arg1Keys = Object.getOwnPropertyNames(arg1);
                for (const name of this.outputNames) {
                    if (arg1Keys.indexOf(name) !== -1) {
                        const v = arg1[name];
                        if (v === null || v instanceof _tensor__WEBPACK_IMPORTED_MODULE_1__.Tensor) {
                            isFetches = true;
                            isFetchesEmpty = false;
                            fetches[name] = v;
                        }
                    }
                }
                if (isFetches) {
                    if (typeof arg2 === 'object' && arg2 !== null) {
                        options = arg2;
                    }
                    else if (typeof arg2 !== 'undefined') {
                        throw new TypeError('\'options\' must be an object.');
                    }
                }
                else {
                    options = arg1;
                }
            }
        }
        else if (typeof arg1 !== 'undefined') {
            throw new TypeError('Unexpected argument[1]: must be \'fetches\' or \'options\'.');
        }
        // check if all inputs are in feed
        for (const name of this.inputNames) {
            if (typeof feeds[name] === 'undefined') {
                throw new Error(`input '${name}' is missing in 'feeds'.`);
            }
        }
        // if no fetches is specified, we use the full output names list
        if (isFetchesEmpty) {
            for (const name of this.outputNames) {
                fetches[name] = null;
            }
        }
        // feeds, fetches and options are prepared
        const results = await this.handler.run(feeds, fetches, options);
        const returnValue = {};
        for (const key in results) {
            if (Object.hasOwnProperty.call(results, key)) {
                returnValue[key] = new _tensor__WEBPACK_IMPORTED_MODULE_1__.Tensor(results[key].type, results[key].data, results[key].dims);
            }
        }
        return returnValue;
    }
    static async create(arg0, arg1, arg2, arg3) {
        // either load from a file or buffer
        let filePathOrUint8Array;
        let options = {};
        if (typeof arg0 === 'string') {
            filePathOrUint8Array = arg0;
            if (typeof arg1 === 'object' && arg1 !== null) {
                options = arg1;
            }
            else if (typeof arg1 !== 'undefined') {
                throw new TypeError('\'options\' must be an object.');
            }
        }
        else if (arg0 instanceof Uint8Array) {
            filePathOrUint8Array = arg0;
            if (typeof arg1 === 'object' && arg1 !== null) {
                options = arg1;
            }
            else if (typeof arg1 !== 'undefined') {
                throw new TypeError('\'options\' must be an object.');
            }
        }
        else if (arg0 instanceof ArrayBuffer ||
            (typeof SharedArrayBuffer !== 'undefined' && arg0 instanceof SharedArrayBuffer)) {
            const buffer = arg0;
            let byteOffset = 0;
            let byteLength = arg0.byteLength;
            if (typeof arg1 === 'object' && arg1 !== null) {
                options = arg1;
            }
            else if (typeof arg1 === 'number') {
                byteOffset = arg1;
                if (!Number.isSafeInteger(byteOffset)) {
                    throw new RangeError('\'byteOffset\' must be an integer.');
                }
                if (byteOffset < 0 || byteOffset >= buffer.byteLength) {
                    throw new RangeError(`'byteOffset' is out of range [0, ${buffer.byteLength}).`);
                }
                byteLength = arg0.byteLength - byteOffset;
                if (typeof arg2 === 'number') {
                    byteLength = arg2;
                    if (!Number.isSafeInteger(byteLength)) {
                        throw new RangeError('\'byteLength\' must be an integer.');
                    }
                    if (byteLength <= 0 || byteOffset + byteLength > buffer.byteLength) {
                        throw new RangeError(`'byteLength' is out of range (0, ${buffer.byteLength - byteOffset}].`);
                    }
                    if (typeof arg3 === 'object' && arg3 !== null) {
                        options = arg3;
                    }
                    else if (typeof arg3 !== 'undefined') {
                        throw new TypeError('\'options\' must be an object.');
                    }
                }
                else if (typeof arg2 !== 'undefined') {
                    throw new TypeError('\'byteLength\' must be a number.');
                }
            }
            else if (typeof arg1 !== 'undefined') {
                throw new TypeError('\'options\' must be an object.');
            }
            filePathOrUint8Array = new Uint8Array(buffer, byteOffset, byteLength);
        }
        else {
            throw new TypeError('Unexpected argument[0]: must be \'path\' or \'buffer\'.');
        }
        // get backend hints
        const eps = options.executionProviders || [];
        const backendHints = eps.map(i => typeof i === 'string' ? i : i.name);
        const backend = await (0,_backend_impl__WEBPACK_IMPORTED_MODULE_0__.resolveBackend)(backendHints);
        const handler = await backend.createSessionHandler(filePathOrUint8Array, options);
        return new InferenceSession(handler);
    }
    startProfiling() {
        this.handler.startProfiling();
    }
    endProfiling() {
        this.handler.endProfiling();
    }
    get inputNames() {
        return this.handler.inputNames;
    }
    get outputNames() {
        return this.handler.outputNames;
    }
}
//# sourceMappingURL=inference-session-impl.js.map

/***/ }),

/***/ "../common/dist/lib/inference-session.js":
/*!***********************************************!*\
  !*** ../common/dist/lib/inference-session.js ***!
  \***********************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "InferenceSession": () => (/* binding */ InferenceSession)
/* harmony export */ });
/* harmony import */ var _inference_session_impl__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./inference-session-impl */ "../common/dist/lib/inference-session-impl.js");
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

// eslint-disable-next-line @typescript-eslint/naming-convention
const InferenceSession = _inference_session_impl__WEBPACK_IMPORTED_MODULE_0__.InferenceSession;
//# sourceMappingURL=inference-session.js.map

/***/ }),

/***/ "../common/dist/lib/onnx-value.js":
/*!****************************************!*\
  !*** ../common/dist/lib/onnx-value.js ***!
  \****************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

//# sourceMappingURL=onnx-value.js.map

/***/ }),

/***/ "../common/dist/lib/tensor-impl.js":
/*!*****************************************!*\
  !*** ../common/dist/lib/tensor-impl.js ***!
  \*****************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "Tensor": () => (/* binding */ Tensor)
/* harmony export */ });
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
const isBigInt64ArrayAvailable = typeof BigInt64Array !== 'undefined' && typeof BigInt64Array.from === 'function';
const isBigUint64ArrayAvailable = typeof BigUint64Array !== 'undefined' && typeof BigUint64Array.from === 'function';
// a runtime map that maps type string to TypedArray constructor. Should match Tensor.DataTypeMap.
const NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP = new Map([
    ['float32', Float32Array],
    ['uint8', Uint8Array],
    ['int8', Int8Array],
    ['uint16', Uint16Array],
    ['int16', Int16Array],
    ['int32', Int32Array],
    ['bool', Uint8Array],
    ['float64', Float64Array],
    ['uint32', Uint32Array],
]);
// a runtime map that maps type string to TypedArray constructor. Should match Tensor.DataTypeMap.
const NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP = new Map([
    [Float32Array, 'float32'],
    [Uint8Array, 'uint8'],
    [Int8Array, 'int8'],
    [Uint16Array, 'uint16'],
    [Int16Array, 'int16'],
    [Int32Array, 'int32'],
    [Float64Array, 'float64'],
    [Uint32Array, 'uint32'],
]);
if (isBigInt64ArrayAvailable) {
    NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set('int64', BigInt64Array);
    NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(BigInt64Array, 'int64');
}
if (isBigUint64ArrayAvailable) {
    NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set('uint64', BigUint64Array);
    NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(BigUint64Array, 'uint64');
}
/**
 * calculate size from dims.
 *
 * @param dims the dims array. May be an illegal input.
 */
const calculateSize = (dims) => {
    let size = 1;
    for (let i = 0; i < dims.length; i++) {
        const dim = dims[i];
        if (typeof dim !== 'number' || !Number.isSafeInteger(dim)) {
            throw new TypeError(`dims[${i}] must be an integer, got: ${dim}`);
        }
        if (dim < 0) {
            throw new RangeError(`dims[${i}] must be a non-negative integer, got: ${dim}`);
        }
        size *= dim;
    }
    return size;
};
class Tensor {
    constructor(arg0, arg1, arg2) {
        let type;
        let data;
        let dims;
        // check whether arg0 is type or data
        if (typeof arg0 === 'string') {
            //
            // Override: constructor(type, data, ...)
            //
            type = arg0;
            dims = arg2;
            if (arg0 === 'string') {
                // string tensor
                if (!Array.isArray(arg1)) {
                    throw new TypeError('A string tensor\'s data must be a string array.');
                }
                // we don't check whether every element in the array is string; this is too slow. we assume it's correct and
                // error will be populated at inference
                data = arg1;
            }
            else {
                // numeric tensor
                const typedArrayConstructor = NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(arg0);
                if (typedArrayConstructor === undefined) {
                    throw new TypeError(`Unsupported tensor type: ${arg0}.`);
                }
                if (Array.isArray(arg1)) {
                    // use 'as any' here because TypeScript's check on type of 'SupportedTypedArrayConstructors.from()' produces
                    // incorrect results.
                    // 'typedArrayConstructor' should be one of the typed array prototype objects.
                    // eslint-disable-next-line @typescript-eslint/no-explicit-any
                    data = typedArrayConstructor.from(arg1);
                }
                else if (arg1 instanceof typedArrayConstructor) {
                    data = arg1;
                }
                else {
                    throw new TypeError(`A ${type} tensor's data must be type of ${typedArrayConstructor}`);
                }
            }
        }
        else {
            //
            // Override: constructor(data, ...)
            //
            dims = arg1;
            if (Array.isArray(arg0)) {
                // only boolean[] and string[] is supported
                if (arg0.length === 0) {
                    throw new TypeError('Tensor type cannot be inferred from an empty array.');
                }
                const firstElementType = typeof arg0[0];
                if (firstElementType === 'string') {
                    type = 'string';
                    data = arg0;
                }
                else if (firstElementType === 'boolean') {
                    type = 'bool';
                    // 'arg0' is of type 'boolean[]'. Uint8Array.from(boolean[]) actually works, but typescript thinks this is
                    // wrong type. We use 'as any' to make it happy.
                    // eslint-disable-next-line @typescript-eslint/no-explicit-any
                    data = Uint8Array.from(arg0);
                }
                else {
                    throw new TypeError(`Invalid element type of data array: ${firstElementType}.`);
                }
            }
            else {
                // get tensor type from TypedArray
                const mappedType = NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(arg0.constructor);
                if (mappedType === undefined) {
                    throw new TypeError(`Unsupported type for tensor data: ${arg0.constructor}.`);
                }
                type = mappedType;
                data = arg0;
            }
        }
        // type and data is processed, now processing dims
        if (dims === undefined) {
            // assume 1-D tensor if dims omitted
            dims = [data.length];
        }
        else if (!Array.isArray(dims)) {
            throw new TypeError('A tensor\'s dims must be a number array');
        }
        // perform check
        const size = calculateSize(dims);
        if (size !== data.length) {
            throw new Error(`Tensor's size(${size}) does not match data length(${data.length}).`);
        }
        this.dims = dims;
        this.type = type;
        this.data = data;
        this.size = size;
    }
    // #endregion
    /**
     * Create a new tensor object from image object
     *
     * @param buffer - Extracted image buffer data - assuming RGBA format
     * @param imageFormat - input image configuration - required configurations height, width, format
     * @param tensorFormat - output tensor configuration - Default is RGB format
     */
    static bufferToTensor(buffer, options) {
        if (buffer === undefined) {
            throw new Error('Image buffer must be defined');
        }
        if (options.height === undefined || options.width === undefined) {
            throw new Error('Image height and width must be defined');
        }
        const { height, width } = options;
        const norm = options.norm;
        let normMean;
        let normBias;
        if (norm === undefined || norm.mean === undefined) {
            normMean = 255;
        }
        else {
            normMean = norm.mean;
        }
        if (norm === undefined || norm.bias === undefined) {
            normBias = 0;
        }
        else {
            normBias = norm.bias;
        }
        const inputformat = options.bitmapFormat !== undefined ? options.bitmapFormat : 'RGBA';
        // default value is RGBA since imagedata and HTMLImageElement uses it
        const outputformat = options.tensorFormat !== undefined ?
            (options.tensorFormat !== undefined ? options.tensorFormat : 'RGB') :
            'RGB';
        const offset = height * width;
        const float32Data = outputformat === 'RGBA' ? new Float32Array(offset * 4) : new Float32Array(offset * 3);
        // Default pointer assignments
        let step = 4, rImagePointer = 0, gImagePointer = 1, bImagePointer = 2, aImagePointer = 3;
        let rTensorPointer = 0, gTensorPointer = offset, bTensorPointer = offset * 2, aTensorPointer = -1;
        // Updating the pointer assignments based on the input image format
        if (inputformat === 'RGB') {
            step = 3;
            rImagePointer = 0;
            gImagePointer = 1;
            bImagePointer = 2;
            aImagePointer = -1;
        }
        // Updating the pointer assignments based on the output tensor format
        if (outputformat === 'RGBA') {
            aTensorPointer = offset * 3;
        }
        else if (outputformat === 'RBG') {
            rTensorPointer = 0;
            bTensorPointer = offset;
            gTensorPointer = offset * 2;
        }
        else if (outputformat === 'BGR') {
            bTensorPointer = 0;
            gTensorPointer = offset;
            rTensorPointer = offset * 2;
        }
        for (let i = 0; i < offset; i++, rImagePointer += step, bImagePointer += step, gImagePointer += step, aImagePointer += step) {
            float32Data[rTensorPointer++] = (buffer[rImagePointer] + normBias) / normMean;
            float32Data[gTensorPointer++] = (buffer[gImagePointer] + normBias) / normMean;
            float32Data[bTensorPointer++] = (buffer[bImagePointer] + normBias) / normMean;
            if (aTensorPointer !== -1 && aImagePointer !== -1) {
                float32Data[aTensorPointer++] = (buffer[aImagePointer] + normBias) / normMean;
            }
        }
        // Float32Array -> ort.Tensor
        const outputTensor = outputformat === 'RGBA' ? new Tensor('float32', float32Data, [1, 4, height, width]) :
            new Tensor('float32', float32Data, [1, 3, height, width]);
        return outputTensor;
    }
    static async fromImage(image, options) {
        // checking the type of image object
        const isHTMLImageEle = typeof (HTMLImageElement) !== 'undefined' && image instanceof HTMLImageElement;
        const isImageDataEle = typeof (ImageData) !== 'undefined' && image instanceof ImageData;
        const isImageBitmap = typeof (ImageBitmap) !== 'undefined' && image instanceof ImageBitmap;
        const isURL = typeof (String) !== 'undefined' && (image instanceof String || typeof image === 'string');
        let data;
        let tensorConfig = {};
        // filling and checking image configuration options
        if (isHTMLImageEle) {
            // HTMLImageElement - image object - format is RGBA by default
            const canvas = document.createElement('canvas');
            const pixels2DContext = canvas.getContext('2d');
            if (pixels2DContext != null) {
                let height = image.naturalHeight;
                let width = image.naturalWidth;
                if (options !== undefined && options.resizedHeight !== undefined && options.resizedWidth !== undefined) {
                    height = options.resizedHeight;
                    width = options.resizedWidth;
                }
                if (options !== undefined) {
                    tensorConfig = options;
                    if (options.tensorFormat !== undefined) {
                        throw new Error('Image input config format must be RGBA for HTMLImageElement');
                    }
                    else {
                        tensorConfig.tensorFormat = 'RGBA';
                    }
                    if (options.height !== undefined && options.height !== height) {
                        throw new Error('Image input config height doesn\'t match HTMLImageElement height');
                    }
                    else {
                        tensorConfig.height = height;
                    }
                    if (options.width !== undefined && options.width !== width) {
                        throw new Error('Image input config width doesn\'t match HTMLImageElement width');
                    }
                    else {
                        tensorConfig.width = width;
                    }
                }
                else {
                    tensorConfig.tensorFormat = 'RGBA';
                    tensorConfig.height = height;
                    tensorConfig.width = width;
                }
                canvas.width = width;
                canvas.height = height;
                pixels2DContext.drawImage(image, 0, 0, width, height);
                data = pixels2DContext.getImageData(0, 0, width, height).data;
            }
            else {
                throw new Error('Can not access image data');
            }
        }
        else if (isImageDataEle) {
            // ImageData - image object - format is RGBA by default
            const format = 'RGBA';
            let height;
            let width;
            if (options !== undefined && options.resizedWidth !== undefined && options.resizedHeight !== undefined) {
                height = options.resizedHeight;
                width = options.resizedWidth;
            }
            else {
                height = image.height;
                width = image.width;
            }
            if (options !== undefined) {
                tensorConfig = options;
                if (options.bitmapFormat !== undefined && options.bitmapFormat !== format) {
                    throw new Error('Image input config format must be RGBA for ImageData');
                }
                else {
                    tensorConfig.bitmapFormat = 'RGBA';
                }
            }
            else {
                tensorConfig.bitmapFormat = 'RGBA';
            }
            tensorConfig.height = height;
            tensorConfig.width = width;
            if (options !== undefined) {
                const tempCanvas = document.createElement('canvas');
                tempCanvas.width = width;
                tempCanvas.height = height;
                const pixels2DContext = tempCanvas.getContext('2d');
                if (pixels2DContext != null) {
                    pixels2DContext.putImageData(image, 0, 0);
                    data = pixels2DContext.getImageData(0, 0, width, height).data;
                }
                else {
                    throw new Error('Can not access image data');
                }
            }
            else {
                data = image.data;
            }
        }
        else if (isImageBitmap) {
            // ImageBitmap - image object - format must be provided by user
            if (options === undefined) {
                throw new Error('Please provide image config with format for Imagebitmap');
            }
            if (options.bitmapFormat !== undefined) {
                throw new Error('Image input config format must be defined for ImageBitmap');
            }
            const pixels2DContext = document.createElement('canvas').getContext('2d');
            if (pixels2DContext != null) {
                const height = image.height;
                const width = image.width;
                pixels2DContext.drawImage(image, 0, 0, width, height);
                data = pixels2DContext.getImageData(0, 0, width, height).data;
                if (options !== undefined) {
                    // using square brackets to avoid TS error - type 'never'
                    if (options.height !== undefined && options.height !== height) {
                        throw new Error('Image input config height doesn\'t match ImageBitmap height');
                    }
                    else {
                        tensorConfig.height = height;
                    }
                    // using square brackets to avoid TS error - type 'never'
                    if (options.width !== undefined && options.width !== width) {
                        throw new Error('Image input config width doesn\'t match ImageBitmap width');
                    }
                    else {
                        tensorConfig.width = width;
                    }
                }
                else {
                    tensorConfig.height = height;
                    tensorConfig.width = width;
                }
                return Tensor.bufferToTensor(data, tensorConfig);
            }
            else {
                throw new Error('Can not access image data');
            }
        }
        else if (isURL) {
            return new Promise((resolve, reject) => {
                const canvas = document.createElement('canvas');
                const context = canvas.getContext('2d');
                if (!image || !context) {
                    return reject();
                }
                const newImage = new Image();
                newImage.crossOrigin = 'Anonymous';
                newImage.src = image;
                newImage.onload = () => {
                    canvas.width = newImage.width;
                    canvas.height = newImage.height;
                    context.drawImage(newImage, 0, 0, canvas.width, canvas.height);
                    const img = context.getImageData(0, 0, canvas.width, canvas.height);
                    if (options !== undefined) {
                        // using square brackets to avoid TS error - type 'never'
                        if (options.height !== undefined && options.height !== canvas.height) {
                            throw new Error('Image input config height doesn\'t match ImageBitmap height');
                        }
                        else {
                            tensorConfig.height = canvas.height;
                        }
                        // using square brackets to avoid TS error - type 'never'
                        if (options.width !== undefined && options.width !== canvas.width) {
                            throw new Error('Image input config width doesn\'t match ImageBitmap width');
                        }
                        else {
                            tensorConfig.width = canvas.width;
                        }
                    }
                    else {
                        tensorConfig.height = canvas.height;
                        tensorConfig.width = canvas.width;
                    }
                    resolve(Tensor.bufferToTensor(img.data, tensorConfig));
                };
            });
        }
        else {
            throw new Error('Input data provided is not supported - aborted tensor creation');
        }
        if (data !== undefined) {
            return Tensor.bufferToTensor(data, tensorConfig);
        }
        else {
            throw new Error('Input data provided is not supported - aborted tensor creation');
        }
    }
    toImageData(options) {
        var _a, _b;
        const pixels2DContext = document.createElement('canvas').getContext('2d');
        let image;
        if (pixels2DContext != null) {
            // Default values for height and width & format
            const width = this.dims[3];
            const height = this.dims[2];
            const channels = this.dims[1];
            const inputformat = options !== undefined ? (options.format !== undefined ? options.format : 'RGB') : 'RGB';
            const normMean = options !== undefined ? (((_a = options.norm) === null || _a === void 0 ? void 0 : _a.mean) !== undefined ? options.norm.mean : 255) : 255;
            const normBias = options !== undefined ? (((_b = options.norm) === null || _b === void 0 ? void 0 : _b.bias) !== undefined ? options.norm.bias : 0) : 0;
            const offset = height * width;
            if (options !== undefined) {
                if (options.height !== undefined && options.height !== height) {
                    throw new Error('Image output config height doesn\'t match tensor height');
                }
                if (options.width !== undefined && options.width !== width) {
                    throw new Error('Image output config width doesn\'t match tensor width');
                }
                if (options.format !== undefined && (channels === 4 && options.format !== 'RGBA') ||
                    (channels === 3 && (options.format !== 'RGB' && options.format !== 'BGR'))) {
                    throw new Error('Tensor format doesn\'t match input tensor dims');
                }
            }
            // Default pointer assignments
            const step = 4;
            let rImagePointer = 0, gImagePointer = 1, bImagePointer = 2, aImagePointer = 3;
            let rTensorPointer = 0, gTensorPointer = offset, bTensorPointer = offset * 2, aTensorPointer = -1;
            // Updating the pointer assignments based on the input image format
            if (inputformat === 'RGBA') {
                rTensorPointer = 0;
                gTensorPointer = offset;
                bTensorPointer = offset * 2;
                aTensorPointer = offset * 3;
            }
            else if (inputformat === 'RGB') {
                rTensorPointer = 0;
                gTensorPointer = offset;
                bTensorPointer = offset * 2;
            }
            else if (inputformat === 'RBG') {
                rTensorPointer = 0;
                bTensorPointer = offset;
                gTensorPointer = offset * 2;
            }
            image = pixels2DContext.createImageData(width, height);
            for (let i = 0; i < height * width; rImagePointer += step, gImagePointer += step, bImagePointer += step, aImagePointer += step, i++) {
                image.data[rImagePointer] = (this.data[rTensorPointer++] - normBias) * normMean; // R value
                image.data[gImagePointer] = (this.data[gTensorPointer++] - normBias) * normMean; // G value
                image.data[bImagePointer] = (this.data[bTensorPointer++] - normBias) * normMean; // B value
                image.data[aImagePointer] =
                    aTensorPointer === -1 ? 255 : (this.data[aTensorPointer++] - normBias) * normMean; // A value
            }
        }
        else {
            throw new Error('Can not access image data');
        }
        return image;
    }
    // #endregion
    // #region tensor utilities
    reshape(dims) {
        return new Tensor(this.type, this.data, dims);
    }
}
//# sourceMappingURL=tensor-impl.js.map

/***/ }),

/***/ "../common/dist/lib/tensor.js":
/*!************************************!*\
  !*** ../common/dist/lib/tensor.js ***!
  \************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "Tensor": () => (/* binding */ Tensor)
/* harmony export */ });
/* harmony import */ var _tensor_impl__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./tensor-impl */ "../common/dist/lib/tensor-impl.js");
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

// eslint-disable-next-line @typescript-eslint/naming-convention
const Tensor = _tensor_impl__WEBPACK_IMPORTED_MODULE_0__.Tensor;
//# sourceMappingURL=tensor.js.map

/***/ }),

/***/ "./lib/wasm/binding/ort-wasm-threaded.js":
/*!***********************************************!*\
  !*** ./lib/wasm/binding/ort-wasm-threaded.js ***!
  \***********************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var __filename = "/index.js";
var __dirname = "/";

var ortWasmThreaded = (() => {
  var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined;
  if (true) _scriptDir = _scriptDir || __filename;
  return (
function(ortWasmThreaded) {
  ortWasmThreaded = ortWasmThreaded || {};


function d(){m.buffer!=n&&p(m.buffer);return aa}function q(){m.buffer!=n&&p(m.buffer);return ba}function r(){m.buffer!=n&&p(m.buffer);return ca}function v(){m.buffer!=n&&p(m.buffer);return da}function ea(){m.buffer!=n&&p(m.buffer);return fa}var x;x||(x=typeof ortWasmThreaded !== 'undefined' ? ortWasmThreaded : {});var ha,ia;x.ready=new Promise(function(a,b){ha=a;ia=b});
var ja=Object.assign({},x),ka="./this.program",la=(a,b)=>{throw b;},ma="object"==typeof window,y="function"==typeof importScripts,B="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,C=x.ENVIRONMENT_IS_PTHREAD||!1,D="";function na(a){return x.locateFile?x.locateFile(a,D):D+a}var oa,pa,qa,fs,ra,sa;
if(B){D=y?(__webpack_require__(/*! path */ "?75c6").dirname)(D)+"/":__dirname+"/";sa=()=>{ra||(fs=__webpack_require__(/*! fs */ "?63c8"),ra=__webpack_require__(/*! path */ "?75c6"))};oa=function(b,c){sa();b=ra.normalize(b);return fs.readFileSync(b,c?void 0:"utf8")};qa=b=>{b=oa(b,!0);b.buffer||(b=new Uint8Array(b));return b};pa=(b,c,e)=>{sa();b=ra.normalize(b);fs.readFile(b,function(f,h){f?e(f):c(h.buffer)})};1<process.argv.length&&(ka=process.argv[1].replace(/\\/g,"/"));process.argv.slice(2);process.on("uncaughtException",function(b){if(!(b instanceof E))throw b;});process.on("unhandledRejection",
function(b){throw b;});la=(b,c)=>{if(F())throw process.exitCode=b,c;c instanceof E||G("exiting due to exception: "+c);process.exit(b)};x.inspect=function(){return"[Emscripten Module object]"};let a;try{a=__webpack_require__(/*! worker_threads */ "?c6f7")}catch(b){throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'),b;}__webpack_require__.g.Worker=a.Worker}else if(ma||y)y?D=self.location.href:"undefined"!=typeof document&&document.currentScript&&(D=document.currentScript.src),
_scriptDir&&(D=_scriptDir),0!==D.indexOf("blob:")?D=D.substr(0,D.replace(/[?#].*/,"").lastIndexOf("/")+1):D="",B||(oa=a=>{var b=new XMLHttpRequest;b.open("GET",a,!1);b.send(null);return b.responseText},y&&(qa=a=>{var b=new XMLHttpRequest;b.open("GET",a,!1);b.responseType="arraybuffer";b.send(null);return new Uint8Array(b.response)}),pa=(a,b,c)=>{var e=new XMLHttpRequest;e.open("GET",a,!0);e.responseType="arraybuffer";e.onload=()=>{200==e.status||0==e.status&&e.response?b(e.response):c()};e.onerror=
c;e.send(null)});B&&"undefined"==typeof performance&&(__webpack_require__.g.performance=(__webpack_require__(/*! perf_hooks */ "?674f").performance));var ta=console.log.bind(console),ua=console.warn.bind(console);B&&(sa(),ta=a=>fs.writeSync(1,a+"\n"),ua=a=>fs.writeSync(2,a+"\n"));var va=x.print||ta,G=x.printErr||ua;Object.assign(x,ja);ja=null;x.thisProgram&&(ka=x.thisProgram);x.quit&&(la=x.quit);var H;x.wasmBinary&&(H=x.wasmBinary);var noExitRuntime=x.noExitRuntime||!1;"object"!=typeof WebAssembly&&I("no native wasm support detected");
var m,wa,xa=!1,ya="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;
function za(a,b,c){b>>>=0;var e=b+c;for(c=b;a[c]&&!(c>=e);)++c;if(16<c-b&&a.buffer&&ya)return ya.decode(a.buffer instanceof SharedArrayBuffer?a.slice(b,c):a.subarray(b,c));for(e="";b<c;){var f=a[b++];if(f&128){var h=a[b++]&63;if(192==(f&224))e+=String.fromCharCode((f&31)<<6|h);else{var k=a[b++]&63;f=224==(f&240)?(f&15)<<12|h<<6|k:(f&7)<<18|h<<12|k<<6|a[b++]&63;65536>f?e+=String.fromCharCode(f):(f-=65536,e+=String.fromCharCode(55296|f>>10,56320|f&1023))}}else e+=String.fromCharCode(f)}return e}
function Aa(a,b){return(a>>>=0)?za(q(),a,b):""}
function Ba(a,b,c,e){c>>>=0;if(!(0<e))return 0;var f=c;e=c+e-1;for(var h=0;h<a.length;++h){var k=a.charCodeAt(h);if(55296<=k&&57343>=k){var l=a.charCodeAt(++h);k=65536+((k&1023)<<10)|l&1023}if(127>=k){if(c>=e)break;b[c++>>>0]=k}else{if(2047>=k){if(c+1>=e)break;b[c++>>>0]=192|k>>6}else{if(65535>=k){if(c+2>=e)break;b[c++>>>0]=224|k>>12}else{if(c+3>=e)break;b[c++>>>0]=240|k>>18;b[c++>>>0]=128|k>>12&63}b[c++>>>0]=128|k>>6&63}b[c++>>>0]=128|k&63}}b[c>>>0]=0;return c-f}
function Ca(a){for(var b=0,c=0;c<a.length;++c){var e=a.charCodeAt(c);127>=e?b++:2047>=e?b+=2:55296<=e&&57343>=e?(b+=4,++c):b+=3}return b}var n,aa,ba,ca,da,fa;C&&(n=x.buffer);function p(a){n=a;x.HEAP8=aa=new Int8Array(a);x.HEAP16=new Int16Array(a);x.HEAP32=ca=new Int32Array(a);x.HEAPU8=ba=new Uint8Array(a);x.HEAPU16=new Uint16Array(a);x.HEAPU32=da=new Uint32Array(a);x.HEAPF32=new Float32Array(a);x.HEAPF64=fa=new Float64Array(a)}var Da=x.INITIAL_MEMORY||16777216;
if(C)m=x.wasmMemory,n=x.buffer;else if(x.wasmMemory)m=x.wasmMemory;else if(m=new WebAssembly.Memory({initial:Da/65536,maximum:65536,shared:!0}),!(m.buffer instanceof SharedArrayBuffer))throw G("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),B&&console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"),
Error("bad memory");m&&(n=m.buffer);Da=n.byteLength;p(n);var Ea,Fa=[],Ga=[],Ha=[],Ia=[],Ja=0;function F(){return noExitRuntime||0<Ja}function Ka(){var a=x.preRun.shift();Fa.unshift(a)}var L=0,La=null,M=null;function I(a){if(C)postMessage({cmd:"onAbort",arg:a});else if(x.onAbort)x.onAbort(a);a="Aborted("+a+")";G(a);xa=!0;a=new WebAssembly.RuntimeError(a+". Build with -sASSERTIONS for more info.");ia(a);throw a;}function Ma(){return O.startsWith("data:application/octet-stream;base64,")}var O;O="ort-wasm-threaded.wasm";
Ma()||(O=na(O));function Na(){var a=O;try{if(a==O&&H)return new Uint8Array(H);if(qa)return qa(a);throw"both async and sync fetching of the wasm failed";}catch(b){I(b)}}
function Oa(){if(!H&&(ma||y)){if("function"==typeof fetch&&!O.startsWith("file://"))return fetch(O,{credentials:"same-origin"}).then(function(a){if(!a.ok)throw"failed to load wasm binary file at '"+O+"'";return a.arrayBuffer()}).catch(function(){return Na()});if(pa)return new Promise(function(a,b){pa(O,function(c){a(new Uint8Array(c))},b)})}return Promise.resolve().then(function(){return Na()})}var Pa={};
function E(a){this.name="ExitStatus";this.message="Program terminated with exit("+a+")";this.status=a}function Qa(a){(a=P.Vb[a])||I();P.mc(a)}function Ra(a){var b=P.Cc();if(!b)return 6;P.ac.push(b);P.Vb[a.Ub]=b;b.Ub=a.Ub;var c={cmd:"run",start_routine:a.Ic,arg:a.zc,pthread_ptr:a.Ub};b.$b=()=>{c.time=performance.now();b.postMessage(c,a.Nc)};b.loaded&&(b.$b(),delete b.$b);return 0}function Sa(a){if(C)return Q(1,1,a);if(!F()){P.oc();if(x.onExit)x.onExit(a);xa=!0}la(a,new E(a))}
function Ta(a,b){if(!b&&C)throw Ua(a),"unwind";F()||C||(Va(),R(Ha),Wa(0),Xa[1].length&&Ya(1,10),Xa[2].length&&Ya(2,10),P.oc());Sa(a)}
var P={Yb:[],ac:[],qc:[],Vb:{},fc:function(){C&&P.Ec()},Pc:function(){},Ec:function(){P.receiveObjectTransfer=P.Gc;P.threadInitTLS=P.pc;P.setExitStatus=P.nc;noExitRuntime=!1},nc:function(){},oc:function(){for(var a of Object.values(P.Vb))P.mc(a);for(a of P.Yb)a.terminate();P.Yb=[]},mc:function(a){var b=a.Ub;delete P.Vb[b];P.Yb.push(a);P.ac.splice(P.ac.indexOf(a),1);a.Ub=0;Za(b)},Gc:function(){},pc:function(){P.qc.forEach(a=>a())},Fc:function(a,b){a.onmessage=c=>{c=c.data;var e=c.cmd;a.Ub&&(P.Bc=a.Ub);
if(c.targetThread&&c.targetThread!=$a()){var f=P.Vb[c.Qc];f?f.postMessage(c,c.transferList):G('Internal error! Worker sent a message "'+e+'" to target pthread '+c.targetThread+", but that thread no longer exists!")}else if("processProxyingQueue"===e)ab(c.queue);else if("spawnThread"===e)Ra(c);else if("cleanupThread"===e)Qa(c.thread);else if("killThread"===e)c=c.thread,e=P.Vb[c],delete P.Vb[c],e.terminate(),Za(c),P.ac.splice(P.ac.indexOf(e),1),e.Ub=0;else if("cancelThread"===e)P.Vb[c.thread].postMessage({cmd:"cancel"});
else if("loaded"===e)a.loaded=!0,b&&b(a),a.$b&&(a.$b(),delete a.$b);else if("print"===e)va("Thread "+c.threadId+": "+c.text);else if("printErr"===e)G("Thread "+c.threadId+": "+c.text);else if("alert"===e)alert("Thread "+c.threadId+": "+c.text);else if("setimmediate"===c.target)a.postMessage(c);else if("onAbort"===e){if(x.onAbort)x.onAbort(c.arg)}else e&&G("worker sent an unknown command "+e);P.Bc=void 0};a.onerror=c=>{G("worker sent an error! "+c.filename+":"+c.lineno+": "+c.message);throw c;};B&&
(a.on("message",function(c){a.onmessage({data:c})}),a.on("error",function(c){a.onerror(c)}),a.on("detachedExit",function(){}));a.postMessage({cmd:"load",urlOrBlob:x.mainScriptUrlOrBlob||_scriptDir,wasmMemory:m,wasmModule:wa})},yc:function(){var a=na("ort-wasm-threaded.worker.js");P.Yb.push(new Worker(a))},Cc:function(){0==P.Yb.length&&(P.yc(),P.Fc(P.Yb[0]));return P.Yb.pop()}};x.PThread=P;function R(a){for(;0<a.length;)a.shift()(x)}function bb(a){var b=S();a=a();U(b);return a}
x.establishStackSpace=function(){var a=$a(),b=r()[a+44>>2>>>0];a=r()[a+48>>2>>>0];cb(b,b-a);U(b)};function Ua(a){if(C)return Q(2,0,a);try{Ta(a)}catch(b){b instanceof E||"unwind"==b||la(1,b)}}var db=[];function V(a){var b=db[a];b||(a>=db.length&&(db.length=a+1),db[a]=b=Ea.get(a));return b}x.invokeEntryPoint=function(a,b){a=V(a)(b);F()?P.nc(a):eb(a)};function fb(a,b){d().set(a,b>>>0)}var gb=[],hb=0,W=0;
function X(a){this.Zb=a;this.Sb=a-24;this.xc=function(b){v()[this.Sb+4>>2>>>0]=b};this.bc=function(){return v()[this.Sb+4>>2>>>0]};this.wc=function(b){v()[this.Sb+8>>2>>>0]=b};this.Dc=function(){return v()[this.Sb+8>>2>>>0]};this.rc=function(){r()[this.Sb>>2>>>0]=0};this.hc=function(b){b=b?1:0;d()[this.Sb+12>>0>>>0]=b};this.uc=function(){return 0!=d()[this.Sb+12>>0>>>0]};this.ic=function(b){b=b?1:0;d()[this.Sb+13>>0>>>0]=b};this.kc=function(){return 0!=d()[this.Sb+13>>0>>>0]};this.fc=function(b,c){this.cc(0);
this.xc(b);this.wc(c);this.rc();this.hc(!1);this.ic(!1)};this.sc=function(){Atomics.add(r(),this.Sb>>2,1)};this.Hc=function(){return 1===Atomics.sub(r(),this.Sb>>2,1)};this.cc=function(b){v()[this.Sb+16>>2>>>0]=b};this.tc=function(){return v()[this.Sb+16>>2>>>0]};this.vc=function(){if(ib(this.bc()))return v()[this.Zb>>2>>>0];var b=this.tc();return 0!==b?b:this.Zb}}function jb(a){return kb((new X(a)).Sb)}function lb(a,b,c,e){return C?Q(3,1,a,b,c,e):mb(a,b,c,e)}
function mb(a,b,c,e){if("undefined"==typeof SharedArrayBuffer)return G("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var f=[];if(C&&0===f.length)return lb(a,b,c,e);a={Ic:c,Ub:a,zc:e,Nc:f};return C?(a.Oc="spawnThread",postMessage(a,f),0):Ra(a)}function nb(a,b,c){return C?Q(4,1,a,b,c):0}function ob(a,b){if(C)return Q(5,1,a,b)}function pb(a,b){if(C)return Q(6,1,a,b)}function qb(a,b,c){if(C)return Q(7,1,a,b,c)}function rb(a,b,c){return C?Q(8,1,a,b,c):0}
function sb(a,b){if(C)return Q(9,1,a,b)}function tb(a,b,c){if(C)return Q(10,1,a,b,c)}function ub(a,b,c,e){if(C)return Q(11,1,a,b,c,e)}function vb(a,b,c,e){if(C)return Q(12,1,a,b,c,e)}function wb(a,b,c,e){if(C)return Q(13,1,a,b,c,e)}function xb(a){if(C)return Q(14,1,a)}function yb(a,b){if(C)return Q(15,1,a,b)}function zb(a,b,c){if(C)return Q(16,1,a,b,c)}function ab(a){Atomics.store(r(),a>>2,1);$a()&&Ab(a);Atomics.compareExchange(r(),a>>2,1,0)}x.executeNotifiedProxyingQueue=ab;
function Bb(a){return v()[a>>>2]+4294967296*r()[a+4>>>2]}function Cb(a,b,c,e,f,h){return C?Q(17,1,a,b,c,e,f,h):-52}function Db(a,b,c,e,f,h){if(C)return Q(18,1,a,b,c,e,f,h)}function Eb(a){var b=Ca(a)+1,c=Fb(b);c&&Ba(a,d(),c,b);return c}
function Gb(a,b,c){function e(t){return(t=t.toTimeString().match(/\(([A-Za-z ]+)\)$/))?t[1]:"GMT"}if(C)return Q(19,1,a,b,c);var f=(new Date).getFullYear(),h=new Date(f,0,1),k=new Date(f,6,1);f=h.getTimezoneOffset();var l=k.getTimezoneOffset(),u=Math.max(f,l);r()[a>>2>>>0]=60*u;r()[b>>2>>>0]=Number(f!=l);a=e(h);b=e(k);a=Eb(a);b=Eb(b);l<f?(v()[c>>2>>>0]=a,v()[c+4>>2>>>0]=b):(v()[c>>2>>>0]=b,v()[c+4>>2>>>0]=a)}function Hb(a,b,c){Hb.Ac||(Hb.Ac=!0,Gb(a,b,c))}var Ib,Jb;
Jb=B?()=>{var a=process.hrtime();return 1E3*a[0]+a[1]/1E6}:C?()=>performance.now()-x.__performance_now_clock_drift:()=>performance.now();function Q(a,b){var c=arguments.length-2,e=arguments;return bb(()=>{for(var f=Kb(8*c),h=f>>3,k=0;k<c;k++){var l=e[2+k];ea()[h+k>>>0]=l}return Lb(a,c,f,b)})}var Mb=[],Nb={};
function Ob(){if(!Pb){var a={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:ka||"./this.program"},b;for(b in Nb)void 0===Nb[b]?delete a[b]:a[b]=Nb[b];var c=[];for(b in a)c.push(b+"="+a[b]);Pb=c}return Pb}var Pb;
function Qb(a,b){if(C)return Q(20,1,a,b);var c=0;Ob().forEach(function(e,f){var h=b+c;f=v()[a+4*f>>2>>>0]=h;for(h=0;h<e.length;++h)d()[f++>>0>>>0]=e.charCodeAt(h);d()[f>>0>>>0]=0;c+=e.length+1});return 0}function Rb(a,b){if(C)return Q(21,1,a,b);var c=Ob();v()[a>>2>>>0]=c.length;var e=0;c.forEach(function(f){e+=f.length+1});v()[b>>2>>>0]=e;return 0}function Sb(a){return C?Q(22,1,a):52}function Tb(a,b,c,e){return C?Q(23,1,a,b,c,e):52}function Ub(a,b,c,e,f){return C?Q(24,1,a,b,c,e,f):70}
var Xa=[null,[],[]];function Ya(a,b){var c=Xa[a];0===b||10===b?((1===a?va:G)(za(c,0)),c.length=0):c.push(b)}function Vb(a,b,c,e){if(C)return Q(25,1,a,b,c,e);for(var f=0,h=0;h<c;h++){var k=v()[b>>2>>>0],l=v()[b+4>>2>>>0];b+=8;for(var u=0;u<l;u++)Ya(a,q()[k+u>>>0]);f+=l}v()[e>>2>>>0]=f;return 0}var Y=0;
function Wb(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var a=new Uint8Array(1);return()=>{crypto.getRandomValues(a);return a[0]}}if(B)try{var b=__webpack_require__(Object(function webpackMissingModule() { var e = new Error("Cannot find module 'crypto'"); e.code = 'MODULE_NOT_FOUND'; throw e; }()));return()=>b.randomBytes(1)[0]}catch(c){}return()=>I("randomDevice")}function Xb(a,b){Xb.lc||(Xb.lc=Wb());for(var c=0;c<b;c++)d()[a+c>>0>>>0]=Xb.lc();return 0}function Yb(a){return 0===a%4&&(0!==a%100||0===a%400)}var Zb=[31,29,31,30,31,30,31,31,30,31,30,31],$b=[31,28,31,30,31,30,31,31,30,31,30,31];
function ac(a){var b=Array(Ca(a)+1);Ba(a,b,0,b.length);return b}
function bc(a,b,c,e){function f(g,w,z){for(g="number"==typeof g?g.toString():g||"";g.length<w;)g=z[0]+g;return g}function h(g,w){return f(g,w,"0")}function k(g,w){function z(T){return 0>T?-1:0<T?1:0}var N;0===(N=z(g.getFullYear()-w.getFullYear()))&&0===(N=z(g.getMonth()-w.getMonth()))&&(N=z(g.getDate()-w.getDate()));return N}function l(g){switch(g.getDay()){case 0:return new Date(g.getFullYear()-1,11,29);case 1:return g;case 2:return new Date(g.getFullYear(),0,3);case 3:return new Date(g.getFullYear(),
0,2);case 4:return new Date(g.getFullYear(),0,1);case 5:return new Date(g.getFullYear()-1,11,31);case 6:return new Date(g.getFullYear()-1,11,30)}}function u(g){var w=g.Wb;for(g=new Date((new Date(g.Xb+1900,0,1)).getTime());0<w;){var z=g.getMonth(),N=(Yb(g.getFullYear())?Zb:$b)[z];if(w>N-g.getDate())w-=N-g.getDate()+1,g.setDate(1),11>z?g.setMonth(z+1):(g.setMonth(0),g.setFullYear(g.getFullYear()+1));else{g.setDate(g.getDate()+w);break}}z=new Date(g.getFullYear()+1,0,4);w=l(new Date(g.getFullYear(),
0,4));z=l(z);return 0>=k(w,g)?0>=k(z,g)?g.getFullYear()+1:g.getFullYear():g.getFullYear()-1}var t=r()[e+40>>2>>>0];e={Lc:r()[e>>2>>>0],Kc:r()[e+4>>2>>>0],dc:r()[e+8>>2>>>0],jc:r()[e+12>>2>>>0],ec:r()[e+16>>2>>>0],Xb:r()[e+20>>2>>>0],Tb:r()[e+24>>2>>>0],Wb:r()[e+28>>2>>>0],Rc:r()[e+32>>2>>>0],Jc:r()[e+36>>2>>>0],Mc:t?Aa(t):""};c=Aa(c);t={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C",
"%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"};for(var A in t)c=c.replace(new RegExp(A,"g"),t[A]);var K="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),J="January February March April May June July August September October November December".split(" ");t={"%a":function(g){return K[g.Tb].substring(0,3)},"%A":function(g){return K[g.Tb]},
"%b":function(g){return J[g.ec].substring(0,3)},"%B":function(g){return J[g.ec]},"%C":function(g){return h((g.Xb+1900)/100|0,2)},"%d":function(g){return h(g.jc,2)},"%e":function(g){return f(g.jc,2," ")},"%g":function(g){return u(g).toString().substring(2)},"%G":function(g){return u(g)},"%H":function(g){return h(g.dc,2)},"%I":function(g){g=g.dc;0==g?g=12:12<g&&(g-=12);return h(g,2)},"%j":function(g){for(var w=0,z=0;z<=g.ec-1;w+=(Yb(g.Xb+1900)?Zb:$b)[z++]);return h(g.jc+w,3)},"%m":function(g){return h(g.ec+
1,2)},"%M":function(g){return h(g.Kc,2)},"%n":function(){return"\n"},"%p":function(g){return 0<=g.dc&&12>g.dc?"AM":"PM"},"%S":function(g){return h(g.Lc,2)},"%t":function(){return"\t"},"%u":function(g){return g.Tb||7},"%U":function(g){return h(Math.floor((g.Wb+7-g.Tb)/7),2)},"%V":function(g){var w=Math.floor((g.Wb+7-(g.Tb+6)%7)/7);2>=(g.Tb+371-g.Wb-2)%7&&w++;if(w)53==w&&(z=(g.Tb+371-g.Wb)%7,4==z||3==z&&Yb(g.Xb)||(w=1));else{w=52;var z=(g.Tb+7-g.Wb-1)%7;(4==z||5==z&&Yb(g.Xb%400-1))&&w++}return h(w,
2)},"%w":function(g){return g.Tb},"%W":function(g){return h(Math.floor((g.Wb+7-(g.Tb+6)%7)/7),2)},"%y":function(g){return(g.Xb+1900).toString().substring(2)},"%Y":function(g){return g.Xb+1900},"%z":function(g){g=g.Jc;var w=0<=g;g=Math.abs(g)/60;return(w?"+":"-")+String("0000"+(g/60*100+g%60)).slice(-4)},"%Z":function(g){return g.Mc},"%%":function(){return"%"}};c=c.replace(/%%/g,"\x00\x00");for(A in t)c.includes(A)&&(c=c.replace(new RegExp(A,"g"),t[A](e)));c=c.replace(/\0\0/g,"%");A=ac(c);if(A.length>
b)return 0;fb(A,a);return A.length-1}P.fc();
var cc=[null,Sa,Ua,lb,nb,ob,pb,qb,rb,sb,tb,ub,vb,wb,xb,yb,zb,Cb,Db,Gb,Qb,Rb,Sb,Tb,Ub,Vb],Pc={b:function(a){return Fb(a+24)+24},n:function(a){a=new X(a);a.uc()||(a.hc(!0),hb--);a.ic(!1);gb.push(a);a.sc();return a.vc()},ma:function(a){G("Unexpected exception thrown, this is not properly supported - aborting");xa=!0;throw a;},x:function(){Z(0);var a=gb.pop();if(a.Hc()&&!a.kc()){var b=a.Dc();b&&V(b)(a.Zb);jb(a.Zb)}W=0},e:function(){var a=W;if(!a)return Y=0;var b=new X(a);b.cc(a);var c=b.bc();if(!c)return Y=
0,a;for(var e=Array.prototype.slice.call(arguments),f=0;f<e.length;f++){var h=e[f];if(0===h||h===c)break;if(dc(h,c,b.Sb+16))return Y=h,a}Y=c;return a},l:function(){var a=W;if(!a)return Y=0;var b=new X(a);b.cc(a);var c=b.bc();if(!c)return Y=0,a;for(var e=Array.prototype.slice.call(arguments),f=0;f<e.length;f++){var h=e[f];if(0===h||h===c)break;if(dc(h,c,b.Sb+16))return Y=h,a}Y=c;return a},h:function(){var a=W;if(!a)return Y=0;var b=new X(a);b.cc(a);var c=b.bc();if(!c)return Y=0,a;for(var e=Array.prototype.slice.call(arguments),
f=0;f<e.length;f++){var h=e[f];if(0===h||h===c)break;if(dc(h,c,b.Sb+16))return Y=h,a}Y=c;return a},t:jb,M:function(){var a=gb.pop();a||I("no exception to throw");var b=a.Zb;a.kc()||(gb.push(a),a.ic(!0),a.hc(!1),hb++);W=b;throw b;},c:function(a,b,c){(new X(a)).fc(b,c);W=a;hb++;throw a;},pa:function(){return hb},Fa:function(a){ec(a,!y,1,!ma);P.pc()},T:function(a){C?postMessage({cmd:"cleanupThread",thread:a}):Qa(a)},xa:mb,j:function(a){W||(W=a);throw a;},H:nb,Ma:ob,ua:pb,wa:qb,oa:rb,Ka:sb,Ca:tb,Ja:ub,
V:vb,va:wb,sa:xb,La:yb,ta:zb,Ta:function(){},X:function(){I("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking")},Ua:function(){I("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking")},W:function(){return Date.now()},ya:function(){return 2097152},Oa:function(){return!0},za:function(a,b,c,e){if(a==b)setTimeout(()=>ab(e));else if(C)postMessage({targetThread:a,cmd:"processProxyingQueue",
queue:e});else{a=P.Vb[a];if(!a)return;a.postMessage({cmd:"processProxyingQueue",queue:e})}return 1},Ea:function(){return-1},Pa:function(a,b){a=new Date(1E3*Bb(a));r()[b>>2>>>0]=a.getUTCSeconds();r()[b+4>>2>>>0]=a.getUTCMinutes();r()[b+8>>2>>>0]=a.getUTCHours();r()[b+12>>2>>>0]=a.getUTCDate();r()[b+16>>2>>>0]=a.getUTCMonth();r()[b+20>>2>>>0]=a.getUTCFullYear()-1900;r()[b+24>>2>>>0]=a.getUTCDay();a=(a.getTime()-Date.UTC(a.getUTCFullYear(),0,1,0,0,0,0))/864E5|0;r()[b+28>>2>>>0]=a},Qa:function(a,b){a=
new Date(1E3*Bb(a));r()[b>>2>>>0]=a.getSeconds();r()[b+4>>2>>>0]=a.getMinutes();r()[b+8>>2>>>0]=a.getHours();r()[b+12>>2>>>0]=a.getDate();r()[b+16>>2>>>0]=a.getMonth();r()[b+20>>2>>>0]=a.getFullYear()-1900;r()[b+24>>2>>>0]=a.getDay();var c=new Date(a.getFullYear(),0,1),e=(a.getTime()-c.getTime())/864E5|0;r()[b+28>>2>>>0]=e;r()[b+36>>2>>>0]=-(60*a.getTimezoneOffset());e=(new Date(a.getFullYear(),6,1)).getTimezoneOffset();c=c.getTimezoneOffset();a=(e!=c&&a.getTimezoneOffset()==Math.min(c,e))|0;r()[b+
32>>2>>>0]=a},Ra:function(a){var b=new Date(r()[a+20>>2>>>0]+1900,r()[a+16>>2>>>0],r()[a+12>>2>>>0],r()[a+8>>2>>>0],r()[a+4>>2>>>0],r()[a>>2>>>0],0),c=r()[a+32>>2>>>0],e=b.getTimezoneOffset(),f=new Date(b.getFullYear(),0,1),h=(new Date(b.getFullYear(),6,1)).getTimezoneOffset(),k=f.getTimezoneOffset(),l=Math.min(k,h);0>c?r()[a+32>>2>>>0]=Number(h!=k&&l==e):0<c!=(l==e)&&(h=Math.max(k,h),b.setTime(b.getTime()+6E4*((0<c?l:h)-e)));r()[a+24>>2>>>0]=b.getDay();c=(b.getTime()-f.getTime())/864E5|0;r()[a+28>>
2>>>0]=c;r()[a>>2>>>0]=b.getSeconds();r()[a+4>>2>>>0]=b.getMinutes();r()[a+8>>2>>>0]=b.getHours();r()[a+12>>2>>>0]=b.getDate();r()[a+16>>2>>>0]=b.getMonth();return b.getTime()/1E3|0},Aa:Cb,Ba:Db,Sa:Hb,y:function(){I("")},U:function(){if(!B&&!y){var a="Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread";Ib||(Ib={});Ib[a]||(Ib[a]=1,B&&(a="warning: "+a),G(a))}},ra:function(){return 4294901760},B:Jb,Ia:function(a,b,
c){q().copyWithin(a>>>0,b>>>0,b+c>>>0)},F:function(){return B?(__webpack_require__(/*! os */ "?aedb").cpus)().length:navigator.hardwareConcurrency},Da:function(a,b,c){Mb.length=b;c>>=3;for(var e=0;e<b;e++)Mb[e]=ea()[c+e>>>0];return(0>a?Pa[-a-1]:cc[a]).apply(null,Mb)},qa:function(a){var b=q().length;a>>>=0;if(a<=b||4294901760<a)return!1;for(var c=1;4>=c;c*=2){var e=b*(1+.2/c);e=Math.min(e,a+100663296);var f=Math;e=Math.max(a,e);f=f.min.call(f,4294901760,e+(65536-e%65536)%65536);a:{try{m.grow(f-n.byteLength+65535>>>16);p(m.buffer);
var h=1;break a}catch(k){}h=void 0}if(h)return!0}return!1},Na:function(){throw"unwind";},Ga:Qb,Ha:Rb,J:Ta,I:Sb,S:Tb,ga:Ub,R:Vb,d:function(){return Y},na:Xb,ia:fc,ja:gc,K:hc,f:ic,P:jc,Q:kc,k:lc,p:mc,q:nc,N:oc,s:pc,w:qc,L:rc,E:sc,aa:tc,_:uc,Z:vc,ca:wc,$:xc,ba:yc,Y:zc,g:Ac,r:Bc,i:Cc,ha:Dc,m:Ec,v:Fc,u:Gc,O:Hc,A:Ic,ka:Jc,C:Kc,D:Lc,fa:Mc,da:Nc,ea:Oc,o:function(a){return a},a:m||x.wasmMemory,G:function(a){Y=a},la:bc,z:function(a,b,c,e){return bc(a,b,c,e)}};
(function(){function a(f,h){x.asm=f.exports;P.qc.push(x.asm.sb);Ea=x.asm.ub;Ga.unshift(x.asm.Va);wa=h;C||(L--,x.monitorRunDependencies&&x.monitorRunDependencies(L),0==L&&(null!==La&&(clearInterval(La),La=null),M&&(f=M,M=null,f())))}function b(f){a(f.instance,f.module)}function c(f){return Oa().then(function(h){return WebAssembly.instantiate(h,e)}).then(function(h){return h}).then(f,function(h){G("failed to asynchronously prepare wasm: "+h);I(h)})}var e={a:Pc};C||(L++,x.monitorRunDependencies&&x.monitorRunDependencies(L));
if(x.instantiateWasm)try{return x.instantiateWasm(e,a)}catch(f){return G("Module.instantiateWasm callback failed with error: "+f),!1}(function(){return H||"function"!=typeof WebAssembly.instantiateStreaming||Ma()||O.startsWith("file://")||B||"function"!=typeof fetch?c(b):fetch(O,{credentials:"same-origin"}).then(function(f){return WebAssembly.instantiateStreaming(f,e).then(b,function(h){G("wasm streaming compile failed: "+h);G("falling back to ArrayBuffer instantiation");return c(b)})})})().catch(ia);
return{}})();x.___wasm_call_ctors=function(){return(x.___wasm_call_ctors=x.asm.Va).apply(null,arguments)};x._OrtInit=function(){return(x._OrtInit=x.asm.Wa).apply(null,arguments)};x._OrtCreateSessionOptions=function(){return(x._OrtCreateSessionOptions=x.asm.Xa).apply(null,arguments)};x._OrtAppendExecutionProvider=function(){return(x._OrtAppendExecutionProvider=x.asm.Ya).apply(null,arguments)};x._OrtAddSessionConfigEntry=function(){return(x._OrtAddSessionConfigEntry=x.asm.Za).apply(null,arguments)};
x._OrtReleaseSessionOptions=function(){return(x._OrtReleaseSessionOptions=x.asm._a).apply(null,arguments)};x._OrtCreateSession=function(){return(x._OrtCreateSession=x.asm.$a).apply(null,arguments)};x._OrtReleaseSession=function(){return(x._OrtReleaseSession=x.asm.ab).apply(null,arguments)};x._OrtGetInputCount=function(){return(x._OrtGetInputCount=x.asm.bb).apply(null,arguments)};x._OrtGetOutputCount=function(){return(x._OrtGetOutputCount=x.asm.cb).apply(null,arguments)};
x._OrtGetInputName=function(){return(x._OrtGetInputName=x.asm.db).apply(null,arguments)};x._OrtGetOutputName=function(){return(x._OrtGetOutputName=x.asm.eb).apply(null,arguments)};x._OrtFree=function(){return(x._OrtFree=x.asm.fb).apply(null,arguments)};x._OrtCreateTensor=function(){return(x._OrtCreateTensor=x.asm.gb).apply(null,arguments)};x._OrtGetTensorData=function(){return(x._OrtGetTensorData=x.asm.hb).apply(null,arguments)};
x._OrtReleaseTensor=function(){return(x._OrtReleaseTensor=x.asm.ib).apply(null,arguments)};x._OrtCreateRunOptions=function(){return(x._OrtCreateRunOptions=x.asm.jb).apply(null,arguments)};x._OrtAddRunConfigEntry=function(){return(x._OrtAddRunConfigEntry=x.asm.kb).apply(null,arguments)};x._OrtReleaseRunOptions=function(){return(x._OrtReleaseRunOptions=x.asm.lb).apply(null,arguments)};x._OrtRun=function(){return(x._OrtRun=x.asm.mb).apply(null,arguments)};
x._OrtEndProfiling=function(){return(x._OrtEndProfiling=x.asm.nb).apply(null,arguments)};var $a=x._pthread_self=function(){return($a=x._pthread_self=x.asm.ob).apply(null,arguments)},Fb=x._malloc=function(){return(Fb=x._malloc=x.asm.pb).apply(null,arguments)},kb=x._free=function(){return(kb=x._free=x.asm.qb).apply(null,arguments)},Wa=x._fflush=function(){return(Wa=x._fflush=x.asm.rb).apply(null,arguments)};x.__emscripten_tls_init=function(){return(x.__emscripten_tls_init=x.asm.sb).apply(null,arguments)};
var Va=x.___funcs_on_exit=function(){return(Va=x.___funcs_on_exit=x.asm.tb).apply(null,arguments)},ec=x.__emscripten_thread_init=function(){return(ec=x.__emscripten_thread_init=x.asm.vb).apply(null,arguments)};x.__emscripten_thread_crashed=function(){return(x.__emscripten_thread_crashed=x.asm.wb).apply(null,arguments)};
var Lb=x._emscripten_run_in_main_runtime_thread_js=function(){return(Lb=x._emscripten_run_in_main_runtime_thread_js=x.asm.xb).apply(null,arguments)},Ab=x.__emscripten_proxy_execute_task_queue=function(){return(Ab=x.__emscripten_proxy_execute_task_queue=x.asm.yb).apply(null,arguments)},Za=x.__emscripten_thread_free_data=function(){return(Za=x.__emscripten_thread_free_data=x.asm.zb).apply(null,arguments)},eb=x.__emscripten_thread_exit=function(){return(eb=x.__emscripten_thread_exit=x.asm.Ab).apply(null,
arguments)},Z=x._setThrew=function(){return(Z=x._setThrew=x.asm.Bb).apply(null,arguments)},cb=x._emscripten_stack_set_limits=function(){return(cb=x._emscripten_stack_set_limits=x.asm.Cb).apply(null,arguments)},S=x.stackSave=function(){return(S=x.stackSave=x.asm.Db).apply(null,arguments)},U=x.stackRestore=function(){return(U=x.stackRestore=x.asm.Eb).apply(null,arguments)},Kb=x.stackAlloc=function(){return(Kb=x.stackAlloc=x.asm.Fb).apply(null,arguments)},dc=x.___cxa_can_catch=function(){return(dc=x.___cxa_can_catch=
x.asm.Gb).apply(null,arguments)},ib=x.___cxa_is_pointer_type=function(){return(ib=x.___cxa_is_pointer_type=x.asm.Hb).apply(null,arguments)},Qc=x.dynCall_j=function(){return(Qc=x.dynCall_j=x.asm.Ib).apply(null,arguments)},Rc=x.dynCall_iiiiij=function(){return(Rc=x.dynCall_iiiiij=x.asm.Jb).apply(null,arguments)},Sc=x.dynCall_jii=function(){return(Sc=x.dynCall_jii=x.asm.Kb).apply(null,arguments)},Tc=x.dynCall_viiiiij=function(){return(Tc=x.dynCall_viiiiij=x.asm.Lb).apply(null,arguments)},Uc=x.dynCall_vjji=
function(){return(Uc=x.dynCall_vjji=x.asm.Mb).apply(null,arguments)},Vc=x.dynCall_viiijjjii=function(){return(Vc=x.dynCall_viiijjjii=x.asm.Nb).apply(null,arguments)},Wc=x.dynCall_iij=function(){return(Wc=x.dynCall_iij=x.asm.Ob).apply(null,arguments)},Xc=x.dynCall_ji=function(){return(Xc=x.dynCall_ji=x.asm.Pb).apply(null,arguments)},Yc=x.dynCall_iiiiiij=function(){return(Yc=x.dynCall_iiiiiij=x.asm.Qb).apply(null,arguments)},Zc=x.dynCall_iiij=function(){return(Zc=x.dynCall_iiij=x.asm.Rb).apply(null,
arguments)};function ic(a,b){var c=S();try{return V(a)(b)}catch(e){U(c);if(e!==e+0)throw e;Z(1,0)}}function Bc(a,b){var c=S();try{V(a)(b)}catch(e){U(c);if(e!==e+0)throw e;Z(1,0)}}function Cc(a,b,c){var e=S();try{V(a)(b,c)}catch(f){U(e);if(f!==f+0)throw f;Z(1,0)}}function lc(a,b,c){var e=S();try{return V(a)(b,c)}catch(f){U(e);if(f!==f+0)throw f;Z(1,0)}}function mc(a,b,c,e){var f=S();try{return V(a)(b,c,e)}catch(h){U(f);if(h!==h+0)throw h;Z(1,0)}}
function qc(a,b,c,e,f,h,k){var l=S();try{return V(a)(b,c,e,f,h,k)}catch(u){U(l);if(u!==u+0)throw u;Z(1,0)}}function Ac(a){var b=S();try{V(a)()}catch(c){U(b);if(c!==c+0)throw c;Z(1,0)}}function pc(a,b,c,e,f,h){var k=S();try{return V(a)(b,c,e,f,h)}catch(l){U(k);if(l!==l+0)throw l;Z(1,0)}}function nc(a,b,c,e,f){var h=S();try{return V(a)(b,c,e,f)}catch(k){U(h);if(k!==k+0)throw k;Z(1,0)}}function Ec(a,b,c,e){var f=S();try{V(a)(b,c,e)}catch(h){U(f);if(h!==h+0)throw h;Z(1,0)}}
function Gc(a,b,c,e,f,h){var k=S();try{V(a)(b,c,e,f,h)}catch(l){U(k);if(l!==l+0)throw l;Z(1,0)}}function Fc(a,b,c,e,f){var h=S();try{V(a)(b,c,e,f)}catch(k){U(h);if(k!==k+0)throw k;Z(1,0)}}function Ic(a,b,c,e,f,h,k,l){var u=S();try{V(a)(b,c,e,f,h,k,l)}catch(t){U(u);if(t!==t+0)throw t;Z(1,0)}}function kc(a,b,c){var e=S();try{return V(a)(b,c)}catch(f){U(e);if(f!==f+0)throw f;Z(1,0)}}function jc(a,b,c){var e=S();try{return V(a)(b,c)}catch(f){U(e);if(f!==f+0)throw f;Z(1,0)}}
function Jc(a,b,c,e,f,h,k,l,u){var t=S();try{V(a)(b,c,e,f,h,k,l,u)}catch(A){U(t);if(A!==A+0)throw A;Z(1,0)}}function Hc(a,b,c,e,f,h,k){var l=S();try{V(a)(b,c,e,f,h,k)}catch(u){U(l);if(u!==u+0)throw u;Z(1,0)}}function oc(a,b,c,e,f,h){var k=S();try{return V(a)(b,c,e,f,h)}catch(l){U(k);if(l!==l+0)throw l;Z(1,0)}}function rc(a,b,c,e,f,h,k,l){var u=S();try{return V(a)(b,c,e,f,h,k,l)}catch(t){U(u);if(t!==t+0)throw t;Z(1,0)}}
function sc(a,b,c,e,f,h,k,l,u,t,A,K){var J=S();try{return V(a)(b,c,e,f,h,k,l,u,t,A,K)}catch(g){U(J);if(g!==g+0)throw g;Z(1,0)}}function Kc(a,b,c,e,f,h,k,l,u,t,A){var K=S();try{V(a)(b,c,e,f,h,k,l,u,t,A)}catch(J){U(K);if(J!==J+0)throw J;Z(1,0)}}function Lc(a,b,c,e,f,h,k,l,u,t,A,K,J,g,w,z){var N=S();try{V(a)(b,c,e,f,h,k,l,u,t,A,K,J,g,w,z)}catch(T){U(N);if(T!==T+0)throw T;Z(1,0)}}function hc(a){var b=S();try{return V(a)()}catch(c){U(b);if(c!==c+0)throw c;Z(1,0)}}
function gc(a,b,c){var e=S();try{return V(a)(b,c)}catch(f){U(e);if(f!==f+0)throw f;Z(1,0)}}function fc(a,b,c){var e=S();try{return V(a)(b,c)}catch(f){U(e);if(f!==f+0)throw f;Z(1,0)}}function Dc(a,b,c,e){var f=S();try{V(a)(b,c,e)}catch(h){U(f);if(h!==h+0)throw h;Z(1,0)}}function Mc(a,b,c,e,f,h,k,l){var u=S();try{Tc(a,b,c,e,f,h,k,l)}catch(t){U(u);if(t!==t+0)throw t;Z(1,0)}}function Oc(a,b,c,e,f,h){var k=S();try{Uc(a,b,c,e,f,h)}catch(l){U(k);if(l!==l+0)throw l;Z(1,0)}}
function Nc(a,b,c,e,f,h,k,l,u,t,A,K){var J=S();try{Vc(a,b,c,e,f,h,k,l,u,t,A,K)}catch(g){U(J);if(g!==g+0)throw g;Z(1,0)}}function wc(a,b,c,e){var f=S();try{return Wc(a,b,c,e)}catch(h){U(f);if(h!==h+0)throw h;Z(1,0)}}function yc(a,b){var c=S();try{return Xc(a,b)}catch(e){U(c);if(e!==e+0)throw e;Z(1,0)}}function tc(a,b,c,e,f,h,k,l){var u=S();try{return Yc(a,b,c,e,f,h,k,l)}catch(t){U(u);if(t!==t+0)throw t;Z(1,0)}}function xc(a){var b=S();try{return Qc(a)}catch(c){U(b);if(c!==c+0)throw c;Z(1,0)}}
function uc(a,b,c,e,f,h,k){var l=S();try{return Rc(a,b,c,e,f,h,k)}catch(u){U(l);if(u!==u+0)throw u;Z(1,0)}}function vc(a,b,c,e,f){var h=S();try{return Zc(a,b,c,e,f)}catch(k){U(h);if(k!==k+0)throw k;Z(1,0)}}function zc(a,b,c){var e=S();try{return Sc(a,b,c)}catch(f){U(e);if(f!==f+0)throw f;Z(1,0)}}x.UTF8ToString=Aa;x.stringToUTF8=function(a,b,c){return Ba(a,q(),b,c)};x.lengthBytesUTF8=Ca;x.keepRuntimeAlive=F;x.wasmMemory=m;x.stackSave=S;x.stackRestore=U;x.stackAlloc=Kb;x.ExitStatus=E;x.PThread=P;var $c;
M=function ad(){$c||bd();$c||(M=ad)};
function bd(){function a(){if(!$c&&($c=!0,x.calledRun=!0,!xa)){C||R(Ga);ha(x);if(x.onRuntimeInitialized)x.onRuntimeInitialized();if(!C){if(x.postRun)for("function"==typeof x.postRun&&(x.postRun=[x.postRun]);x.postRun.length;){var b=x.postRun.shift();Ia.unshift(b)}R(Ia)}}}if(!(0<L))if(C)ha(x),C||R(Ga),postMessage({cmd:"loaded"});else{if(x.preRun)for("function"==typeof x.preRun&&(x.preRun=[x.preRun]);x.preRun.length;)Ka();R(Fa);0<L||(x.setStatus?(x.setStatus("Running..."),setTimeout(function(){setTimeout(function(){x.setStatus("")},
1);a()},1)):a())}}if(x.preInit)for("function"==typeof x.preInit&&(x.preInit=[x.preInit]);0<x.preInit.length;)x.preInit.pop()();bd();


  return ortWasmThreaded.ready
}
);
})();
if (true)
  module.exports = ortWasmThreaded;
else {}


/***/ }),

/***/ "./lib/wasm/binding/ort-wasm.js":
/*!**************************************!*\
  !*** ./lib/wasm/binding/ort-wasm.js ***!
  \**************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var __filename = "/index.js";
var __dirname = "/";

var ortWasm = (() => {
  var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined;
  if (true) _scriptDir = _scriptDir || __filename;
  return (
function(ortWasm) {
  ortWasm = ortWasm || {};


var d;d||(d=typeof ortWasm !== 'undefined' ? ortWasm : {});var aa,ba;d.ready=new Promise(function(a,b){aa=a;ba=b});var ca=Object.assign({},d),da="./this.program",ea=(a,b)=>{throw b;},fa="object"==typeof window,m="function"==typeof importScripts,p="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,q="",ha,r,v,fs,y,ia;
if(p)q=m?(__webpack_require__(/*! path */ "?75c6").dirname)(q)+"/":__dirname+"/",ia=()=>{y||(fs=__webpack_require__(/*! fs */ "?63c8"),y=__webpack_require__(/*! path */ "?75c6"))},ha=function(a,b){ia();a=y.normalize(a);return fs.readFileSync(a,b?void 0:"utf8")},v=a=>{a=ha(a,!0);a.buffer||(a=new Uint8Array(a));return a},r=(a,b,c)=>{ia();a=y.normalize(a);fs.readFile(a,function(e,f){e?c(e):b(f.buffer)})},1<process.argv.length&&(da=process.argv[1].replace(/\\/g,"/")),process.argv.slice(2),process.on("uncaughtException",function(a){if(!(a instanceof ja))throw a;}),process.on("unhandledRejection",
function(a){throw a;}),ea=(a,b)=>{if(noExitRuntime||0<ka)throw process.exitCode=a,b;b instanceof ja||z("exiting due to exception: "+b);process.exit(a)},d.inspect=function(){return"[Emscripten Module object]"};else if(fa||m)m?q=self.location.href:"undefined"!=typeof document&&document.currentScript&&(q=document.currentScript.src),_scriptDir&&(q=_scriptDir),0!==q.indexOf("blob:")?q=q.substr(0,q.replace(/[?#].*/,"").lastIndexOf("/")+1):q="",ha=a=>{var b=new XMLHttpRequest;b.open("GET",a,!1);b.send(null);
return b.responseText},m&&(v=a=>{var b=new XMLHttpRequest;b.open("GET",a,!1);b.responseType="arraybuffer";b.send(null);return new Uint8Array(b.response)}),r=(a,b,c)=>{var e=new XMLHttpRequest;e.open("GET",a,!0);e.responseType="arraybuffer";e.onload=()=>{200==e.status||0==e.status&&e.response?b(e.response):c()};e.onerror=c;e.send(null)};var la=d.print||console.log.bind(console),z=d.printErr||console.warn.bind(console);Object.assign(d,ca);ca=null;d.thisProgram&&(da=d.thisProgram);d.quit&&(ea=d.quit);
var A;d.wasmBinary&&(A=d.wasmBinary);var noExitRuntime=d.noExitRuntime||!1;"object"!=typeof WebAssembly&&B("no native wasm support detected");var ma,D=!1,na="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;
function oa(a,b,c){b>>>=0;var e=b+c;for(c=b;a[c]&&!(c>=e);)++c;if(16<c-b&&a.buffer&&na)return na.decode(a.subarray(b,c));for(e="";b<c;){var f=a[b++];if(f&128){var h=a[b++]&63;if(192==(f&224))e+=String.fromCharCode((f&31)<<6|h);else{var k=a[b++]&63;f=224==(f&240)?(f&15)<<12|h<<6|k:(f&7)<<18|h<<12|k<<6|a[b++]&63;65536>f?e+=String.fromCharCode(f):(f-=65536,e+=String.fromCharCode(55296|f>>10,56320|f&1023))}}else e+=String.fromCharCode(f)}return e}function pa(a,b){return(a>>>=0)?oa(G,a,b):""}
function qa(a,b,c,e){c>>>=0;if(!(0<e))return 0;var f=c;e=c+e-1;for(var h=0;h<a.length;++h){var k=a.charCodeAt(h);if(55296<=k&&57343>=k){var l=a.charCodeAt(++h);k=65536+((k&1023)<<10)|l&1023}if(127>=k){if(c>=e)break;b[c++>>>0]=k}else{if(2047>=k){if(c+1>=e)break;b[c++>>>0]=192|k>>6}else{if(65535>=k){if(c+2>=e)break;b[c++>>>0]=224|k>>12}else{if(c+3>=e)break;b[c++>>>0]=240|k>>18;b[c++>>>0]=128|k>>12&63}b[c++>>>0]=128|k>>6&63}b[c++>>>0]=128|k&63}}b[c>>>0]=0;return c-f}
function ra(a){for(var b=0,c=0;c<a.length;++c){var e=a.charCodeAt(c);127>=e?b++:2047>=e?b+=2:55296<=e&&57343>=e?(b+=4,++c):b+=3}return b}var sa,H,G,I,J;function ta(){var a=ma.buffer;sa=a;d.HEAP8=H=new Int8Array(a);d.HEAP16=new Int16Array(a);d.HEAP32=I=new Int32Array(a);d.HEAPU8=G=new Uint8Array(a);d.HEAPU16=new Uint16Array(a);d.HEAPU32=J=new Uint32Array(a);d.HEAPF32=new Float32Array(a);d.HEAPF64=new Float64Array(a)}var ua,va=[],wa=[],xa=[],ya=[],ka=0;
function za(){var a=d.preRun.shift();va.unshift(a)}var K=0,Aa=null,L=null;function B(a){if(d.onAbort)d.onAbort(a);a="Aborted("+a+")";z(a);D=!0;a=new WebAssembly.RuntimeError(a+". Build with -sASSERTIONS for more info.");ba(a);throw a;}function Ba(){return N.startsWith("data:application/octet-stream;base64,")}var N;N="ort-wasm.wasm";if(!Ba()){var Ca=N;N=d.locateFile?d.locateFile(Ca,q):q+Ca}
function Da(){var a=N;try{if(a==N&&A)return new Uint8Array(A);if(v)return v(a);throw"both async and sync fetching of the wasm failed";}catch(b){B(b)}}
function Ea(){if(!A&&(fa||m)){if("function"==typeof fetch&&!N.startsWith("file://"))return fetch(N,{credentials:"same-origin"}).then(function(a){if(!a.ok)throw"failed to load wasm binary file at '"+N+"'";return a.arrayBuffer()}).catch(function(){return Da()});if(r)return new Promise(function(a,b){r(N,function(c){a(new Uint8Array(c))},b)})}return Promise.resolve().then(function(){return Da()})}function ja(a){this.name="ExitStatus";this.message="Program terminated with exit("+a+")";this.status=a}
function O(a){for(;0<a.length;)a.shift()(d)}var P=[],Q=0,R=0;
function S(a){this.Db=a;this.zb=a-24;this.Ub=function(b){J[this.zb+4>>2>>>0]=b};this.Eb=function(){return J[this.zb+4>>2>>>0]};this.Sb=function(b){J[this.zb+8>>2>>>0]=b};this.Wb=function(){return J[this.zb+8>>2>>>0]};this.Tb=function(){I[this.zb>>2>>>0]=0};this.Ib=function(b){H[this.zb+12>>0>>>0]=b?1:0};this.Pb=function(){return 0!=H[this.zb+12>>0>>>0]};this.Jb=function(b){H[this.zb+13>>0>>>0]=b?1:0};this.Lb=function(){return 0!=H[this.zb+13>>0>>>0]};this.Rb=function(b,c){this.Fb(0);this.Ub(b);this.Sb(c);
this.Tb();this.Ib(!1);this.Jb(!1)};this.Nb=function(){I[this.zb>>2>>>0]+=1};this.Xb=function(){var b=I[this.zb>>2>>>0];I[this.zb>>2>>>0]=b-1;return 1===b};this.Fb=function(b){J[this.zb+16>>2>>>0]=b};this.Ob=function(){return J[this.zb+16>>2>>>0]};this.Qb=function(){if(Fa(this.Eb()))return J[this.Db>>2>>>0];var b=this.Ob();return 0!==b?b:this.Db}}function Ga(a){return Ha((new S(a)).zb)}var T=[];function U(a){var b=T[a];b||(a>=T.length&&(T.length=a+1),T[a]=b=ua.get(a));return b}
function Ia(a){var b=ra(a)+1,c=Ja(b);c&&qa(a,H,c,b);return c}function Ka(a,b,c){function e(n){return(n=n.toTimeString().match(/\(([A-Za-z ]+)\)$/))?n[1]:"GMT"}var f=(new Date).getFullYear(),h=new Date(f,0,1),k=new Date(f,6,1);f=h.getTimezoneOffset();var l=k.getTimezoneOffset();I[a>>2>>>0]=60*Math.max(f,l);I[b>>2>>>0]=Number(f!=l);a=e(h);b=e(k);a=Ia(a);b=Ia(b);l<f?(J[c>>2>>>0]=a,J[c+4>>2>>>0]=b):(J[c>>2>>>0]=b,J[c+4>>2>>>0]=a)}function La(a,b,c){La.Vb||(La.Vb=!0,Ka(a,b,c))}var Ma={};
function Na(){if(!Oa){var a={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:da||"./this.program"},b;for(b in Ma)void 0===Ma[b]?delete a[b]:a[b]=Ma[b];var c=[];for(b in a)c.push(b+"="+a[b]);Oa=c}return Oa}var Oa,Pa=[null,[],[]];function Qa(a,b){var c=Pa[a];0===b||10===b?((1===a?la:z)(oa(c,0)),c.length=0):c.push(b)}var V=0;
function Ra(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var a=new Uint8Array(1);return()=>{crypto.getRandomValues(a);return a[0]}}if(p)try{var b=__webpack_require__(Object(function webpackMissingModule() { var e = new Error("Cannot find module 'crypto'"); e.code = 'MODULE_NOT_FOUND'; throw e; }()));return()=>b.randomBytes(1)[0]}catch(c){}return()=>B("randomDevice")}function W(a,b){W.Mb||(W.Mb=Ra());for(var c=0;c<b;c++)H[a+c>>0>>>0]=W.Mb();return 0}function Sa(a){return 0===a%4&&(0!==a%100||0===a%400)}var Ta=[31,29,31,30,31,30,31,31,30,31,30,31],Ua=[31,28,31,30,31,30,31,31,30,31,30,31];
function Va(a){var b=Array(ra(a)+1);qa(a,b,0,b.length);return b}
function Wa(a,b,c,e){function f(g,u,w){for(g="number"==typeof g?g.toString():g||"";g.length<u;)g=w[0]+g;return g}function h(g,u){return f(g,u,"0")}function k(g,u){function w(M){return 0>M?-1:0<M?1:0}var F;0===(F=w(g.getFullYear()-u.getFullYear()))&&0===(F=w(g.getMonth()-u.getMonth()))&&(F=w(g.getDate()-u.getDate()));return F}function l(g){switch(g.getDay()){case 0:return new Date(g.getFullYear()-1,11,29);case 1:return g;case 2:return new Date(g.getFullYear(),0,3);case 3:return new Date(g.getFullYear(),
0,2);case 4:return new Date(g.getFullYear(),0,1);case 5:return new Date(g.getFullYear()-1,11,31);case 6:return new Date(g.getFullYear()-1,11,30)}}function n(g){var u=g.Bb;for(g=new Date((new Date(g.Cb+1900,0,1)).getTime());0<u;){var w=g.getMonth(),F=(Sa(g.getFullYear())?Ta:Ua)[w];if(u>F-g.getDate())u-=F-g.getDate()+1,g.setDate(1),11>w?g.setMonth(w+1):(g.setMonth(0),g.setFullYear(g.getFullYear()+1));else{g.setDate(g.getDate()+u);break}}w=new Date(g.getFullYear()+1,0,4);u=l(new Date(g.getFullYear(),
0,4));w=l(w);return 0>=k(u,g)?0>=k(w,g)?g.getFullYear()+1:g.getFullYear():g.getFullYear()-1}var t=I[e+40>>2>>>0];e={$b:I[e>>2>>>0],Zb:I[e+4>>2>>>0],Gb:I[e+8>>2>>>0],Kb:I[e+12>>2>>>0],Hb:I[e+16>>2>>>0],Cb:I[e+20>>2>>>0],Ab:I[e+24>>2>>>0],Bb:I[e+28>>2>>>0],bc:I[e+32>>2>>>0],Yb:I[e+36>>2>>>0],ac:t?pa(t):""};c=pa(c);t={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y",
"%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"};for(var x in t)c=c.replace(new RegExp(x,"g"),t[x]);var E="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),C="January February March April May June July August September October November December".split(" ");t={"%a":function(g){return E[g.Ab].substring(0,3)},"%A":function(g){return E[g.Ab]},"%b":function(g){return C[g.Hb].substring(0,
3)},"%B":function(g){return C[g.Hb]},"%C":function(g){return h((g.Cb+1900)/100|0,2)},"%d":function(g){return h(g.Kb,2)},"%e":function(g){return f(g.Kb,2," ")},"%g":function(g){return n(g).toString().substring(2)},"%G":function(g){return n(g)},"%H":function(g){return h(g.Gb,2)},"%I":function(g){g=g.Gb;0==g?g=12:12<g&&(g-=12);return h(g,2)},"%j":function(g){for(var u=0,w=0;w<=g.Hb-1;u+=(Sa(g.Cb+1900)?Ta:Ua)[w++]);return h(g.Kb+u,3)},"%m":function(g){return h(g.Hb+1,2)},"%M":function(g){return h(g.Zb,
2)},"%n":function(){return"\n"},"%p":function(g){return 0<=g.Gb&&12>g.Gb?"AM":"PM"},"%S":function(g){return h(g.$b,2)},"%t":function(){return"\t"},"%u":function(g){return g.Ab||7},"%U":function(g){return h(Math.floor((g.Bb+7-g.Ab)/7),2)},"%V":function(g){var u=Math.floor((g.Bb+7-(g.Ab+6)%7)/7);2>=(g.Ab+371-g.Bb-2)%7&&u++;if(u)53==u&&(w=(g.Ab+371-g.Bb)%7,4==w||3==w&&Sa(g.Cb)||(u=1));else{u=52;var w=(g.Ab+7-g.Bb-1)%7;(4==w||5==w&&Sa(g.Cb%400-1))&&u++}return h(u,2)},"%w":function(g){return g.Ab},"%W":function(g){return h(Math.floor((g.Bb+
7-(g.Ab+6)%7)/7),2)},"%y":function(g){return(g.Cb+1900).toString().substring(2)},"%Y":function(g){return g.Cb+1900},"%z":function(g){g=g.Yb;var u=0<=g;g=Math.abs(g)/60;return(u?"+":"-")+String("0000"+(g/60*100+g%60)).slice(-4)},"%Z":function(g){return g.ac},"%%":function(){return"%"}};c=c.replace(/%%/g,"\x00\x00");for(x in t)c.includes(x)&&(c=c.replace(new RegExp(x,"g"),t[x](e)));c=c.replace(/\0\0/g,"%");x=Va(c);if(x.length>b)return 0;H.set(x,a>>>0);return x.length-1}
var Jb={a:function(a){return Ja(a+24)+24},m:function(a){a=new S(a);a.Pb()||(a.Ib(!0),Q--);a.Jb(!1);P.push(a);a.Nb();return a.Qb()},ia:function(a){z("Unexpected exception thrown, this is not properly supported - aborting");D=!0;throw a;},w:function(){X(0);var a=P.pop();if(a.Xb()&&!a.Lb()){var b=a.Wb();b&&U(b)(a.Db);Ga(a.Db)}R=0},d:function(){var a=R;if(!a)return V=0;var b=new S(a);b.Fb(a);var c=b.Eb();if(!c)return V=0,a;for(var e=Array.prototype.slice.call(arguments),f=0;f<e.length;f++){var h=e[f];
if(0===h||h===c)break;if(Xa(h,c,b.zb+16))return V=h,a}V=c;return a},k:function(){var a=R;if(!a)return V=0;var b=new S(a);b.Fb(a);var c=b.Eb();if(!c)return V=0,a;for(var e=Array.prototype.slice.call(arguments),f=0;f<e.length;f++){var h=e[f];if(0===h||h===c)break;if(Xa(h,c,b.zb+16))return V=h,a}V=c;return a},g:function(){var a=R;if(!a)return V=0;var b=new S(a);b.Fb(a);var c=b.Eb();if(!c)return V=0,a;for(var e=Array.prototype.slice.call(arguments),f=0;f<e.length;f++){var h=e[f];if(0===h||h===c)break;
if(Xa(h,c,b.zb+16))return V=h,a}V=c;return a},s:Ga,L:function(){var a=P.pop();a||B("no exception to throw");var b=a.Db;a.Lb()||(P.push(a),a.Jb(!0),a.Ib(!1),Q++);R=b;throw b;},b:function(a,b,c){(new S(a)).Rb(b,c);R=a;Q++;throw a;},la:function(){return Q},i:function(a){R||(R=a);throw a;},H:function(){return 0},Ba:function(){},pa:function(){},ra:function(){},ka:function(){return 0},za:function(){},ua:function(){},ya:function(){},R:function(){},qa:function(){},na:function(){},Aa:function(){},oa:function(){},
Ha:function(){},Ja:function(){B("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking")},Ia:function(){B("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking")},S:function(){return Date.now()},Ca:function(){return!0},Da:function(a,b){a=new Date(1E3*(J[a>>>2]+4294967296*I[a+4>>>2]));I[b>>2>>>0]=a.getUTCSeconds();I[b+4>>2>>>0]=a.getUTCMinutes();I[b+8>>2>>>0]=a.getUTCHours();I[b+12>>2>>>
0]=a.getUTCDate();I[b+16>>2>>>0]=a.getUTCMonth();I[b+20>>2>>>0]=a.getUTCFullYear()-1900;I[b+24>>2>>>0]=a.getUTCDay();I[b+28>>2>>>0]=(a.getTime()-Date.UTC(a.getUTCFullYear(),0,1,0,0,0,0))/864E5|0},Ea:function(a,b){a=new Date(1E3*(J[a>>>2]+4294967296*I[a+4>>>2]));I[b>>2>>>0]=a.getSeconds();I[b+4>>2>>>0]=a.getMinutes();I[b+8>>2>>>0]=a.getHours();I[b+12>>2>>>0]=a.getDate();I[b+16>>2>>>0]=a.getMonth();I[b+20>>2>>>0]=a.getFullYear()-1900;I[b+24>>2>>>0]=a.getDay();var c=new Date(a.getFullYear(),0,1);I[b+
28>>2>>>0]=(a.getTime()-c.getTime())/864E5|0;I[b+36>>2>>>0]=-(60*a.getTimezoneOffset());var e=(new Date(a.getFullYear(),6,1)).getTimezoneOffset();c=c.getTimezoneOffset();I[b+32>>2>>>0]=(e!=c&&a.getTimezoneOffset()==Math.min(c,e))|0},Fa:function(a){var b=new Date(I[a+20>>2>>>0]+1900,I[a+16>>2>>>0],I[a+12>>2>>>0],I[a+8>>2>>>0],I[a+4>>2>>>0],I[a>>2>>>0],0),c=I[a+32>>2>>>0],e=b.getTimezoneOffset(),f=new Date(b.getFullYear(),0,1),h=(new Date(b.getFullYear(),6,1)).getTimezoneOffset(),k=f.getTimezoneOffset(),
l=Math.min(k,h);0>c?I[a+32>>2>>>0]=Number(h!=k&&l==e):0<c!=(l==e)&&(h=Math.max(k,h),b.setTime(b.getTime()+6E4*((0<c?l:h)-e)));I[a+24>>2>>>0]=b.getDay();I[a+28>>2>>>0]=(b.getTime()-f.getTime())/864E5|0;I[a>>2>>>0]=b.getSeconds();I[a+4>>2>>>0]=b.getMinutes();I[a+8>>2>>>0]=b.getHours();I[a+12>>2>>>0]=b.getDate();I[a+16>>2>>>0]=b.getMonth();return b.getTime()/1E3|0},sa:function(){return-52},ta:function(){},Ga:La,B:function(){B("")},ma:function(){return 4294901760},I:p?()=>{var a=process.hrtime();return 1E3*
a[0]+a[1]/1E6}:()=>performance.now(),xa:function(a,b,c){G.copyWithin(a>>>0,b>>>0,b+c>>>0)},G:function(a){var b=G.length;a>>>=0;if(4294901760<a)return!1;for(var c=1;4>=c;c*=2){var e=b*(1+.2/c);e=Math.min(e,a+100663296);var f=Math;e=Math.max(a,e);f=f.min.call(f,4294901760,e+(65536-e%65536)%65536);a:{try{ma.grow(f-sa.byteLength+65535>>>16);ta();var h=1;break a}catch(k){}h=void 0}if(h)return!0}return!1},va:function(a,b){var c=0;Na().forEach(function(e,f){var h=b+c;f=J[a+4*f>>2>>>0]=h;for(h=0;h<e.length;++h)H[f++>>
0>>>0]=e.charCodeAt(h);H[f>>0>>>0]=0;c+=e.length+1});return 0},wa:function(a,b){var c=Na();J[a>>2>>>0]=c.length;var e=0;c.forEach(function(f){e+=f.length+1});J[b>>2>>>0]=e;return 0},ba:function(a){noExitRuntime||0<ka||(Ya(),O(xa),Za(0),Pa[1].length&&Qa(1,10),Pa[2].length&&Qa(2,10));if(!(noExitRuntime||0<ka)){if(d.onExit)d.onExit(a);D=!0}ea(a,new ja(a))},E:function(){return 52},Q:function(){return 52},ca:function(){return 70},P:function(a,b,c,e){for(var f=0,h=0;h<c;h++){var k=J[b>>2>>>0],l=J[b+4>>
2>>>0];b+=8;for(var n=0;n<l;n++)Qa(a,G[k+n>>>0]);f+=l}J[e>>2>>>0]=f;return 0},c:function(){return V},ja:W,ea:$a,fa:ab,J:bb,e:cb,N:db,O:eb,j:fb,o:gb,p:hb,M:ib,r:jb,v:kb,K:lb,D:mb,X:nb,V:ob,U:pb,Z:qb,W:rb,Y:sb,T:tb,f:ub,q:vb,h:wb,da:xb,l:yb,t:zb,u:Ab,x:Bb,z:Cb,ga:Db,A:Eb,C:Fb,aa:Gb,_:Hb,$:Ib,n:function(a){return a},F:function(a){V=a},ha:Wa,y:function(a,b,c,e){return Wa(a,b,c,e)}};
(function(){function a(f){d.asm=f.exports;ma=d.asm.Ka;ta();ua=d.asm.ib;wa.unshift(d.asm.La);K--;d.monitorRunDependencies&&d.monitorRunDependencies(K);0==K&&(null!==Aa&&(clearInterval(Aa),Aa=null),L&&(f=L,L=null,f()))}function b(f){a(f.instance)}function c(f){return Ea().then(function(h){return WebAssembly.instantiate(h,e)}).then(function(h){return h}).then(f,function(h){z("failed to asynchronously prepare wasm: "+h);B(h)})}var e={a:Jb};K++;d.monitorRunDependencies&&d.monitorRunDependencies(K);if(d.instantiateWasm)try{return d.instantiateWasm(e,
a)}catch(f){return z("Module.instantiateWasm callback failed with error: "+f),!1}(function(){return A||"function"!=typeof WebAssembly.instantiateStreaming||Ba()||N.startsWith("file://")||p||"function"!=typeof fetch?c(b):fetch(N,{credentials:"same-origin"}).then(function(f){return WebAssembly.instantiateStreaming(f,e).then(b,function(h){z("wasm streaming compile failed: "+h);z("falling back to ArrayBuffer instantiation");return c(b)})})})().catch(ba);return{}})();
d.___wasm_call_ctors=function(){return(d.___wasm_call_ctors=d.asm.La).apply(null,arguments)};d._OrtInit=function(){return(d._OrtInit=d.asm.Ma).apply(null,arguments)};d._OrtCreateSessionOptions=function(){return(d._OrtCreateSessionOptions=d.asm.Na).apply(null,arguments)};d._OrtAppendExecutionProvider=function(){return(d._OrtAppendExecutionProvider=d.asm.Oa).apply(null,arguments)};d._OrtAddSessionConfigEntry=function(){return(d._OrtAddSessionConfigEntry=d.asm.Pa).apply(null,arguments)};
d._OrtReleaseSessionOptions=function(){return(d._OrtReleaseSessionOptions=d.asm.Qa).apply(null,arguments)};d._OrtCreateSession=function(){return(d._OrtCreateSession=d.asm.Ra).apply(null,arguments)};d._OrtReleaseSession=function(){return(d._OrtReleaseSession=d.asm.Sa).apply(null,arguments)};d._OrtGetInputCount=function(){return(d._OrtGetInputCount=d.asm.Ta).apply(null,arguments)};d._OrtGetOutputCount=function(){return(d._OrtGetOutputCount=d.asm.Ua).apply(null,arguments)};
d._OrtGetInputName=function(){return(d._OrtGetInputName=d.asm.Va).apply(null,arguments)};d._OrtGetOutputName=function(){return(d._OrtGetOutputName=d.asm.Wa).apply(null,arguments)};d._OrtFree=function(){return(d._OrtFree=d.asm.Xa).apply(null,arguments)};d._OrtCreateTensor=function(){return(d._OrtCreateTensor=d.asm.Ya).apply(null,arguments)};d._OrtGetTensorData=function(){return(d._OrtGetTensorData=d.asm.Za).apply(null,arguments)};
d._OrtReleaseTensor=function(){return(d._OrtReleaseTensor=d.asm._a).apply(null,arguments)};d._OrtCreateRunOptions=function(){return(d._OrtCreateRunOptions=d.asm.$a).apply(null,arguments)};d._OrtAddRunConfigEntry=function(){return(d._OrtAddRunConfigEntry=d.asm.ab).apply(null,arguments)};d._OrtReleaseRunOptions=function(){return(d._OrtReleaseRunOptions=d.asm.bb).apply(null,arguments)};d._OrtRun=function(){return(d._OrtRun=d.asm.cb).apply(null,arguments)};
d._OrtEndProfiling=function(){return(d._OrtEndProfiling=d.asm.db).apply(null,arguments)};
var Ja=d._malloc=function(){return(Ja=d._malloc=d.asm.eb).apply(null,arguments)},Ha=d._free=function(){return(Ha=d._free=d.asm.fb).apply(null,arguments)},Za=d._fflush=function(){return(Za=d._fflush=d.asm.gb).apply(null,arguments)},Ya=d.___funcs_on_exit=function(){return(Ya=d.___funcs_on_exit=d.asm.hb).apply(null,arguments)},X=d._setThrew=function(){return(X=d._setThrew=d.asm.jb).apply(null,arguments)},Y=d.stackSave=function(){return(Y=d.stackSave=d.asm.kb).apply(null,arguments)},Z=d.stackRestore=
function(){return(Z=d.stackRestore=d.asm.lb).apply(null,arguments)},Kb=d.stackAlloc=function(){return(Kb=d.stackAlloc=d.asm.mb).apply(null,arguments)},Xa=d.___cxa_can_catch=function(){return(Xa=d.___cxa_can_catch=d.asm.nb).apply(null,arguments)},Fa=d.___cxa_is_pointer_type=function(){return(Fa=d.___cxa_is_pointer_type=d.asm.ob).apply(null,arguments)},Lb=d.dynCall_j=function(){return(Lb=d.dynCall_j=d.asm.pb).apply(null,arguments)},Mb=d.dynCall_iiiiij=function(){return(Mb=d.dynCall_iiiiij=d.asm.qb).apply(null,
arguments)},Nb=d.dynCall_jii=function(){return(Nb=d.dynCall_jii=d.asm.rb).apply(null,arguments)},Ob=d.dynCall_viiiiij=function(){return(Ob=d.dynCall_viiiiij=d.asm.sb).apply(null,arguments)},Pb=d.dynCall_vjji=function(){return(Pb=d.dynCall_vjji=d.asm.tb).apply(null,arguments)},Qb=d.dynCall_viiijjjii=function(){return(Qb=d.dynCall_viiijjjii=d.asm.ub).apply(null,arguments)},Rb=d.dynCall_iij=function(){return(Rb=d.dynCall_iij=d.asm.vb).apply(null,arguments)},Sb=d.dynCall_ji=function(){return(Sb=d.dynCall_ji=
d.asm.wb).apply(null,arguments)},Tb=d.dynCall_iiiiiij=function(){return(Tb=d.dynCall_iiiiiij=d.asm.xb).apply(null,arguments)},Ub=d.dynCall_iiij=function(){return(Ub=d.dynCall_iiij=d.asm.yb).apply(null,arguments)};function cb(a,b){var c=Y();try{return U(a)(b)}catch(e){Z(c);if(e!==e+0)throw e;X(1,0)}}function vb(a,b){var c=Y();try{U(a)(b)}catch(e){Z(c);if(e!==e+0)throw e;X(1,0)}}function wb(a,b,c){var e=Y();try{U(a)(b,c)}catch(f){Z(e);if(f!==f+0)throw f;X(1,0)}}
function fb(a,b,c){var e=Y();try{return U(a)(b,c)}catch(f){Z(e);if(f!==f+0)throw f;X(1,0)}}function gb(a,b,c,e){var f=Y();try{return U(a)(b,c,e)}catch(h){Z(f);if(h!==h+0)throw h;X(1,0)}}function kb(a,b,c,e,f,h,k){var l=Y();try{return U(a)(b,c,e,f,h,k)}catch(n){Z(l);if(n!==n+0)throw n;X(1,0)}}function ub(a){var b=Y();try{U(a)()}catch(c){Z(b);if(c!==c+0)throw c;X(1,0)}}function jb(a,b,c,e,f,h){var k=Y();try{return U(a)(b,c,e,f,h)}catch(l){Z(k);if(l!==l+0)throw l;X(1,0)}}
function hb(a,b,c,e,f){var h=Y();try{return U(a)(b,c,e,f)}catch(k){Z(h);if(k!==k+0)throw k;X(1,0)}}function yb(a,b,c,e){var f=Y();try{U(a)(b,c,e)}catch(h){Z(f);if(h!==h+0)throw h;X(1,0)}}function Ab(a,b,c,e,f,h){var k=Y();try{U(a)(b,c,e,f,h)}catch(l){Z(k);if(l!==l+0)throw l;X(1,0)}}function zb(a,b,c,e,f){var h=Y();try{U(a)(b,c,e,f)}catch(k){Z(h);if(k!==k+0)throw k;X(1,0)}}function Bb(a,b,c,e,f,h,k){var l=Y();try{U(a)(b,c,e,f,h,k)}catch(n){Z(l);if(n!==n+0)throw n;X(1,0)}}
function Cb(a,b,c,e,f,h,k,l){var n=Y();try{U(a)(b,c,e,f,h,k,l)}catch(t){Z(n);if(t!==t+0)throw t;X(1,0)}}function eb(a,b,c){var e=Y();try{return U(a)(b,c)}catch(f){Z(e);if(f!==f+0)throw f;X(1,0)}}function db(a,b,c){var e=Y();try{return U(a)(b,c)}catch(f){Z(e);if(f!==f+0)throw f;X(1,0)}}function Db(a,b,c,e,f,h,k,l,n){var t=Y();try{U(a)(b,c,e,f,h,k,l,n)}catch(x){Z(t);if(x!==x+0)throw x;X(1,0)}}function ib(a,b,c,e,f,h){var k=Y();try{return U(a)(b,c,e,f,h)}catch(l){Z(k);if(l!==l+0)throw l;X(1,0)}}
function lb(a,b,c,e,f,h,k,l){var n=Y();try{return U(a)(b,c,e,f,h,k,l)}catch(t){Z(n);if(t!==t+0)throw t;X(1,0)}}function mb(a,b,c,e,f,h,k,l,n,t,x,E){var C=Y();try{return U(a)(b,c,e,f,h,k,l,n,t,x,E)}catch(g){Z(C);if(g!==g+0)throw g;X(1,0)}}function Eb(a,b,c,e,f,h,k,l,n,t,x){var E=Y();try{U(a)(b,c,e,f,h,k,l,n,t,x)}catch(C){Z(E);if(C!==C+0)throw C;X(1,0)}}function Fb(a,b,c,e,f,h,k,l,n,t,x,E,C,g,u,w){var F=Y();try{U(a)(b,c,e,f,h,k,l,n,t,x,E,C,g,u,w)}catch(M){Z(F);if(M!==M+0)throw M;X(1,0)}}
function bb(a){var b=Y();try{return U(a)()}catch(c){Z(b);if(c!==c+0)throw c;X(1,0)}}function ab(a,b,c){var e=Y();try{return U(a)(b,c)}catch(f){Z(e);if(f!==f+0)throw f;X(1,0)}}function $a(a,b,c){var e=Y();try{return U(a)(b,c)}catch(f){Z(e);if(f!==f+0)throw f;X(1,0)}}function xb(a,b,c,e){var f=Y();try{U(a)(b,c,e)}catch(h){Z(f);if(h!==h+0)throw h;X(1,0)}}function Gb(a,b,c,e,f,h,k,l){var n=Y();try{Ob(a,b,c,e,f,h,k,l)}catch(t){Z(n);if(t!==t+0)throw t;X(1,0)}}
function Ib(a,b,c,e,f,h){var k=Y();try{Pb(a,b,c,e,f,h)}catch(l){Z(k);if(l!==l+0)throw l;X(1,0)}}function Hb(a,b,c,e,f,h,k,l,n,t,x,E){var C=Y();try{Qb(a,b,c,e,f,h,k,l,n,t,x,E)}catch(g){Z(C);if(g!==g+0)throw g;X(1,0)}}function qb(a,b,c,e){var f=Y();try{return Rb(a,b,c,e)}catch(h){Z(f);if(h!==h+0)throw h;X(1,0)}}function sb(a,b){var c=Y();try{return Sb(a,b)}catch(e){Z(c);if(e!==e+0)throw e;X(1,0)}}
function nb(a,b,c,e,f,h,k,l){var n=Y();try{return Tb(a,b,c,e,f,h,k,l)}catch(t){Z(n);if(t!==t+0)throw t;X(1,0)}}function rb(a){var b=Y();try{return Lb(a)}catch(c){Z(b);if(c!==c+0)throw c;X(1,0)}}function ob(a,b,c,e,f,h,k){var l=Y();try{return Mb(a,b,c,e,f,h,k)}catch(n){Z(l);if(n!==n+0)throw n;X(1,0)}}function pb(a,b,c,e,f){var h=Y();try{return Ub(a,b,c,e,f)}catch(k){Z(h);if(k!==k+0)throw k;X(1,0)}}function tb(a,b,c){var e=Y();try{return Nb(a,b,c)}catch(f){Z(e);if(f!==f+0)throw f;X(1,0)}}
d.UTF8ToString=pa;d.stringToUTF8=function(a,b,c){return qa(a,G,b,c)};d.lengthBytesUTF8=ra;d.stackSave=Y;d.stackRestore=Z;d.stackAlloc=Kb;var Vb;L=function Wb(){Vb||Xb();Vb||(L=Wb)};
function Xb(){function a(){if(!Vb&&(Vb=!0,d.calledRun=!0,!D)){O(wa);aa(d);if(d.onRuntimeInitialized)d.onRuntimeInitialized();if(d.postRun)for("function"==typeof d.postRun&&(d.postRun=[d.postRun]);d.postRun.length;){var b=d.postRun.shift();ya.unshift(b)}O(ya)}}if(!(0<K)){if(d.preRun)for("function"==typeof d.preRun&&(d.preRun=[d.preRun]);d.preRun.length;)za();O(va);0<K||(d.setStatus?(d.setStatus("Running..."),setTimeout(function(){setTimeout(function(){d.setStatus("")},1);a()},1)):a())}}
if(d.preInit)for("function"==typeof d.preInit&&(d.preInit=[d.preInit]);0<d.preInit.length;)d.preInit.pop()();Xb();


  return ortWasm.ready
}
);
})();
if (true)
  module.exports = ortWasm;
else {}


/***/ }),

/***/ "./node_modules/@protobufjs/aspromise/index.js":
/*!*****************************************************!*\
  !*** ./node_modules/@protobufjs/aspromise/index.js ***!
  \*****************************************************/
/***/ ((module) => {

"use strict";

module.exports = asPromise;

/**
 * Callback as used by {@link util.asPromise}.
 * @typedef asPromiseCallback
 * @type {function}
 * @param {Error|null} error Error, if any
 * @param {...*} params Additional arguments
 * @returns {undefined}
 */

/**
 * Returns a promise from a node-style callback function.
 * @memberof util
 * @param {asPromiseCallback} fn Function to call
 * @param {*} ctx Function context
 * @param {...*} params Function arguments
 * @returns {Promise<*>} Promisified function
 */
function asPromise(fn, ctx/*, varargs */) {
    var params  = new Array(arguments.length - 1),
        offset  = 0,
        index   = 2,
        pending = true;
    while (index < arguments.length)
        params[offset++] = arguments[index++];
    return new Promise(function executor(resolve, reject) {
        params[offset] = function callback(err/*, varargs */) {
            if (pending) {
                pending = false;
                if (err)
                    reject(err);
                else {
                    var params = new Array(arguments.length - 1),
                        offset = 0;
                    while (offset < params.length)
                        params[offset++] = arguments[offset];
                    resolve.apply(null, params);
                }
            }
        };
        try {
            fn.apply(ctx || null, params);
        } catch (err) {
            if (pending) {
                pending = false;
                reject(err);
            }
        }
    });
}


/***/ }),

/***/ "./node_modules/@protobufjs/base64/index.js":
/*!**************************************************!*\
  !*** ./node_modules/@protobufjs/base64/index.js ***!
  \**************************************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";


/**
 * A minimal base64 implementation for number arrays.
 * @memberof util
 * @namespace
 */
var base64 = exports;

/**
 * Calculates the byte length of a base64 encoded string.
 * @param {string} string Base64 encoded string
 * @returns {number} Byte length
 */
base64.length = function length(string) {
    var p = string.length;
    if (!p)
        return 0;
    var n = 0;
    while (--p % 4 > 1 && string.charAt(p) === "=")
        ++n;
    return Math.ceil(string.length * 3) / 4 - n;
};

// Base64 encoding table
var b64 = new Array(64);

// Base64 decoding table
var s64 = new Array(123);

// 65..90, 97..122, 48..57, 43, 47
for (var i = 0; i < 64;)
    s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++;

/**
 * Encodes a buffer to a base64 encoded string.
 * @param {Uint8Array} buffer Source buffer
 * @param {number} start Source start
 * @param {number} end Source end
 * @returns {string} Base64 encoded string
 */
base64.encode = function encode(buffer, start, end) {
    var parts = null,
        chunk = [];
    var i = 0, // output index
        j = 0, // goto index
        t;     // temporary
    while (start < end) {
        var b = buffer[start++];
        switch (j) {
            case 0:
                chunk[i++] = b64[b >> 2];
                t = (b & 3) << 4;
                j = 1;
                break;
            case 1:
                chunk[i++] = b64[t | b >> 4];
                t = (b & 15) << 2;
                j = 2;
                break;
            case 2:
                chunk[i++] = b64[t | b >> 6];
                chunk[i++] = b64[b & 63];
                j = 0;
                break;
        }
        if (i > 8191) {
            (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));
            i = 0;
        }
    }
    if (j) {
        chunk[i++] = b64[t];
        chunk[i++] = 61;
        if (j === 1)
            chunk[i++] = 61;
    }
    if (parts) {
        if (i)
            parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));
        return parts.join("");
    }
    return String.fromCharCode.apply(String, chunk.slice(0, i));
};

var invalidEncoding = "invalid encoding";

/**
 * Decodes a base64 encoded string to a buffer.
 * @param {string} string Source string
 * @param {Uint8Array} buffer Destination buffer
 * @param {number} offset Destination offset
 * @returns {number} Number of bytes written
 * @throws {Error} If encoding is invalid
 */
base64.decode = function decode(string, buffer, offset) {
    var start = offset;
    var j = 0, // goto index
        t;     // temporary
    for (var i = 0; i < string.length;) {
        var c = string.charCodeAt(i++);
        if (c === 61 && j > 1)
            break;
        if ((c = s64[c]) === undefined)
            throw Error(invalidEncoding);
        switch (j) {
            case 0:
                t = c;
                j = 1;
                break;
            case 1:
                buffer[offset++] = t << 2 | (c & 48) >> 4;
                t = c;
                j = 2;
                break;
            case 2:
                buffer[offset++] = (t & 15) << 4 | (c & 60) >> 2;
                t = c;
                j = 3;
                break;
            case 3:
                buffer[offset++] = (t & 3) << 6 | c;
                j = 0;
                break;
        }
    }
    if (j === 1)
        throw Error(invalidEncoding);
    return offset - start;
};

/**
 * Tests if the specified string appears to be base64 encoded.
 * @param {string} string String to test
 * @returns {boolean} `true` if probably base64 encoded, otherwise false
 */
base64.test = function test(string) {
    return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string);
};


/***/ }),

/***/ "./node_modules/@protobufjs/eventemitter/index.js":
/*!********************************************************!*\
  !*** ./node_modules/@protobufjs/eventemitter/index.js ***!
  \********************************************************/
/***/ ((module) => {

"use strict";

module.exports = EventEmitter;

/**
 * Constructs a new event emitter instance.
 * @classdesc A minimal event emitter.
 * @memberof util
 * @constructor
 */
function EventEmitter() {

    /**
     * Registered listeners.
     * @type {Object.<string,*>}
     * @private
     */
    this._listeners = {};
}

/**
 * Registers an event listener.
 * @param {string} evt Event name
 * @param {function} fn Listener
 * @param {*} [ctx] Listener context
 * @returns {util.EventEmitter} `this`
 */
EventEmitter.prototype.on = function on(evt, fn, ctx) {
    (this._listeners[evt] || (this._listeners[evt] = [])).push({
        fn  : fn,
        ctx : ctx || this
    });
    return this;
};

/**
 * Removes an event listener or any matching listeners if arguments are omitted.
 * @param {string} [evt] Event name. Removes all listeners if omitted.
 * @param {function} [fn] Listener to remove. Removes all listeners of `evt` if omitted.
 * @returns {util.EventEmitter} `this`
 */
EventEmitter.prototype.off = function off(evt, fn) {
    if (evt === undefined)
        this._listeners = {};
    else {
        if (fn === undefined)
            this._listeners[evt] = [];
        else {
            var listeners = this._listeners[evt];
            for (var i = 0; i < listeners.length;)
                if (listeners[i].fn === fn)
                    listeners.splice(i, 1);
                else
                    ++i;
        }
    }
    return this;
};

/**
 * Emits an event by calling its listeners with the specified arguments.
 * @param {string} evt Event name
 * @param {...*} args Arguments
 * @returns {util.EventEmitter} `this`
 */
EventEmitter.prototype.emit = function emit(evt) {
    var listeners = this._listeners[evt];
    if (listeners) {
        var args = [],
            i = 1;
        for (; i < arguments.length;)
            args.push(arguments[i++]);
        for (i = 0; i < listeners.length;)
            listeners[i].fn.apply(listeners[i++].ctx, args);
    }
    return this;
};


/***/ }),

/***/ "./node_modules/@protobufjs/float/index.js":
/*!*************************************************!*\
  !*** ./node_modules/@protobufjs/float/index.js ***!
  \*************************************************/
/***/ ((module) => {

"use strict";


module.exports = factory(factory);

/**
 * Reads / writes floats / doubles from / to buffers.
 * @name util.float
 * @namespace
 */

/**
 * Writes a 32 bit float to a buffer using little endian byte order.
 * @name util.float.writeFloatLE
 * @function
 * @param {number} val Value to write
 * @param {Uint8Array} buf Target buffer
 * @param {number} pos Target buffer offset
 * @returns {undefined}
 */

/**
 * Writes a 32 bit float to a buffer using big endian byte order.
 * @name util.float.writeFloatBE
 * @function
 * @param {number} val Value to write
 * @param {Uint8Array} buf Target buffer
 * @param {number} pos Target buffer offset
 * @returns {undefined}
 */

/**
 * Reads a 32 bit float from a buffer using little endian byte order.
 * @name util.float.readFloatLE
 * @function
 * @param {Uint8Array} buf Source buffer
 * @param {number} pos Source buffer offset
 * @returns {number} Value read
 */

/**
 * Reads a 32 bit float from a buffer using big endian byte order.
 * @name util.float.readFloatBE
 * @function
 * @param {Uint8Array} buf Source buffer
 * @param {number} pos Source buffer offset
 * @returns {number} Value read
 */

/**
 * Writes a 64 bit double to a buffer using little endian byte order.
 * @name util.float.writeDoubleLE
 * @function
 * @param {number} val Value to write
 * @param {Uint8Array} buf Target buffer
 * @param {number} pos Target buffer offset
 * @returns {undefined}
 */

/**
 * Writes a 64 bit double to a buffer using big endian byte order.
 * @name util.float.writeDoubleBE
 * @function
 * @param {number} val Value to write
 * @param {Uint8Array} buf Target buffer
 * @param {number} pos Target buffer offset
 * @returns {undefined}
 */

/**
 * Reads a 64 bit double from a buffer using little endian byte order.
 * @name util.float.readDoubleLE
 * @function
 * @param {Uint8Array} buf Source buffer
 * @param {number} pos Source buffer offset
 * @returns {number} Value read
 */

/**
 * Reads a 64 bit double from a buffer using big endian byte order.
 * @name util.float.readDoubleBE
 * @function
 * @param {Uint8Array} buf Source buffer
 * @param {number} pos Source buffer offset
 * @returns {number} Value read
 */

// Factory function for the purpose of node-based testing in modified global environments
function factory(exports) {

    // float: typed array
    if (typeof Float32Array !== "undefined") (function() {

        var f32 = new Float32Array([ -0 ]),
            f8b = new Uint8Array(f32.buffer),
            le  = f8b[3] === 128;

        function writeFloat_f32_cpy(val, buf, pos) {
            f32[0] = val;
            buf[pos    ] = f8b[0];
            buf[pos + 1] = f8b[1];
            buf[pos + 2] = f8b[2];
            buf[pos + 3] = f8b[3];
        }

        function writeFloat_f32_rev(val, buf, pos) {
            f32[0] = val;
            buf[pos    ] = f8b[3];
            buf[pos + 1] = f8b[2];
            buf[pos + 2] = f8b[1];
            buf[pos + 3] = f8b[0];
        }

        /* istanbul ignore next */
        exports.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev;
        /* istanbul ignore next */
        exports.writeFloatBE = le ? writeFloat_f32_rev : writeFloat_f32_cpy;

        function readFloat_f32_cpy(buf, pos) {
            f8b[0] = buf[pos    ];
            f8b[1] = buf[pos + 1];
            f8b[2] = buf[pos + 2];
            f8b[3] = buf[pos + 3];
            return f32[0];
        }

        function readFloat_f32_rev(buf, pos) {
            f8b[3] = buf[pos    ];
            f8b[2] = buf[pos + 1];
            f8b[1] = buf[pos + 2];
            f8b[0] = buf[pos + 3];
            return f32[0];
        }

        /* istanbul ignore next */
        exports.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev;
        /* istanbul ignore next */
        exports.readFloatBE = le ? readFloat_f32_rev : readFloat_f32_cpy;

    // float: ieee754
    })(); else (function() {

        function writeFloat_ieee754(writeUint, val, buf, pos) {
            var sign = val < 0 ? 1 : 0;
            if (sign)
                val = -val;
            if (val === 0)
                writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos);
            else if (isNaN(val))
                writeUint(2143289344, buf, pos);
            else if (val > 3.4028234663852886e+38) // +-Infinity
                writeUint((sign << 31 | 2139095040) >>> 0, buf, pos);
            else if (val < 1.1754943508222875e-38) // denormal
                writeUint((sign << 31 | Math.round(val / 1.401298464324817e-45)) >>> 0, buf, pos);
            else {
                var exponent = Math.floor(Math.log(val) / Math.LN2),
                    mantissa = Math.round(val * Math.pow(2, -exponent) * 8388608) & 8388607;
                writeUint((sign << 31 | exponent + 127 << 23 | mantissa) >>> 0, buf, pos);
            }
        }

        exports.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE);
        exports.writeFloatBE = writeFloat_ieee754.bind(null, writeUintBE);

        function readFloat_ieee754(readUint, buf, pos) {
            var uint = readUint(buf, pos),
                sign = (uint >> 31) * 2 + 1,
                exponent = uint >>> 23 & 255,
                mantissa = uint & 8388607;
            return exponent === 255
                ? mantissa
                ? NaN
                : sign * Infinity
                : exponent === 0 // denormal
                ? sign * 1.401298464324817e-45 * mantissa
                : sign * Math.pow(2, exponent - 150) * (mantissa + 8388608);
        }

        exports.readFloatLE = readFloat_ieee754.bind(null, readUintLE);
        exports.readFloatBE = readFloat_ieee754.bind(null, readUintBE);

    })();

    // double: typed array
    if (typeof Float64Array !== "undefined") (function() {

        var f64 = new Float64Array([-0]),
            f8b = new Uint8Array(f64.buffer),
            le  = f8b[7] === 128;

        function writeDouble_f64_cpy(val, buf, pos) {
            f64[0] = val;
            buf[pos    ] = f8b[0];
            buf[pos + 1] = f8b[1];
            buf[pos + 2] = f8b[2];
            buf[pos + 3] = f8b[3];
            buf[pos + 4] = f8b[4];
            buf[pos + 5] = f8b[5];
            buf[pos + 6] = f8b[6];
            buf[pos + 7] = f8b[7];
        }

        function writeDouble_f64_rev(val, buf, pos) {
            f64[0] = val;
            buf[pos    ] = f8b[7];
            buf[pos + 1] = f8b[6];
            buf[pos + 2] = f8b[5];
            buf[pos + 3] = f8b[4];
            buf[pos + 4] = f8b[3];
            buf[pos + 5] = f8b[2];
            buf[pos + 6] = f8b[1];
            buf[pos + 7] = f8b[0];
        }

        /* istanbul ignore next */
        exports.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev;
        /* istanbul ignore next */
        exports.writeDoubleBE = le ? writeDouble_f64_rev : writeDouble_f64_cpy;

        function readDouble_f64_cpy(buf, pos) {
            f8b[0] = buf[pos    ];
            f8b[1] = buf[pos + 1];
            f8b[2] = buf[pos + 2];
            f8b[3] = buf[pos + 3];
            f8b[4] = buf[pos + 4];
            f8b[5] = buf[pos + 5];
            f8b[6] = buf[pos + 6];
            f8b[7] = buf[pos + 7];
            return f64[0];
        }

        function readDouble_f64_rev(buf, pos) {
            f8b[7] = buf[pos    ];
            f8b[6] = buf[pos + 1];
            f8b[5] = buf[pos + 2];
            f8b[4] = buf[pos + 3];
            f8b[3] = buf[pos + 4];
            f8b[2] = buf[pos + 5];
            f8b[1] = buf[pos + 6];
            f8b[0] = buf[pos + 7];
            return f64[0];
        }

        /* istanbul ignore next */
        exports.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev;
        /* istanbul ignore next */
        exports.readDoubleBE = le ? readDouble_f64_rev : readDouble_f64_cpy;

    // double: ieee754
    })(); else (function() {

        function writeDouble_ieee754(writeUint, off0, off1, val, buf, pos) {
            var sign = val < 0 ? 1 : 0;
            if (sign)
                val = -val;
            if (val === 0) {
                writeUint(0, buf, pos + off0);
                writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos + off1);
            } else if (isNaN(val)) {
                writeUint(0, buf, pos + off0);
                writeUint(2146959360, buf, pos + off1);
            } else if (val > 1.7976931348623157e+308) { // +-Infinity
                writeUint(0, buf, pos + off0);
                writeUint((sign << 31 | 2146435072) >>> 0, buf, pos + off1);
            } else {
                var mantissa;
                if (val < 2.2250738585072014e-308) { // denormal
                    mantissa = val / 5e-324;
                    writeUint(mantissa >>> 0, buf, pos + off0);
                    writeUint((sign << 31 | mantissa / 4294967296) >>> 0, buf, pos + off1);
                } else {
                    var exponent = Math.floor(Math.log(val) / Math.LN2);
                    if (exponent === 1024)
                        exponent = 1023;
                    mantissa = val * Math.pow(2, -exponent);
                    writeUint(mantissa * 4503599627370496 >>> 0, buf, pos + off0);
                    writeUint((sign << 31 | exponent + 1023 << 20 | mantissa * 1048576 & 1048575) >>> 0, buf, pos + off1);
                }
            }
        }

        exports.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4);
        exports.writeDoubleBE = writeDouble_ieee754.bind(null, writeUintBE, 4, 0);

        function readDouble_ieee754(readUint, off0, off1, buf, pos) {
            var lo = readUint(buf, pos + off0),
                hi = readUint(buf, pos + off1);
            var sign = (hi >> 31) * 2 + 1,
                exponent = hi >>> 20 & 2047,
                mantissa = 4294967296 * (hi & 1048575) + lo;
            return exponent === 2047
                ? mantissa
                ? NaN
                : sign * Infinity
                : exponent === 0 // denormal
                ? sign * 5e-324 * mantissa
                : sign * Math.pow(2, exponent - 1075) * (mantissa + 4503599627370496);
        }

        exports.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4);
        exports.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0);

    })();

    return exports;
}

// uint helpers

function writeUintLE(val, buf, pos) {
    buf[pos    ] =  val        & 255;
    buf[pos + 1] =  val >>> 8  & 255;
    buf[pos + 2] =  val >>> 16 & 255;
    buf[pos + 3] =  val >>> 24;
}

function writeUintBE(val, buf, pos) {
    buf[pos    ] =  val >>> 24;
    buf[pos + 1] =  val >>> 16 & 255;
    buf[pos + 2] =  val >>> 8  & 255;
    buf[pos + 3] =  val        & 255;
}

function readUintLE(buf, pos) {
    return (buf[pos    ]
          | buf[pos + 1] << 8
          | buf[pos + 2] << 16
          | buf[pos + 3] << 24) >>> 0;
}

function readUintBE(buf, pos) {
    return (buf[pos    ] << 24
          | buf[pos + 1] << 16
          | buf[pos + 2] << 8
          | buf[pos + 3]) >>> 0;
}


/***/ }),

/***/ "./node_modules/@protobufjs/inquire/index.js":
/*!***************************************************!*\
  !*** ./node_modules/@protobufjs/inquire/index.js ***!
  \***************************************************/
/***/ ((module) => {

"use strict";

module.exports = inquire;

/**
 * Requires a module only if available.
 * @memberof util
 * @param {string} moduleName Module to require
 * @returns {?Object} Required module if available and not empty, otherwise `null`
 */
function inquire(moduleName) {
    return null;
}


/***/ }),

/***/ "./node_modules/@protobufjs/pool/index.js":
/*!************************************************!*\
  !*** ./node_modules/@protobufjs/pool/index.js ***!
  \************************************************/
/***/ ((module) => {

"use strict";

module.exports = pool;

/**
 * An allocator as used by {@link util.pool}.
 * @typedef PoolAllocator
 * @type {function}
 * @param {number} size Buffer size
 * @returns {Uint8Array} Buffer
 */

/**
 * A slicer as used by {@link util.pool}.
 * @typedef PoolSlicer
 * @type {function}
 * @param {number} start Start offset
 * @param {number} end End offset
 * @returns {Uint8Array} Buffer slice
 * @this {Uint8Array}
 */

/**
 * A general purpose buffer pool.
 * @memberof util
 * @function
 * @param {PoolAllocator} alloc Allocator
 * @param {PoolSlicer} slice Slicer
 * @param {number} [size=8192] Slab size
 * @returns {PoolAllocator} Pooled allocator
 */
function pool(alloc, slice, size) {
    var SIZE   = size || 8192;
    var MAX    = SIZE >>> 1;
    var slab   = null;
    var offset = SIZE;
    return function pool_alloc(size) {
        if (size < 1 || size > MAX)
            return alloc(size);
        if (offset + size > SIZE) {
            slab = alloc(SIZE);
            offset = 0;
        }
        var buf = slice.call(slab, offset, offset += size);
        if (offset & 7) // align to 32 bit
            offset = (offset | 7) + 1;
        return buf;
    };
}


/***/ }),

/***/ "./node_modules/@protobufjs/utf8/index.js":
/*!************************************************!*\
  !*** ./node_modules/@protobufjs/utf8/index.js ***!
  \************************************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";


/**
 * A minimal UTF8 implementation for number arrays.
 * @memberof util
 * @namespace
 */
var utf8 = exports;

/**
 * Calculates the UTF8 byte length of a string.
 * @param {string} string String
 * @returns {number} Byte length
 */
utf8.length = function utf8_length(string) {
    var len = 0,
        c = 0;
    for (var i = 0; i < string.length; ++i) {
        c = string.charCodeAt(i);
        if (c < 128)
            len += 1;
        else if (c < 2048)
            len += 2;
        else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) {
            ++i;
            len += 4;
        } else
            len += 3;
    }
    return len;
};

/**
 * Reads UTF8 bytes as a string.
 * @param {Uint8Array} buffer Source buffer
 * @param {number} start Source start
 * @param {number} end Source end
 * @returns {string} String read
 */
utf8.read = function utf8_read(buffer, start, end) {
    var len = end - start;
    if (len < 1)
        return "";
    var parts = null,
        chunk = [],
        i = 0, // char offset
        t;     // temporary
    while (start < end) {
        t = buffer[start++];
        if (t < 128)
            chunk[i++] = t;
        else if (t > 191 && t < 224)
            chunk[i++] = (t & 31) << 6 | buffer[start++] & 63;
        else if (t > 239 && t < 365) {
            t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000;
            chunk[i++] = 0xD800 + (t >> 10);
            chunk[i++] = 0xDC00 + (t & 1023);
        } else
            chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63;
        if (i > 8191) {
            (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));
            i = 0;
        }
    }
    if (parts) {
        if (i)
            parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));
        return parts.join("");
    }
    return String.fromCharCode.apply(String, chunk.slice(0, i));
};

/**
 * Writes a string as UTF8 bytes.
 * @param {string} string Source string
 * @param {Uint8Array} buffer Destination buffer
 * @param {number} offset Destination offset
 * @returns {number} Bytes written
 */
utf8.write = function utf8_write(string, buffer, offset) {
    var start = offset,
        c1, // character 1
        c2; // character 2
    for (var i = 0; i < string.length; ++i) {
        c1 = string.charCodeAt(i);
        if (c1 < 128) {
            buffer[offset++] = c1;
        } else if (c1 < 2048) {
            buffer[offset++] = c1 >> 6       | 192;
            buffer[offset++] = c1       & 63 | 128;
        } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) {
            c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF);
            ++i;
            buffer[offset++] = c1 >> 18      | 240;
            buffer[offset++] = c1 >> 12 & 63 | 128;
            buffer[offset++] = c1 >> 6  & 63 | 128;
            buffer[offset++] = c1       & 63 | 128;
        } else {
            buffer[offset++] = c1 >> 12      | 224;
            buffer[offset++] = c1 >> 6  & 63 | 128;
            buffer[offset++] = c1       & 63 | 128;
        }
    }
    return offset - start;
};


/***/ }),

/***/ "./node_modules/guid-typescript/dist/guid.js":
/*!***************************************************!*\
  !*** ./node_modules/guid-typescript/dist/guid.js ***!
  \***************************************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";

exports.__esModule = true;
var Guid = /** @class */ (function () {
    function Guid(guid) {
        if (!guid) {
            throw new TypeError("Invalid argument; `value` has no value.");
        }
        this.value = Guid.EMPTY;
        if (guid && Guid.isGuid(guid)) {
            this.value = guid;
        }
    }
    Guid.isGuid = function (guid) {
        var value = guid.toString();
        return guid && (guid instanceof Guid || Guid.validator.test(value));
    };
    Guid.create = function () {
        return new Guid([Guid.gen(2), Guid.gen(1), Guid.gen(1), Guid.gen(1), Guid.gen(3)].join("-"));
    };
    Guid.createEmpty = function () {
        return new Guid("emptyguid");
    };
    Guid.parse = function (guid) {
        return new Guid(guid);
    };
    Guid.raw = function () {
        return [Guid.gen(2), Guid.gen(1), Guid.gen(1), Guid.gen(1), Guid.gen(3)].join("-");
    };
    Guid.gen = function (count) {
        var out = "";
        for (var i = 0; i < count; i++) {
            // tslint:disable-next-line:no-bitwise
            out += (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
        }
        return out;
    };
    Guid.prototype.equals = function (other) {
        // Comparing string `value` against provided `guid` will auto-call
        // toString on `guid` for comparison
        return Guid.isGuid(other) && this.value === other.toString();
    };
    Guid.prototype.isEmpty = function () {
        return this.value === Guid.EMPTY;
    };
    Guid.prototype.toString = function () {
        return this.value;
    };
    Guid.prototype.toJSON = function () {
        return {
            value: this.value
        };
    };
    Guid.validator = new RegExp("^[a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12}$", "i");
    Guid.EMPTY = "00000000-0000-0000-0000-000000000000";
    return Guid;
}());
exports.Guid = Guid;


/***/ }),

/***/ "./node_modules/long/src/long.js":
/*!***************************************!*\
  !*** ./node_modules/long/src/long.js ***!
  \***************************************/
/***/ ((module) => {

module.exports = Long;

/**
 * wasm optimizations, to do native i64 multiplication and divide
 */
var wasm = null;

try {
  wasm = new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([
    0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11
  ])), {}).exports;
} catch (e) {
  // no wasm support :(
}

/**
 * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers.
 *  See the from* functions below for more convenient ways of constructing Longs.
 * @exports Long
 * @class A Long class for representing a 64 bit two's-complement integer value.
 * @param {number} low The low (signed) 32 bits of the long
 * @param {number} high The high (signed) 32 bits of the long
 * @param {boolean=} unsigned Whether unsigned or not, defaults to signed
 * @constructor
 */
function Long(low, high, unsigned) {

    /**
     * The low 32 bits as a signed value.
     * @type {number}
     */
    this.low = low | 0;

    /**
     * The high 32 bits as a signed value.
     * @type {number}
     */
    this.high = high | 0;

    /**
     * Whether unsigned or not.
     * @type {boolean}
     */
    this.unsigned = !!unsigned;
}

// The internal representation of a long is the two given signed, 32-bit values.
// We use 32-bit pieces because these are the size of integers on which
// Javascript performs bit-operations.  For operations like addition and
// multiplication, we split each number into 16 bit pieces, which can easily be
// multiplied within Javascript's floating-point representation without overflow
// or change in sign.
//
// In the algorithms below, we frequently reduce the negative case to the
// positive case by negating the input(s) and then post-processing the result.
// Note that we must ALWAYS check specially whether those values are MIN_VALUE
// (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as
// a positive number, it overflows back into a negative).  Not handling this
// case would often result in infinite recursion.
//
// Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the from*
// methods on which they depend.

/**
 * An indicator used to reliably determine if an object is a Long or not.
 * @type {boolean}
 * @const
 * @private
 */
Long.prototype.__isLong__;

Object.defineProperty(Long.prototype, "__isLong__", { value: true });

/**
 * @function
 * @param {*} obj Object
 * @returns {boolean}
 * @inner
 */
function isLong(obj) {
    return (obj && obj["__isLong__"]) === true;
}

/**
 * Tests if the specified object is a Long.
 * @function
 * @param {*} obj Object
 * @returns {boolean}
 */
Long.isLong = isLong;

/**
 * A cache of the Long representations of small integer values.
 * @type {!Object}
 * @inner
 */
var INT_CACHE = {};

/**
 * A cache of the Long representations of small unsigned integer values.
 * @type {!Object}
 * @inner
 */
var UINT_CACHE = {};

/**
 * @param {number} value
 * @param {boolean=} unsigned
 * @returns {!Long}
 * @inner
 */
function fromInt(value, unsigned) {
    var obj, cachedObj, cache;
    if (unsigned) {
        value >>>= 0;
        if (cache = (0 <= value && value < 256)) {
            cachedObj = UINT_CACHE[value];
            if (cachedObj)
                return cachedObj;
        }
        obj = fromBits(value, (value | 0) < 0 ? -1 : 0, true);
        if (cache)
            UINT_CACHE[value] = obj;
        return obj;
    } else {
        value |= 0;
        if (cache = (-128 <= value && value < 128)) {
            cachedObj = INT_CACHE[value];
            if (cachedObj)
                return cachedObj;
        }
        obj = fromBits(value, value < 0 ? -1 : 0, false);
        if (cache)
            INT_CACHE[value] = obj;
        return obj;
    }
}

/**
 * Returns a Long representing the given 32 bit integer value.
 * @function
 * @param {number} value The 32 bit integer in question
 * @param {boolean=} unsigned Whether unsigned or not, defaults to signed
 * @returns {!Long} The corresponding Long value
 */
Long.fromInt = fromInt;

/**
 * @param {number} value
 * @param {boolean=} unsigned
 * @returns {!Long}
 * @inner
 */
function fromNumber(value, unsigned) {
    if (isNaN(value))
        return unsigned ? UZERO : ZERO;
    if (unsigned) {
        if (value < 0)
            return UZERO;
        if (value >= TWO_PWR_64_DBL)
            return MAX_UNSIGNED_VALUE;
    } else {
        if (value <= -TWO_PWR_63_DBL)
            return MIN_VALUE;
        if (value + 1 >= TWO_PWR_63_DBL)
            return MAX_VALUE;
    }
    if (value < 0)
        return fromNumber(-value, unsigned).neg();
    return fromBits((value % TWO_PWR_32_DBL) | 0, (value / TWO_PWR_32_DBL) | 0, unsigned);
}

/**
 * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned.
 * @function
 * @param {number} value The number in question
 * @param {boolean=} unsigned Whether unsigned or not, defaults to signed
 * @returns {!Long} The corresponding Long value
 */
Long.fromNumber = fromNumber;

/**
 * @param {number} lowBits
 * @param {number} highBits
 * @param {boolean=} unsigned
 * @returns {!Long}
 * @inner
 */
function fromBits(lowBits, highBits, unsigned) {
    return new Long(lowBits, highBits, unsigned);
}

/**
 * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. Each is
 *  assumed to use 32 bits.
 * @function
 * @param {number} lowBits The low 32 bits
 * @param {number} highBits The high 32 bits
 * @param {boolean=} unsigned Whether unsigned or not, defaults to signed
 * @returns {!Long} The corresponding Long value
 */
Long.fromBits = fromBits;

/**
 * @function
 * @param {number} base
 * @param {number} exponent
 * @returns {number}
 * @inner
 */
var pow_dbl = Math.pow; // Used 4 times (4*8 to 15+4)

/**
 * @param {string} str
 * @param {(boolean|number)=} unsigned
 * @param {number=} radix
 * @returns {!Long}
 * @inner
 */
function fromString(str, unsigned, radix) {
    if (str.length === 0)
        throw Error('empty string');
    if (str === "NaN" || str === "Infinity" || str === "+Infinity" || str === "-Infinity")
        return ZERO;
    if (typeof unsigned === 'number') {
        // For goog.math.long compatibility
        radix = unsigned,
        unsigned = false;
    } else {
        unsigned = !! unsigned;
    }
    radix = radix || 10;
    if (radix < 2 || 36 < radix)
        throw RangeError('radix');

    var p;
    if ((p = str.indexOf('-')) > 0)
        throw Error('interior hyphen');
    else if (p === 0) {
        return fromString(str.substring(1), unsigned, radix).neg();
    }

    // Do several (8) digits each time through the loop, so as to
    // minimize the calls to the very expensive emulated div.
    var radixToPower = fromNumber(pow_dbl(radix, 8));

    var result = ZERO;
    for (var i = 0; i < str.length; i += 8) {
        var size = Math.min(8, str.length - i),
            value = parseInt(str.substring(i, i + size), radix);
        if (size < 8) {
            var power = fromNumber(pow_dbl(radix, size));
            result = result.mul(power).add(fromNumber(value));
        } else {
            result = result.mul(radixToPower);
            result = result.add(fromNumber(value));
        }
    }
    result.unsigned = unsigned;
    return result;
}

/**
 * Returns a Long representation of the given string, written using the specified radix.
 * @function
 * @param {string} str The textual representation of the Long
 * @param {(boolean|number)=} unsigned Whether unsigned or not, defaults to signed
 * @param {number=} radix The radix in which the text is written (2-36), defaults to 10
 * @returns {!Long} The corresponding Long value
 */
Long.fromString = fromString;

/**
 * @function
 * @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val
 * @param {boolean=} unsigned
 * @returns {!Long}
 * @inner
 */
function fromValue(val, unsigned) {
    if (typeof val === 'number')
        return fromNumber(val, unsigned);
    if (typeof val === 'string')
        return fromString(val, unsigned);
    // Throws for non-objects, converts non-instanceof Long:
    return fromBits(val.low, val.high, typeof unsigned === 'boolean' ? unsigned : val.unsigned);
}

/**
 * Converts the specified value to a Long using the appropriate from* function for its type.
 * @function
 * @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val Value
 * @param {boolean=} unsigned Whether unsigned or not, defaults to signed
 * @returns {!Long}
 */
Long.fromValue = fromValue;

// NOTE: the compiler should inline these constant values below and then remove these variables, so there should be
// no runtime penalty for these.

/**
 * @type {number}
 * @const
 * @inner
 */
var TWO_PWR_16_DBL = 1 << 16;

/**
 * @type {number}
 * @const
 * @inner
 */
var TWO_PWR_24_DBL = 1 << 24;

/**
 * @type {number}
 * @const
 * @inner
 */
var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;

/**
 * @type {number}
 * @const
 * @inner
 */
var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;

/**
 * @type {number}
 * @const
 * @inner
 */
var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2;

/**
 * @type {!Long}
 * @const
 * @inner
 */
var TWO_PWR_24 = fromInt(TWO_PWR_24_DBL);

/**
 * @type {!Long}
 * @inner
 */
var ZERO = fromInt(0);

/**
 * Signed zero.
 * @type {!Long}
 */
Long.ZERO = ZERO;

/**
 * @type {!Long}
 * @inner
 */
var UZERO = fromInt(0, true);

/**
 * Unsigned zero.
 * @type {!Long}
 */
Long.UZERO = UZERO;

/**
 * @type {!Long}
 * @inner
 */
var ONE = fromInt(1);

/**
 * Signed one.
 * @type {!Long}
 */
Long.ONE = ONE;

/**
 * @type {!Long}
 * @inner
 */
var UONE = fromInt(1, true);

/**
 * Unsigned one.
 * @type {!Long}
 */
Long.UONE = UONE;

/**
 * @type {!Long}
 * @inner
 */
var NEG_ONE = fromInt(-1);

/**
 * Signed negative one.
 * @type {!Long}
 */
Long.NEG_ONE = NEG_ONE;

/**
 * @type {!Long}
 * @inner
 */
var MAX_VALUE = fromBits(0xFFFFFFFF|0, 0x7FFFFFFF|0, false);

/**
 * Maximum signed value.
 * @type {!Long}
 */
Long.MAX_VALUE = MAX_VALUE;

/**
 * @type {!Long}
 * @inner
 */
var MAX_UNSIGNED_VALUE = fromBits(0xFFFFFFFF|0, 0xFFFFFFFF|0, true);

/**
 * Maximum unsigned value.
 * @type {!Long}
 */
Long.MAX_UNSIGNED_VALUE = MAX_UNSIGNED_VALUE;

/**
 * @type {!Long}
 * @inner
 */
var MIN_VALUE = fromBits(0, 0x80000000|0, false);

/**
 * Minimum signed value.
 * @type {!Long}
 */
Long.MIN_VALUE = MIN_VALUE;

/**
 * @alias Long.prototype
 * @inner
 */
var LongPrototype = Long.prototype;

/**
 * Converts the Long to a 32 bit integer, assuming it is a 32 bit integer.
 * @returns {number}
 */
LongPrototype.toInt = function toInt() {
    return this.unsigned ? this.low >>> 0 : this.low;
};

/**
 * Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa).
 * @returns {number}
 */
LongPrototype.toNumber = function toNumber() {
    if (this.unsigned)
        return ((this.high >>> 0) * TWO_PWR_32_DBL) + (this.low >>> 0);
    return this.high * TWO_PWR_32_DBL + (this.low >>> 0);
};

/**
 * Converts the Long to a string written in the specified radix.
 * @param {number=} radix Radix (2-36), defaults to 10
 * @returns {string}
 * @override
 * @throws {RangeError} If `radix` is out of range
 */
LongPrototype.toString = function toString(radix) {
    radix = radix || 10;
    if (radix < 2 || 36 < radix)
        throw RangeError('radix');
    if (this.isZero())
        return '0';
    if (this.isNegative()) { // Unsigned Longs are never negative
        if (this.eq(MIN_VALUE)) {
            // We need to change the Long value before it can be negated, so we remove
            // the bottom-most digit in this base and then recurse to do the rest.
            var radixLong = fromNumber(radix),
                div = this.div(radixLong),
                rem1 = div.mul(radixLong).sub(this);
            return div.toString(radix) + rem1.toInt().toString(radix);
        } else
            return '-' + this.neg().toString(radix);
    }

    // Do several (6) digits each time through the loop, so as to
    // minimize the calls to the very expensive emulated div.
    var radixToPower = fromNumber(pow_dbl(radix, 6), this.unsigned),
        rem = this;
    var result = '';
    while (true) {
        var remDiv = rem.div(radixToPower),
            intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0,
            digits = intval.toString(radix);
        rem = remDiv;
        if (rem.isZero())
            return digits + result;
        else {
            while (digits.length < 6)
                digits = '0' + digits;
            result = '' + digits + result;
        }
    }
};

/**
 * Gets the high 32 bits as a signed integer.
 * @returns {number} Signed high bits
 */
LongPrototype.getHighBits = function getHighBits() {
    return this.high;
};

/**
 * Gets the high 32 bits as an unsigned integer.
 * @returns {number} Unsigned high bits
 */
LongPrototype.getHighBitsUnsigned = function getHighBitsUnsigned() {
    return this.high >>> 0;
};

/**
 * Gets the low 32 bits as a signed integer.
 * @returns {number} Signed low bits
 */
LongPrototype.getLowBits = function getLowBits() {
    return this.low;
};

/**
 * Gets the low 32 bits as an unsigned integer.
 * @returns {number} Unsigned low bits
 */
LongPrototype.getLowBitsUnsigned = function getLowBitsUnsigned() {
    return this.low >>> 0;
};

/**
 * Gets the number of bits needed to represent the absolute value of this Long.
 * @returns {number}
 */
LongPrototype.getNumBitsAbs = function getNumBitsAbs() {
    if (this.isNegative()) // Unsigned Longs are never negative
        return this.eq(MIN_VALUE) ? 64 : this.neg().getNumBitsAbs();
    var val = this.high != 0 ? this.high : this.low;
    for (var bit = 31; bit > 0; bit--)
        if ((val & (1 << bit)) != 0)
            break;
    return this.high != 0 ? bit + 33 : bit + 1;
};

/**
 * Tests if this Long's value equals zero.
 * @returns {boolean}
 */
LongPrototype.isZero = function isZero() {
    return this.high === 0 && this.low === 0;
};

/**
 * Tests if this Long's value equals zero. This is an alias of {@link Long#isZero}.
 * @returns {boolean}
 */
LongPrototype.eqz = LongPrototype.isZero;

/**
 * Tests if this Long's value is negative.
 * @returns {boolean}
 */
LongPrototype.isNegative = function isNegative() {
    return !this.unsigned && this.high < 0;
};

/**
 * Tests if this Long's value is positive.
 * @returns {boolean}
 */
LongPrototype.isPositive = function isPositive() {
    return this.unsigned || this.high >= 0;
};

/**
 * Tests if this Long's value is odd.
 * @returns {boolean}
 */
LongPrototype.isOdd = function isOdd() {
    return (this.low & 1) === 1;
};

/**
 * Tests if this Long's value is even.
 * @returns {boolean}
 */
LongPrototype.isEven = function isEven() {
    return (this.low & 1) === 0;
};

/**
 * Tests if this Long's value equals the specified's.
 * @param {!Long|number|string} other Other value
 * @returns {boolean}
 */
LongPrototype.equals = function equals(other) {
    if (!isLong(other))
        other = fromValue(other);
    if (this.unsigned !== other.unsigned && (this.high >>> 31) === 1 && (other.high >>> 31) === 1)
        return false;
    return this.high === other.high && this.low === other.low;
};

/**
 * Tests if this Long's value equals the specified's. This is an alias of {@link Long#equals}.
 * @function
 * @param {!Long|number|string} other Other value
 * @returns {boolean}
 */
LongPrototype.eq = LongPrototype.equals;

/**
 * Tests if this Long's value differs from the specified's.
 * @param {!Long|number|string} other Other value
 * @returns {boolean}
 */
LongPrototype.notEquals = function notEquals(other) {
    return !this.eq(/* validates */ other);
};

/**
 * Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}.
 * @function
 * @param {!Long|number|string} other Other value
 * @returns {boolean}
 */
LongPrototype.neq = LongPrototype.notEquals;

/**
 * Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}.
 * @function
 * @param {!Long|number|string} other Other value
 * @returns {boolean}
 */
LongPrototype.ne = LongPrototype.notEquals;

/**
 * Tests if this Long's value is less than the specified's.
 * @param {!Long|number|string} other Other value
 * @returns {boolean}
 */
LongPrototype.lessThan = function lessThan(other) {
    return this.comp(/* validates */ other) < 0;
};

/**
 * Tests if this Long's value is less than the specified's. This is an alias of {@link Long#lessThan}.
 * @function
 * @param {!Long|number|string} other Other value
 * @returns {boolean}
 */
LongPrototype.lt = LongPrototype.lessThan;

/**
 * Tests if this Long's value is less than or equal the specified's.
 * @param {!Long|number|string} other Other value
 * @returns {boolean}
 */
LongPrototype.lessThanOrEqual = function lessThanOrEqual(other) {
    return this.comp(/* validates */ other) <= 0;
};

/**
 * Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}.
 * @function
 * @param {!Long|number|string} other Other value
 * @returns {boolean}
 */
LongPrototype.lte = LongPrototype.lessThanOrEqual;

/**
 * Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}.
 * @function
 * @param {!Long|number|string} other Other value
 * @returns {boolean}
 */
LongPrototype.le = LongPrototype.lessThanOrEqual;

/**
 * Tests if this Long's value is greater than the specified's.
 * @param {!Long|number|string} other Other value
 * @returns {boolean}
 */
LongPrototype.greaterThan = function greaterThan(other) {
    return this.comp(/* validates */ other) > 0;
};

/**
 * Tests if this Long's value is greater than the specified's. This is an alias of {@link Long#greaterThan}.
 * @function
 * @param {!Long|number|string} other Other value
 * @returns {boolean}
 */
LongPrototype.gt = LongPrototype.greaterThan;

/**
 * Tests if this Long's value is greater than or equal the specified's.
 * @param {!Long|number|string} other Other value
 * @returns {boolean}
 */
LongPrototype.greaterThanOrEqual = function greaterThanOrEqual(other) {
    return this.comp(/* validates */ other) >= 0;
};

/**
 * Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}.
 * @function
 * @param {!Long|number|string} other Other value
 * @returns {boolean}
 */
LongPrototype.gte = LongPrototype.greaterThanOrEqual;

/**
 * Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}.
 * @function
 * @param {!Long|number|string} other Other value
 * @returns {boolean}
 */
LongPrototype.ge = LongPrototype.greaterThanOrEqual;

/**
 * Compares this Long's value with the specified's.
 * @param {!Long|number|string} other Other value
 * @returns {number} 0 if they are the same, 1 if the this is greater and -1
 *  if the given one is greater
 */
LongPrototype.compare = function compare(other) {
    if (!isLong(other))
        other = fromValue(other);
    if (this.eq(other))
        return 0;
    var thisNeg = this.isNegative(),
        otherNeg = other.isNegative();
    if (thisNeg && !otherNeg)
        return -1;
    if (!thisNeg && otherNeg)
        return 1;
    // At this point the sign bits are the same
    if (!this.unsigned)
        return this.sub(other).isNegative() ? -1 : 1;
    // Both are positive if at least one is unsigned
    return (other.high >>> 0) > (this.high >>> 0) || (other.high === this.high && (other.low >>> 0) > (this.low >>> 0)) ? -1 : 1;
};

/**
 * Compares this Long's value with the specified's. This is an alias of {@link Long#compare}.
 * @function
 * @param {!Long|number|string} other Other value
 * @returns {number} 0 if they are the same, 1 if the this is greater and -1
 *  if the given one is greater
 */
LongPrototype.comp = LongPrototype.compare;

/**
 * Negates this Long's value.
 * @returns {!Long} Negated Long
 */
LongPrototype.negate = function negate() {
    if (!this.unsigned && this.eq(MIN_VALUE))
        return MIN_VALUE;
    return this.not().add(ONE);
};

/**
 * Negates this Long's value. This is an alias of {@link Long#negate}.
 * @function
 * @returns {!Long} Negated Long
 */
LongPrototype.neg = LongPrototype.negate;

/**
 * Returns the sum of this and the specified Long.
 * @param {!Long|number|string} addend Addend
 * @returns {!Long} Sum
 */
LongPrototype.add = function add(addend) {
    if (!isLong(addend))
        addend = fromValue(addend);

    // Divide each number into 4 chunks of 16 bits, and then sum the chunks.

    var a48 = this.high >>> 16;
    var a32 = this.high & 0xFFFF;
    var a16 = this.low >>> 16;
    var a00 = this.low & 0xFFFF;

    var b48 = addend.high >>> 16;
    var b32 = addend.high & 0xFFFF;
    var b16 = addend.low >>> 16;
    var b00 = addend.low & 0xFFFF;

    var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
    c00 += a00 + b00;
    c16 += c00 >>> 16;
    c00 &= 0xFFFF;
    c16 += a16 + b16;
    c32 += c16 >>> 16;
    c16 &= 0xFFFF;
    c32 += a32 + b32;
    c48 += c32 >>> 16;
    c32 &= 0xFFFF;
    c48 += a48 + b48;
    c48 &= 0xFFFF;
    return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
};

/**
 * Returns the difference of this and the specified Long.
 * @param {!Long|number|string} subtrahend Subtrahend
 * @returns {!Long} Difference
 */
LongPrototype.subtract = function subtract(subtrahend) {
    if (!isLong(subtrahend))
        subtrahend = fromValue(subtrahend);
    return this.add(subtrahend.neg());
};

/**
 * Returns the difference of this and the specified Long. This is an alias of {@link Long#subtract}.
 * @function
 * @param {!Long|number|string} subtrahend Subtrahend
 * @returns {!Long} Difference
 */
LongPrototype.sub = LongPrototype.subtract;

/**
 * Returns the product of this and the specified Long.
 * @param {!Long|number|string} multiplier Multiplier
 * @returns {!Long} Product
 */
LongPrototype.multiply = function multiply(multiplier) {
    if (this.isZero())
        return ZERO;
    if (!isLong(multiplier))
        multiplier = fromValue(multiplier);

    // use wasm support if present
    if (wasm) {
        var low = wasm.mul(this.low,
                           this.high,
                           multiplier.low,
                           multiplier.high);
        return fromBits(low, wasm.get_high(), this.unsigned);
    }

    if (multiplier.isZero())
        return ZERO;
    if (this.eq(MIN_VALUE))
        return multiplier.isOdd() ? MIN_VALUE : ZERO;
    if (multiplier.eq(MIN_VALUE))
        return this.isOdd() ? MIN_VALUE : ZERO;

    if (this.isNegative()) {
        if (multiplier.isNegative())
            return this.neg().mul(multiplier.neg());
        else
            return this.neg().mul(multiplier).neg();
    } else if (multiplier.isNegative())
        return this.mul(multiplier.neg()).neg();

    // If both longs are small, use float multiplication
    if (this.lt(TWO_PWR_24) && multiplier.lt(TWO_PWR_24))
        return fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned);

    // Divide each long into 4 chunks of 16 bits, and then add up 4x4 products.
    // We can skip products that would overflow.

    var a48 = this.high >>> 16;
    var a32 = this.high & 0xFFFF;
    var a16 = this.low >>> 16;
    var a00 = this.low & 0xFFFF;

    var b48 = multiplier.high >>> 16;
    var b32 = multiplier.high & 0xFFFF;
    var b16 = multiplier.low >>> 16;
    var b00 = multiplier.low & 0xFFFF;

    var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
    c00 += a00 * b00;
    c16 += c00 >>> 16;
    c00 &= 0xFFFF;
    c16 += a16 * b00;
    c32 += c16 >>> 16;
    c16 &= 0xFFFF;
    c16 += a00 * b16;
    c32 += c16 >>> 16;
    c16 &= 0xFFFF;
    c32 += a32 * b00;
    c48 += c32 >>> 16;
    c32 &= 0xFFFF;
    c32 += a16 * b16;
    c48 += c32 >>> 16;
    c32 &= 0xFFFF;
    c32 += a00 * b32;
    c48 += c32 >>> 16;
    c32 &= 0xFFFF;
    c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
    c48 &= 0xFFFF;
    return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
};

/**
 * Returns the product of this and the specified Long. This is an alias of {@link Long#multiply}.
 * @function
 * @param {!Long|number|string} multiplier Multiplier
 * @returns {!Long} Product
 */
LongPrototype.mul = LongPrototype.multiply;

/**
 * Returns this Long divided by the specified. The result is signed if this Long is signed or
 *  unsigned if this Long is unsigned.
 * @param {!Long|number|string} divisor Divisor
 * @returns {!Long} Quotient
 */
LongPrototype.divide = function divide(divisor) {
    if (!isLong(divisor))
        divisor = fromValue(divisor);
    if (divisor.isZero())
        throw Error('division by zero');

    // use wasm support if present
    if (wasm) {
        // guard against signed division overflow: the largest
        // negative number / -1 would be 1 larger than the largest
        // positive number, due to two's complement.
        if (!this.unsigned &&
            this.high === -0x80000000 &&
            divisor.low === -1 && divisor.high === -1) {
            // be consistent with non-wasm code path
            return this;
        }
        var low = (this.unsigned ? wasm.div_u : wasm.div_s)(
            this.low,
            this.high,
            divisor.low,
            divisor.high
        );
        return fromBits(low, wasm.get_high(), this.unsigned);
    }

    if (this.isZero())
        return this.unsigned ? UZERO : ZERO;
    var approx, rem, res;
    if (!this.unsigned) {
        // This section is only relevant for signed longs and is derived from the
        // closure library as a whole.
        if (this.eq(MIN_VALUE)) {
            if (divisor.eq(ONE) || divisor.eq(NEG_ONE))
                return MIN_VALUE;  // recall that -MIN_VALUE == MIN_VALUE
            else if (divisor.eq(MIN_VALUE))
                return ONE;
            else {
                // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|.
                var halfThis = this.shr(1);
                approx = halfThis.div(divisor).shl(1);
                if (approx.eq(ZERO)) {
                    return divisor.isNegative() ? ONE : NEG_ONE;
                } else {
                    rem = this.sub(divisor.mul(approx));
                    res = approx.add(rem.div(divisor));
                    return res;
                }
            }
        } else if (divisor.eq(MIN_VALUE))
            return this.unsigned ? UZERO : ZERO;
        if (this.isNegative()) {
            if (divisor.isNegative())
                return this.neg().div(divisor.neg());
            return this.neg().div(divisor).neg();
        } else if (divisor.isNegative())
            return this.div(divisor.neg()).neg();
        res = ZERO;
    } else {
        // The algorithm below has not been made for unsigned longs. It's therefore
        // required to take special care of the MSB prior to running it.
        if (!divisor.unsigned)
            divisor = divisor.toUnsigned();
        if (divisor.gt(this))
            return UZERO;
        if (divisor.gt(this.shru(1))) // 15 >>> 1 = 7 ; with divisor = 8 ; true
            return UONE;
        res = UZERO;
    }

    // Repeat the following until the remainder is less than other:  find a
    // floating-point that approximates remainder / other *from below*, add this
    // into the result, and subtract it from the remainder.  It is critical that
    // the approximate value is less than or equal to the real value so that the
    // remainder never becomes negative.
    rem = this;
    while (rem.gte(divisor)) {
        // Approximate the result of division. This may be a little greater or
        // smaller than the actual value.
        approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber()));

        // We will tweak the approximate result by changing it in the 48-th digit or
        // the smallest non-fractional digit, whichever is larger.
        var log2 = Math.ceil(Math.log(approx) / Math.LN2),
            delta = (log2 <= 48) ? 1 : pow_dbl(2, log2 - 48),

        // Decrease the approximation until it is smaller than the remainder.  Note
        // that if it is too large, the product overflows and is negative.
            approxRes = fromNumber(approx),
            approxRem = approxRes.mul(divisor);
        while (approxRem.isNegative() || approxRem.gt(rem)) {
            approx -= delta;
            approxRes = fromNumber(approx, this.unsigned);
            approxRem = approxRes.mul(divisor);
        }

        // We know the answer can't be zero... and actually, zero would cause
        // infinite recursion since we would make no progress.
        if (approxRes.isZero())
            approxRes = ONE;

        res = res.add(approxRes);
        rem = rem.sub(approxRem);
    }
    return res;
};

/**
 * Returns this Long divided by the specified. This is an alias of {@link Long#divide}.
 * @function
 * @param {!Long|number|string} divisor Divisor
 * @returns {!Long} Quotient
 */
LongPrototype.div = LongPrototype.divide;

/**
 * Returns this Long modulo the specified.
 * @param {!Long|number|string} divisor Divisor
 * @returns {!Long} Remainder
 */
LongPrototype.modulo = function modulo(divisor) {
    if (!isLong(divisor))
        divisor = fromValue(divisor);

    // use wasm support if present
    if (wasm) {
        var low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(
            this.low,
            this.high,
            divisor.low,
            divisor.high
        );
        return fromBits(low, wasm.get_high(), this.unsigned);
    }

    return this.sub(this.div(divisor).mul(divisor));
};

/**
 * Returns this Long modulo the specified. This is an alias of {@link Long#modulo}.
 * @function
 * @param {!Long|number|string} divisor Divisor
 * @returns {!Long} Remainder
 */
LongPrototype.mod = LongPrototype.modulo;

/**
 * Returns this Long modulo the specified. This is an alias of {@link Long#modulo}.
 * @function
 * @param {!Long|number|string} divisor Divisor
 * @returns {!Long} Remainder
 */
LongPrototype.rem = LongPrototype.modulo;

/**
 * Returns the bitwise NOT of this Long.
 * @returns {!Long}
 */
LongPrototype.not = function not() {
    return fromBits(~this.low, ~this.high, this.unsigned);
};

/**
 * Returns the bitwise AND of this Long and the specified.
 * @param {!Long|number|string} other Other Long
 * @returns {!Long}
 */
LongPrototype.and = function and(other) {
    if (!isLong(other))
        other = fromValue(other);
    return fromBits(this.low & other.low, this.high & other.high, this.unsigned);
};

/**
 * Returns the bitwise OR of this Long and the specified.
 * @param {!Long|number|string} other Other Long
 * @returns {!Long}
 */
LongPrototype.or = function or(other) {
    if (!isLong(other))
        other = fromValue(other);
    return fromBits(this.low | other.low, this.high | other.high, this.unsigned);
};

/**
 * Returns the bitwise XOR of this Long and the given one.
 * @param {!Long|number|string} other Other Long
 * @returns {!Long}
 */
LongPrototype.xor = function xor(other) {
    if (!isLong(other))
        other = fromValue(other);
    return fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned);
};

/**
 * Returns this Long with bits shifted to the left by the given amount.
 * @param {number|!Long} numBits Number of bits
 * @returns {!Long} Shifted Long
 */
LongPrototype.shiftLeft = function shiftLeft(numBits) {
    if (isLong(numBits))
        numBits = numBits.toInt();
    if ((numBits &= 63) === 0)
        return this;
    else if (numBits < 32)
        return fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned);
    else
        return fromBits(0, this.low << (numBits - 32), this.unsigned);
};

/**
 * Returns this Long with bits shifted to the left by the given amount. This is an alias of {@link Long#shiftLeft}.
 * @function
 * @param {number|!Long} numBits Number of bits
 * @returns {!Long} Shifted Long
 */
LongPrototype.shl = LongPrototype.shiftLeft;

/**
 * Returns this Long with bits arithmetically shifted to the right by the given amount.
 * @param {number|!Long} numBits Number of bits
 * @returns {!Long} Shifted Long
 */
LongPrototype.shiftRight = function shiftRight(numBits) {
    if (isLong(numBits))
        numBits = numBits.toInt();
    if ((numBits &= 63) === 0)
        return this;
    else if (numBits < 32)
        return fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned);
    else
        return fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned);
};

/**
 * Returns this Long with bits arithmetically shifted to the right by the given amount. This is an alias of {@link Long#shiftRight}.
 * @function
 * @param {number|!Long} numBits Number of bits
 * @returns {!Long} Shifted Long
 */
LongPrototype.shr = LongPrototype.shiftRight;

/**
 * Returns this Long with bits logically shifted to the right by the given amount.
 * @param {number|!Long} numBits Number of bits
 * @returns {!Long} Shifted Long
 */
LongPrototype.shiftRightUnsigned = function shiftRightUnsigned(numBits) {
    if (isLong(numBits))
        numBits = numBits.toInt();
    numBits &= 63;
    if (numBits === 0)
        return this;
    else {
        var high = this.high;
        if (numBits < 32) {
            var low = this.low;
            return fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits, this.unsigned);
        } else if (numBits === 32)
            return fromBits(high, 0, this.unsigned);
        else
            return fromBits(high >>> (numBits - 32), 0, this.unsigned);
    }
};

/**
 * Returns this Long with bits logically shifted to the right by the given amount. This is an alias of {@link Long#shiftRightUnsigned}.
 * @function
 * @param {number|!Long} numBits Number of bits
 * @returns {!Long} Shifted Long
 */
LongPrototype.shru = LongPrototype.shiftRightUnsigned;

/**
 * Returns this Long with bits logically shifted to the right by the given amount. This is an alias of {@link Long#shiftRightUnsigned}.
 * @function
 * @param {number|!Long} numBits Number of bits
 * @returns {!Long} Shifted Long
 */
LongPrototype.shr_u = LongPrototype.shiftRightUnsigned;

/**
 * Converts this Long to signed.
 * @returns {!Long} Signed long
 */
LongPrototype.toSigned = function toSigned() {
    if (!this.unsigned)
        return this;
    return fromBits(this.low, this.high, false);
};

/**
 * Converts this Long to unsigned.
 * @returns {!Long} Unsigned long
 */
LongPrototype.toUnsigned = function toUnsigned() {
    if (this.unsigned)
        return this;
    return fromBits(this.low, this.high, true);
};

/**
 * Converts this Long to its byte representation.
 * @param {boolean=} le Whether little or big endian, defaults to big endian
 * @returns {!Array.<number>} Byte representation
 */
LongPrototype.toBytes = function toBytes(le) {
    return le ? this.toBytesLE() : this.toBytesBE();
};

/**
 * Converts this Long to its little endian byte representation.
 * @returns {!Array.<number>} Little endian byte representation
 */
LongPrototype.toBytesLE = function toBytesLE() {
    var hi = this.high,
        lo = this.low;
    return [
        lo        & 0xff,
        lo >>>  8 & 0xff,
        lo >>> 16 & 0xff,
        lo >>> 24       ,
        hi        & 0xff,
        hi >>>  8 & 0xff,
        hi >>> 16 & 0xff,
        hi >>> 24
    ];
};

/**
 * Converts this Long to its big endian byte representation.
 * @returns {!Array.<number>} Big endian byte representation
 */
LongPrototype.toBytesBE = function toBytesBE() {
    var hi = this.high,
        lo = this.low;
    return [
        hi >>> 24       ,
        hi >>> 16 & 0xff,
        hi >>>  8 & 0xff,
        hi        & 0xff,
        lo >>> 24       ,
        lo >>> 16 & 0xff,
        lo >>>  8 & 0xff,
        lo        & 0xff
    ];
};

/**
 * Creates a Long from its byte representation.
 * @param {!Array.<number>} bytes Byte representation
 * @param {boolean=} unsigned Whether unsigned or not, defaults to signed
 * @param {boolean=} le Whether little or big endian, defaults to big endian
 * @returns {Long} The corresponding Long value
 */
Long.fromBytes = function fromBytes(bytes, unsigned, le) {
    return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned);
};

/**
 * Creates a Long from its little endian byte representation.
 * @param {!Array.<number>} bytes Little endian byte representation
 * @param {boolean=} unsigned Whether unsigned or not, defaults to signed
 * @returns {Long} The corresponding Long value
 */
Long.fromBytesLE = function fromBytesLE(bytes, unsigned) {
    return new Long(
        bytes[0]       |
        bytes[1] <<  8 |
        bytes[2] << 16 |
        bytes[3] << 24,
        bytes[4]       |
        bytes[5] <<  8 |
        bytes[6] << 16 |
        bytes[7] << 24,
        unsigned
    );
};

/**
 * Creates a Long from its big endian byte representation.
 * @param {!Array.<number>} bytes Big endian byte representation
 * @param {boolean=} unsigned Whether unsigned or not, defaults to signed
 * @returns {Long} The corresponding Long value
 */
Long.fromBytesBE = function fromBytesBE(bytes, unsigned) {
    return new Long(
        bytes[4] << 24 |
        bytes[5] << 16 |
        bytes[6] <<  8 |
        bytes[7],
        bytes[0] << 24 |
        bytes[1] << 16 |
        bytes[2] <<  8 |
        bytes[3],
        unsigned
    );
};


/***/ }),

/***/ "./node_modules/onnx-proto/dist/onnx.js":
/*!**********************************************!*\
  !*** ./node_modules/onnx-proto/dist/onnx.js ***!
  \**********************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";
/*eslint-disable block-scoped-var, id-length, no-control-regex, no-magic-numbers, no-prototype-builtins, no-redeclare, no-shadow, no-var, sort-vars*/


var $protobuf = __webpack_require__(/*! protobufjs/minimal */ "./node_modules/protobufjs/minimal.js");

// Common aliases
var $Reader = $protobuf.Reader, $Writer = $protobuf.Writer, $util = $protobuf.util;

// Exported root namespace
var $root = $protobuf.roots["default"] || ($protobuf.roots["default"] = {});

$root.onnx = (function() {

    /**
     * Namespace onnx.
     * @exports onnx
     * @namespace
     */
    var onnx = {};

    /**
     * Version enum.
     * @name onnx.Version
     * @enum {string}
     * @property {number} _START_VERSION=0 _START_VERSION value
     * @property {number} IR_VERSION_2017_10_10=1 IR_VERSION_2017_10_10 value
     * @property {number} IR_VERSION_2017_10_30=2 IR_VERSION_2017_10_30 value
     * @property {number} IR_VERSION_2017_11_3=3 IR_VERSION_2017_11_3 value
     * @property {number} IR_VERSION_2019_1_22=4 IR_VERSION_2019_1_22 value
     * @property {number} IR_VERSION=5 IR_VERSION value
     */
    onnx.Version = (function() {
        var valuesById = {}, values = Object.create(valuesById);
        values[valuesById[0] = "_START_VERSION"] = 0;
        values[valuesById[1] = "IR_VERSION_2017_10_10"] = 1;
        values[valuesById[2] = "IR_VERSION_2017_10_30"] = 2;
        values[valuesById[3] = "IR_VERSION_2017_11_3"] = 3;
        values[valuesById[4] = "IR_VERSION_2019_1_22"] = 4;
        values[valuesById[5] = "IR_VERSION"] = 5;
        return values;
    })();

    onnx.AttributeProto = (function() {

        /**
         * Properties of an AttributeProto.
         * @memberof onnx
         * @interface IAttributeProto
         * @property {string|null} [name] AttributeProto name
         * @property {string|null} [refAttrName] AttributeProto refAttrName
         * @property {string|null} [docString] AttributeProto docString
         * @property {onnx.AttributeProto.AttributeType|null} [type] AttributeProto type
         * @property {number|null} [f] AttributeProto f
         * @property {number|Long|null} [i] AttributeProto i
         * @property {Uint8Array|null} [s] AttributeProto s
         * @property {onnx.ITensorProto|null} [t] AttributeProto t
         * @property {onnx.IGraphProto|null} [g] AttributeProto g
         * @property {Array.<number>|null} [floats] AttributeProto floats
         * @property {Array.<number|Long>|null} [ints] AttributeProto ints
         * @property {Array.<Uint8Array>|null} [strings] AttributeProto strings
         * @property {Array.<onnx.ITensorProto>|null} [tensors] AttributeProto tensors
         * @property {Array.<onnx.IGraphProto>|null} [graphs] AttributeProto graphs
         */

        /**
         * Constructs a new AttributeProto.
         * @memberof onnx
         * @classdesc Represents an AttributeProto.
         * @implements IAttributeProto
         * @constructor
         * @param {onnx.IAttributeProto=} [properties] Properties to set
         */
        function AttributeProto(properties) {
            this.floats = [];
            this.ints = [];
            this.strings = [];
            this.tensors = [];
            this.graphs = [];
            if (properties)
                for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                        this[keys[i]] = properties[keys[i]];
        }

        /**
         * AttributeProto name.
         * @member {string} name
         * @memberof onnx.AttributeProto
         * @instance
         */
        AttributeProto.prototype.name = "";

        /**
         * AttributeProto refAttrName.
         * @member {string} refAttrName
         * @memberof onnx.AttributeProto
         * @instance
         */
        AttributeProto.prototype.refAttrName = "";

        /**
         * AttributeProto docString.
         * @member {string} docString
         * @memberof onnx.AttributeProto
         * @instance
         */
        AttributeProto.prototype.docString = "";

        /**
         * AttributeProto type.
         * @member {onnx.AttributeProto.AttributeType} type
         * @memberof onnx.AttributeProto
         * @instance
         */
        AttributeProto.prototype.type = 0;

        /**
         * AttributeProto f.
         * @member {number} f
         * @memberof onnx.AttributeProto
         * @instance
         */
        AttributeProto.prototype.f = 0;

        /**
         * AttributeProto i.
         * @member {number|Long} i
         * @memberof onnx.AttributeProto
         * @instance
         */
        AttributeProto.prototype.i = $util.Long ? $util.Long.fromBits(0,0,false) : 0;

        /**
         * AttributeProto s.
         * @member {Uint8Array} s
         * @memberof onnx.AttributeProto
         * @instance
         */
        AttributeProto.prototype.s = $util.newBuffer([]);

        /**
         * AttributeProto t.
         * @member {onnx.ITensorProto|null|undefined} t
         * @memberof onnx.AttributeProto
         * @instance
         */
        AttributeProto.prototype.t = null;

        /**
         * AttributeProto g.
         * @member {onnx.IGraphProto|null|undefined} g
         * @memberof onnx.AttributeProto
         * @instance
         */
        AttributeProto.prototype.g = null;

        /**
         * AttributeProto floats.
         * @member {Array.<number>} floats
         * @memberof onnx.AttributeProto
         * @instance
         */
        AttributeProto.prototype.floats = $util.emptyArray;

        /**
         * AttributeProto ints.
         * @member {Array.<number|Long>} ints
         * @memberof onnx.AttributeProto
         * @instance
         */
        AttributeProto.prototype.ints = $util.emptyArray;

        /**
         * AttributeProto strings.
         * @member {Array.<Uint8Array>} strings
         * @memberof onnx.AttributeProto
         * @instance
         */
        AttributeProto.prototype.strings = $util.emptyArray;

        /**
         * AttributeProto tensors.
         * @member {Array.<onnx.ITensorProto>} tensors
         * @memberof onnx.AttributeProto
         * @instance
         */
        AttributeProto.prototype.tensors = $util.emptyArray;

        /**
         * AttributeProto graphs.
         * @member {Array.<onnx.IGraphProto>} graphs
         * @memberof onnx.AttributeProto
         * @instance
         */
        AttributeProto.prototype.graphs = $util.emptyArray;

        /**
         * Creates a new AttributeProto instance using the specified properties.
         * @function create
         * @memberof onnx.AttributeProto
         * @static
         * @param {onnx.IAttributeProto=} [properties] Properties to set
         * @returns {onnx.AttributeProto} AttributeProto instance
         */
        AttributeProto.create = function create(properties) {
            return new AttributeProto(properties);
        };

        /**
         * Encodes the specified AttributeProto message. Does not implicitly {@link onnx.AttributeProto.verify|verify} messages.
         * @function encode
         * @memberof onnx.AttributeProto
         * @static
         * @param {onnx.IAttributeProto} message AttributeProto message or plain object to encode
         * @param {$protobuf.Writer} [writer] Writer to encode to
         * @returns {$protobuf.Writer} Writer
         */
        AttributeProto.encode = function encode(message, writer) {
            if (!writer)
                writer = $Writer.create();
            if (message.name != null && message.hasOwnProperty("name"))
                writer.uint32(/* id 1, wireType 2 =*/10).string(message.name);
            if (message.f != null && message.hasOwnProperty("f"))
                writer.uint32(/* id 2, wireType 5 =*/21).float(message.f);
            if (message.i != null && message.hasOwnProperty("i"))
                writer.uint32(/* id 3, wireType 0 =*/24).int64(message.i);
            if (message.s != null && message.hasOwnProperty("s"))
                writer.uint32(/* id 4, wireType 2 =*/34).bytes(message.s);
            if (message.t != null && message.hasOwnProperty("t"))
                $root.onnx.TensorProto.encode(message.t, writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim();
            if (message.g != null && message.hasOwnProperty("g"))
                $root.onnx.GraphProto.encode(message.g, writer.uint32(/* id 6, wireType 2 =*/50).fork()).ldelim();
            if (message.floats != null && message.floats.length) {
                writer.uint32(/* id 7, wireType 2 =*/58).fork();
                for (var i = 0; i < message.floats.length; ++i)
                    writer.float(message.floats[i]);
                writer.ldelim();
            }
            if (message.ints != null && message.ints.length) {
                writer.uint32(/* id 8, wireType 2 =*/66).fork();
                for (var i = 0; i < message.ints.length; ++i)
                    writer.int64(message.ints[i]);
                writer.ldelim();
            }
            if (message.strings != null && message.strings.length)
                for (var i = 0; i < message.strings.length; ++i)
                    writer.uint32(/* id 9, wireType 2 =*/74).bytes(message.strings[i]);
            if (message.tensors != null && message.tensors.length)
                for (var i = 0; i < message.tensors.length; ++i)
                    $root.onnx.TensorProto.encode(message.tensors[i], writer.uint32(/* id 10, wireType 2 =*/82).fork()).ldelim();
            if (message.graphs != null && message.graphs.length)
                for (var i = 0; i < message.graphs.length; ++i)
                    $root.onnx.GraphProto.encode(message.graphs[i], writer.uint32(/* id 11, wireType 2 =*/90).fork()).ldelim();
            if (message.docString != null && message.hasOwnProperty("docString"))
                writer.uint32(/* id 13, wireType 2 =*/106).string(message.docString);
            if (message.type != null && message.hasOwnProperty("type"))
                writer.uint32(/* id 20, wireType 0 =*/160).int32(message.type);
            if (message.refAttrName != null && message.hasOwnProperty("refAttrName"))
                writer.uint32(/* id 21, wireType 2 =*/170).string(message.refAttrName);
            return writer;
        };

        /**
         * Encodes the specified AttributeProto message, length delimited. Does not implicitly {@link onnx.AttributeProto.verify|verify} messages.
         * @function encodeDelimited
         * @memberof onnx.AttributeProto
         * @static
         * @param {onnx.IAttributeProto} message AttributeProto message or plain object to encode
         * @param {$protobuf.Writer} [writer] Writer to encode to
         * @returns {$protobuf.Writer} Writer
         */
        AttributeProto.encodeDelimited = function encodeDelimited(message, writer) {
            return this.encode(message, writer).ldelim();
        };

        /**
         * Decodes an AttributeProto message from the specified reader or buffer.
         * @function decode
         * @memberof onnx.AttributeProto
         * @static
         * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
         * @param {number} [length] Message length if known beforehand
         * @returns {onnx.AttributeProto} AttributeProto
         * @throws {Error} If the payload is not a reader or valid buffer
         * @throws {$protobuf.util.ProtocolError} If required fields are missing
         */
        AttributeProto.decode = function decode(reader, length) {
            if (!(reader instanceof $Reader))
                reader = $Reader.create(reader);
            var end = length === undefined ? reader.len : reader.pos + length, message = new $root.onnx.AttributeProto();
            while (reader.pos < end) {
                var tag = reader.uint32();
                switch (tag >>> 3) {
                case 1:
                    message.name = reader.string();
                    break;
                case 21:
                    message.refAttrName = reader.string();
                    break;
                case 13:
                    message.docString = reader.string();
                    break;
                case 20:
                    message.type = reader.int32();
                    break;
                case 2:
                    message.f = reader.float();
                    break;
                case 3:
                    message.i = reader.int64();
                    break;
                case 4:
                    message.s = reader.bytes();
                    break;
                case 5:
                    message.t = $root.onnx.TensorProto.decode(reader, reader.uint32());
                    break;
                case 6:
                    message.g = $root.onnx.GraphProto.decode(reader, reader.uint32());
                    break;
                case 7:
                    if (!(message.floats && message.floats.length))
                        message.floats = [];
                    if ((tag & 7) === 2) {
                        var end2 = reader.uint32() + reader.pos;
                        while (reader.pos < end2)
                            message.floats.push(reader.float());
                    } else
                        message.floats.push(reader.float());
                    break;
                case 8:
                    if (!(message.ints && message.ints.length))
                        message.ints = [];
                    if ((tag & 7) === 2) {
                        var end2 = reader.uint32() + reader.pos;
                        while (reader.pos < end2)
                            message.ints.push(reader.int64());
                    } else
                        message.ints.push(reader.int64());
                    break;
                case 9:
                    if (!(message.strings && message.strings.length))
                        message.strings = [];
                    message.strings.push(reader.bytes());
                    break;
                case 10:
                    if (!(message.tensors && message.tensors.length))
                        message.tensors = [];
                    message.tensors.push($root.onnx.TensorProto.decode(reader, reader.uint32()));
                    break;
                case 11:
                    if (!(message.graphs && message.graphs.length))
                        message.graphs = [];
                    message.graphs.push($root.onnx.GraphProto.decode(reader, reader.uint32()));
                    break;
                default:
                    reader.skipType(tag & 7);
                    break;
                }
            }
            return message;
        };

        /**
         * Decodes an AttributeProto message from the specified reader or buffer, length delimited.
         * @function decodeDelimited
         * @memberof onnx.AttributeProto
         * @static
         * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
         * @returns {onnx.AttributeProto} AttributeProto
         * @throws {Error} If the payload is not a reader or valid buffer
         * @throws {$protobuf.util.ProtocolError} If required fields are missing
         */
        AttributeProto.decodeDelimited = function decodeDelimited(reader) {
            if (!(reader instanceof $Reader))
                reader = new $Reader(reader);
            return this.decode(reader, reader.uint32());
        };

        /**
         * Verifies an AttributeProto message.
         * @function verify
         * @memberof onnx.AttributeProto
         * @static
         * @param {Object.<string,*>} message Plain object to verify
         * @returns {string|null} `null` if valid, otherwise the reason why it is not
         */
        AttributeProto.verify = function verify(message) {
            if (typeof message !== "object" || message === null)
                return "object expected";
            if (message.name != null && message.hasOwnProperty("name"))
                if (!$util.isString(message.name))
                    return "name: string expected";
            if (message.refAttrName != null && message.hasOwnProperty("refAttrName"))
                if (!$util.isString(message.refAttrName))
                    return "refAttrName: string expected";
            if (message.docString != null && message.hasOwnProperty("docString"))
                if (!$util.isString(message.docString))
                    return "docString: string expected";
            if (message.type != null && message.hasOwnProperty("type"))
                switch (message.type) {
                default:
                    return "type: enum value expected";
                case 0:
                case 1:
                case 2:
                case 3:
                case 4:
                case 5:
                case 6:
                case 7:
                case 8:
                case 9:
                case 10:
                    break;
                }
            if (message.f != null && message.hasOwnProperty("f"))
                if (typeof message.f !== "number")
                    return "f: number expected";
            if (message.i != null && message.hasOwnProperty("i"))
                if (!$util.isInteger(message.i) && !(message.i && $util.isInteger(message.i.low) && $util.isInteger(message.i.high)))
                    return "i: integer|Long expected";
            if (message.s != null && message.hasOwnProperty("s"))
                if (!(message.s && typeof message.s.length === "number" || $util.isString(message.s)))
                    return "s: buffer expected";
            if (message.t != null && message.hasOwnProperty("t")) {
                var error = $root.onnx.TensorProto.verify(message.t);
                if (error)
                    return "t." + error;
            }
            if (message.g != null && message.hasOwnProperty("g")) {
                var error = $root.onnx.GraphProto.verify(message.g);
                if (error)
                    return "g." + error;
            }
            if (message.floats != null && message.hasOwnProperty("floats")) {
                if (!Array.isArray(message.floats))
                    return "floats: array expected";
                for (var i = 0; i < message.floats.length; ++i)
                    if (typeof message.floats[i] !== "number")
                        return "floats: number[] expected";
            }
            if (message.ints != null && message.hasOwnProperty("ints")) {
                if (!Array.isArray(message.ints))
                    return "ints: array expected";
                for (var i = 0; i < message.ints.length; ++i)
                    if (!$util.isInteger(message.ints[i]) && !(message.ints[i] && $util.isInteger(message.ints[i].low) && $util.isInteger(message.ints[i].high)))
                        return "ints: integer|Long[] expected";
            }
            if (message.strings != null && message.hasOwnProperty("strings")) {
                if (!Array.isArray(message.strings))
                    return "strings: array expected";
                for (var i = 0; i < message.strings.length; ++i)
                    if (!(message.strings[i] && typeof message.strings[i].length === "number" || $util.isString(message.strings[i])))
                        return "strings: buffer[] expected";
            }
            if (message.tensors != null && message.hasOwnProperty("tensors")) {
                if (!Array.isArray(message.tensors))
                    return "tensors: array expected";
                for (var i = 0; i < message.tensors.length; ++i) {
                    var error = $root.onnx.TensorProto.verify(message.tensors[i]);
                    if (error)
                        return "tensors." + error;
                }
            }
            if (message.graphs != null && message.hasOwnProperty("graphs")) {
                if (!Array.isArray(message.graphs))
                    return "graphs: array expected";
                for (var i = 0; i < message.graphs.length; ++i) {
                    var error = $root.onnx.GraphProto.verify(message.graphs[i]);
                    if (error)
                        return "graphs." + error;
                }
            }
            return null;
        };

        /**
         * Creates an AttributeProto message from a plain object. Also converts values to their respective internal types.
         * @function fromObject
         * @memberof onnx.AttributeProto
         * @static
         * @param {Object.<string,*>} object Plain object
         * @returns {onnx.AttributeProto} AttributeProto
         */
        AttributeProto.fromObject = function fromObject(object) {
            if (object instanceof $root.onnx.AttributeProto)
                return object;
            var message = new $root.onnx.AttributeProto();
            if (object.name != null)
                message.name = String(object.name);
            if (object.refAttrName != null)
                message.refAttrName = String(object.refAttrName);
            if (object.docString != null)
                message.docString = String(object.docString);
            switch (object.type) {
            case "UNDEFINED":
            case 0:
                message.type = 0;
                break;
            case "FLOAT":
            case 1:
                message.type = 1;
                break;
            case "INT":
            case 2:
                message.type = 2;
                break;
            case "STRING":
            case 3:
                message.type = 3;
                break;
            case "TENSOR":
            case 4:
                message.type = 4;
                break;
            case "GRAPH":
            case 5:
                message.type = 5;
                break;
            case "FLOATS":
            case 6:
                message.type = 6;
                break;
            case "INTS":
            case 7:
                message.type = 7;
                break;
            case "STRINGS":
            case 8:
                message.type = 8;
                break;
            case "TENSORS":
            case 9:
                message.type = 9;
                break;
            case "GRAPHS":
            case 10:
                message.type = 10;
                break;
            }
            if (object.f != null)
                message.f = Number(object.f);
            if (object.i != null)
                if ($util.Long)
                    (message.i = $util.Long.fromValue(object.i)).unsigned = false;
                else if (typeof object.i === "string")
                    message.i = parseInt(object.i, 10);
                else if (typeof object.i === "number")
                    message.i = object.i;
                else if (typeof object.i === "object")
                    message.i = new $util.LongBits(object.i.low >>> 0, object.i.high >>> 0).toNumber();
            if (object.s != null)
                if (typeof object.s === "string")
                    $util.base64.decode(object.s, message.s = $util.newBuffer($util.base64.length(object.s)), 0);
                else if (object.s.length)
                    message.s = object.s;
            if (object.t != null) {
                if (typeof object.t !== "object")
                    throw TypeError(".onnx.AttributeProto.t: object expected");
                message.t = $root.onnx.TensorProto.fromObject(object.t);
            }
            if (object.g != null) {
                if (typeof object.g !== "object")
                    throw TypeError(".onnx.AttributeProto.g: object expected");
                message.g = $root.onnx.GraphProto.fromObject(object.g);
            }
            if (object.floats) {
                if (!Array.isArray(object.floats))
                    throw TypeError(".onnx.AttributeProto.floats: array expected");
                message.floats = [];
                for (var i = 0; i < object.floats.length; ++i)
                    message.floats[i] = Number(object.floats[i]);
            }
            if (object.ints) {
                if (!Array.isArray(object.ints))
                    throw TypeError(".onnx.AttributeProto.ints: array expected");
                message.ints = [];
                for (var i = 0; i < object.ints.length; ++i)
                    if ($util.Long)
                        (message.ints[i] = $util.Long.fromValue(object.ints[i])).unsigned = false;
                    else if (typeof object.ints[i] === "string")
                        message.ints[i] = parseInt(object.ints[i], 10);
                    else if (typeof object.ints[i] === "number")
                        message.ints[i] = object.ints[i];
                    else if (typeof object.ints[i] === "object")
                        message.ints[i] = new $util.LongBits(object.ints[i].low >>> 0, object.ints[i].high >>> 0).toNumber();
            }
            if (object.strings) {
                if (!Array.isArray(object.strings))
                    throw TypeError(".onnx.AttributeProto.strings: array expected");
                message.strings = [];
                for (var i = 0; i < object.strings.length; ++i)
                    if (typeof object.strings[i] === "string")
                        $util.base64.decode(object.strings[i], message.strings[i] = $util.newBuffer($util.base64.length(object.strings[i])), 0);
                    else if (object.strings[i].length)
                        message.strings[i] = object.strings[i];
            }
            if (object.tensors) {
                if (!Array.isArray(object.tensors))
                    throw TypeError(".onnx.AttributeProto.tensors: array expected");
                message.tensors = [];
                for (var i = 0; i < object.tensors.length; ++i) {
                    if (typeof object.tensors[i] !== "object")
                        throw TypeError(".onnx.AttributeProto.tensors: object expected");
                    message.tensors[i] = $root.onnx.TensorProto.fromObject(object.tensors[i]);
                }
            }
            if (object.graphs) {
                if (!Array.isArray(object.graphs))
                    throw TypeError(".onnx.AttributeProto.graphs: array expected");
                message.graphs = [];
                for (var i = 0; i < object.graphs.length; ++i) {
                    if (typeof object.graphs[i] !== "object")
                        throw TypeError(".onnx.AttributeProto.graphs: object expected");
                    message.graphs[i] = $root.onnx.GraphProto.fromObject(object.graphs[i]);
                }
            }
            return message;
        };

        /**
         * Creates a plain object from an AttributeProto message. Also converts values to other types if specified.
         * @function toObject
         * @memberof onnx.AttributeProto
         * @static
         * @param {onnx.AttributeProto} message AttributeProto
         * @param {$protobuf.IConversionOptions} [options] Conversion options
         * @returns {Object.<string,*>} Plain object
         */
        AttributeProto.toObject = function toObject(message, options) {
            if (!options)
                options = {};
            var object = {};
            if (options.arrays || options.defaults) {
                object.floats = [];
                object.ints = [];
                object.strings = [];
                object.tensors = [];
                object.graphs = [];
            }
            if (options.defaults) {
                object.name = "";
                object.f = 0;
                if ($util.Long) {
                    var long = new $util.Long(0, 0, false);
                    object.i = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long;
                } else
                    object.i = options.longs === String ? "0" : 0;
                if (options.bytes === String)
                    object.s = "";
                else {
                    object.s = [];
                    if (options.bytes !== Array)
                        object.s = $util.newBuffer(object.s);
                }
                object.t = null;
                object.g = null;
                object.docString = "";
                object.type = options.enums === String ? "UNDEFINED" : 0;
                object.refAttrName = "";
            }
            if (message.name != null && message.hasOwnProperty("name"))
                object.name = message.name;
            if (message.f != null && message.hasOwnProperty("f"))
                object.f = options.json && !isFinite(message.f) ? String(message.f) : message.f;
            if (message.i != null && message.hasOwnProperty("i"))
                if (typeof message.i === "number")
                    object.i = options.longs === String ? String(message.i) : message.i;
                else
                    object.i = options.longs === String ? $util.Long.prototype.toString.call(message.i) : options.longs === Number ? new $util.LongBits(message.i.low >>> 0, message.i.high >>> 0).toNumber() : message.i;
            if (message.s != null && message.hasOwnProperty("s"))
                object.s = options.bytes === String ? $util.base64.encode(message.s, 0, message.s.length) : options.bytes === Array ? Array.prototype.slice.call(message.s) : message.s;
            if (message.t != null && message.hasOwnProperty("t"))
                object.t = $root.onnx.TensorProto.toObject(message.t, options);
            if (message.g != null && message.hasOwnProperty("g"))
                object.g = $root.onnx.GraphProto.toObject(message.g, options);
            if (message.floats && message.floats.length) {
                object.floats = [];
                for (var j = 0; j < message.floats.length; ++j)
                    object.floats[j] = options.json && !isFinite(message.floats[j]) ? String(message.floats[j]) : message.floats[j];
            }
            if (message.ints && message.ints.length) {
                object.ints = [];
                for (var j = 0; j < message.ints.length; ++j)
                    if (typeof message.ints[j] === "number")
                        object.ints[j] = options.longs === String ? String(message.ints[j]) : message.ints[j];
                    else
                        object.ints[j] = options.longs === String ? $util.Long.prototype.toString.call(message.ints[j]) : options.longs === Number ? new $util.LongBits(message.ints[j].low >>> 0, message.ints[j].high >>> 0).toNumber() : message.ints[j];
            }
            if (message.strings && message.strings.length) {
                object.strings = [];
                for (var j = 0; j < message.strings.length; ++j)
                    object.strings[j] = options.bytes === String ? $util.base64.encode(message.strings[j], 0, message.strings[j].length) : options.bytes === Array ? Array.prototype.slice.call(message.strings[j]) : message.strings[j];
            }
            if (message.tensors && message.tensors.length) {
                object.tensors = [];
                for (var j = 0; j < message.tensors.length; ++j)
                    object.tensors[j] = $root.onnx.TensorProto.toObject(message.tensors[j], options);
            }
            if (message.graphs && message.graphs.length) {
                object.graphs = [];
                for (var j = 0; j < message.graphs.length; ++j)
                    object.graphs[j] = $root.onnx.GraphProto.toObject(message.graphs[j], options);
            }
            if (message.docString != null && message.hasOwnProperty("docString"))
                object.docString = message.docString;
            if (message.type != null && message.hasOwnProperty("type"))
                object.type = options.enums === String ? $root.onnx.AttributeProto.AttributeType[message.type] : message.type;
            if (message.refAttrName != null && message.hasOwnProperty("refAttrName"))
                object.refAttrName = message.refAttrName;
            return object;
        };

        /**
         * Converts this AttributeProto to JSON.
         * @function toJSON
         * @memberof onnx.AttributeProto
         * @instance
         * @returns {Object.<string,*>} JSON object
         */
        AttributeProto.prototype.toJSON = function toJSON() {
            return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
        };

        /**
         * AttributeType enum.
         * @name onnx.AttributeProto.AttributeType
         * @enum {string}
         * @property {number} UNDEFINED=0 UNDEFINED value
         * @property {number} FLOAT=1 FLOAT value
         * @property {number} INT=2 INT value
         * @property {number} STRING=3 STRING value
         * @property {number} TENSOR=4 TENSOR value
         * @property {number} GRAPH=5 GRAPH value
         * @property {number} FLOATS=6 FLOATS value
         * @property {number} INTS=7 INTS value
         * @property {number} STRINGS=8 STRINGS value
         * @property {number} TENSORS=9 TENSORS value
         * @property {number} GRAPHS=10 GRAPHS value
         */
        AttributeProto.AttributeType = (function() {
            var valuesById = {}, values = Object.create(valuesById);
            values[valuesById[0] = "UNDEFINED"] = 0;
            values[valuesById[1] = "FLOAT"] = 1;
            values[valuesById[2] = "INT"] = 2;
            values[valuesById[3] = "STRING"] = 3;
            values[valuesById[4] = "TENSOR"] = 4;
            values[valuesById[5] = "GRAPH"] = 5;
            values[valuesById[6] = "FLOATS"] = 6;
            values[valuesById[7] = "INTS"] = 7;
            values[valuesById[8] = "STRINGS"] = 8;
            values[valuesById[9] = "TENSORS"] = 9;
            values[valuesById[10] = "GRAPHS"] = 10;
            return values;
        })();

        return AttributeProto;
    })();

    onnx.ValueInfoProto = (function() {

        /**
         * Properties of a ValueInfoProto.
         * @memberof onnx
         * @interface IValueInfoProto
         * @property {string|null} [name] ValueInfoProto name
         * @property {onnx.ITypeProto|null} [type] ValueInfoProto type
         * @property {string|null} [docString] ValueInfoProto docString
         */

        /**
         * Constructs a new ValueInfoProto.
         * @memberof onnx
         * @classdesc Represents a ValueInfoProto.
         * @implements IValueInfoProto
         * @constructor
         * @param {onnx.IValueInfoProto=} [properties] Properties to set
         */
        function ValueInfoProto(properties) {
            if (properties)
                for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                        this[keys[i]] = properties[keys[i]];
        }

        /**
         * ValueInfoProto name.
         * @member {string} name
         * @memberof onnx.ValueInfoProto
         * @instance
         */
        ValueInfoProto.prototype.name = "";

        /**
         * ValueInfoProto type.
         * @member {onnx.ITypeProto|null|undefined} type
         * @memberof onnx.ValueInfoProto
         * @instance
         */
        ValueInfoProto.prototype.type = null;

        /**
         * ValueInfoProto docString.
         * @member {string} docString
         * @memberof onnx.ValueInfoProto
         * @instance
         */
        ValueInfoProto.prototype.docString = "";

        /**
         * Creates a new ValueInfoProto instance using the specified properties.
         * @function create
         * @memberof onnx.ValueInfoProto
         * @static
         * @param {onnx.IValueInfoProto=} [properties] Properties to set
         * @returns {onnx.ValueInfoProto} ValueInfoProto instance
         */
        ValueInfoProto.create = function create(properties) {
            return new ValueInfoProto(properties);
        };

        /**
         * Encodes the specified ValueInfoProto message. Does not implicitly {@link onnx.ValueInfoProto.verify|verify} messages.
         * @function encode
         * @memberof onnx.ValueInfoProto
         * @static
         * @param {onnx.IValueInfoProto} message ValueInfoProto message or plain object to encode
         * @param {$protobuf.Writer} [writer] Writer to encode to
         * @returns {$protobuf.Writer} Writer
         */
        ValueInfoProto.encode = function encode(message, writer) {
            if (!writer)
                writer = $Writer.create();
            if (message.name != null && message.hasOwnProperty("name"))
                writer.uint32(/* id 1, wireType 2 =*/10).string(message.name);
            if (message.type != null && message.hasOwnProperty("type"))
                $root.onnx.TypeProto.encode(message.type, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim();
            if (message.docString != null && message.hasOwnProperty("docString"))
                writer.uint32(/* id 3, wireType 2 =*/26).string(message.docString);
            return writer;
        };

        /**
         * Encodes the specified ValueInfoProto message, length delimited. Does not implicitly {@link onnx.ValueInfoProto.verify|verify} messages.
         * @function encodeDelimited
         * @memberof onnx.ValueInfoProto
         * @static
         * @param {onnx.IValueInfoProto} message ValueInfoProto message or plain object to encode
         * @param {$protobuf.Writer} [writer] Writer to encode to
         * @returns {$protobuf.Writer} Writer
         */
        ValueInfoProto.encodeDelimited = function encodeDelimited(message, writer) {
            return this.encode(message, writer).ldelim();
        };

        /**
         * Decodes a ValueInfoProto message from the specified reader or buffer.
         * @function decode
         * @memberof onnx.ValueInfoProto
         * @static
         * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
         * @param {number} [length] Message length if known beforehand
         * @returns {onnx.ValueInfoProto} ValueInfoProto
         * @throws {Error} If the payload is not a reader or valid buffer
         * @throws {$protobuf.util.ProtocolError} If required fields are missing
         */
        ValueInfoProto.decode = function decode(reader, length) {
            if (!(reader instanceof $Reader))
                reader = $Reader.create(reader);
            var end = length === undefined ? reader.len : reader.pos + length, message = new $root.onnx.ValueInfoProto();
            while (reader.pos < end) {
                var tag = reader.uint32();
                switch (tag >>> 3) {
                case 1:
                    message.name = reader.string();
                    break;
                case 2:
                    message.type = $root.onnx.TypeProto.decode(reader, reader.uint32());
                    break;
                case 3:
                    message.docString = reader.string();
                    break;
                default:
                    reader.skipType(tag & 7);
                    break;
                }
            }
            return message;
        };

        /**
         * Decodes a ValueInfoProto message from the specified reader or buffer, length delimited.
         * @function decodeDelimited
         * @memberof onnx.ValueInfoProto
         * @static
         * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
         * @returns {onnx.ValueInfoProto} ValueInfoProto
         * @throws {Error} If the payload is not a reader or valid buffer
         * @throws {$protobuf.util.ProtocolError} If required fields are missing
         */
        ValueInfoProto.decodeDelimited = function decodeDelimited(reader) {
            if (!(reader instanceof $Reader))
                reader = new $Reader(reader);
            return this.decode(reader, reader.uint32());
        };

        /**
         * Verifies a ValueInfoProto message.
         * @function verify
         * @memberof onnx.ValueInfoProto
         * @static
         * @param {Object.<string,*>} message Plain object to verify
         * @returns {string|null} `null` if valid, otherwise the reason why it is not
         */
        ValueInfoProto.verify = function verify(message) {
            if (typeof message !== "object" || message === null)
                return "object expected";
            if (message.name != null && message.hasOwnProperty("name"))
                if (!$util.isString(message.name))
                    return "name: string expected";
            if (message.type != null && message.hasOwnProperty("type")) {
                var error = $root.onnx.TypeProto.verify(message.type);
                if (error)
                    return "type." + error;
            }
            if (message.docString != null && message.hasOwnProperty("docString"))
                if (!$util.isString(message.docString))
                    return "docString: string expected";
            return null;
        };

        /**
         * Creates a ValueInfoProto message from a plain object. Also converts values to their respective internal types.
         * @function fromObject
         * @memberof onnx.ValueInfoProto
         * @static
         * @param {Object.<string,*>} object Plain object
         * @returns {onnx.ValueInfoProto} ValueInfoProto
         */
        ValueInfoProto.fromObject = function fromObject(object) {
            if (object instanceof $root.onnx.ValueInfoProto)
                return object;
            var message = new $root.onnx.ValueInfoProto();
            if (object.name != null)
                message.name = String(object.name);
            if (object.type != null) {
                if (typeof object.type !== "object")
                    throw TypeError(".onnx.ValueInfoProto.type: object expected");
                message.type = $root.onnx.TypeProto.fromObject(object.type);
            }
            if (object.docString != null)
                message.docString = String(object.docString);
            return message;
        };

        /**
         * Creates a plain object from a ValueInfoProto message. Also converts values to other types if specified.
         * @function toObject
         * @memberof onnx.ValueInfoProto
         * @static
         * @param {onnx.ValueInfoProto} message ValueInfoProto
         * @param {$protobuf.IConversionOptions} [options] Conversion options
         * @returns {Object.<string,*>} Plain object
         */
        ValueInfoProto.toObject = function toObject(message, options) {
            if (!options)
                options = {};
            var object = {};
            if (options.defaults) {
                object.name = "";
                object.type = null;
                object.docString = "";
            }
            if (message.name != null && message.hasOwnProperty("name"))
                object.name = message.name;
            if (message.type != null && message.hasOwnProperty("type"))
                object.type = $root.onnx.TypeProto.toObject(message.type, options);
            if (message.docString != null && message.hasOwnProperty("docString"))
                object.docString = message.docString;
            return object;
        };

        /**
         * Converts this ValueInfoProto to JSON.
         * @function toJSON
         * @memberof onnx.ValueInfoProto
         * @instance
         * @returns {Object.<string,*>} JSON object
         */
        ValueInfoProto.prototype.toJSON = function toJSON() {
            return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
        };

        return ValueInfoProto;
    })();

    onnx.NodeProto = (function() {

        /**
         * Properties of a NodeProto.
         * @memberof onnx
         * @interface INodeProto
         * @property {Array.<string>|null} [input] NodeProto input
         * @property {Array.<string>|null} [output] NodeProto output
         * @property {string|null} [name] NodeProto name
         * @property {string|null} [opType] NodeProto opType
         * @property {string|null} [domain] NodeProto domain
         * @property {Array.<onnx.IAttributeProto>|null} [attribute] NodeProto attribute
         * @property {string|null} [docString] NodeProto docString
         */

        /**
         * Constructs a new NodeProto.
         * @memberof onnx
         * @classdesc Represents a NodeProto.
         * @implements INodeProto
         * @constructor
         * @param {onnx.INodeProto=} [properties] Properties to set
         */
        function NodeProto(properties) {
            this.input = [];
            this.output = [];
            this.attribute = [];
            if (properties)
                for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                        this[keys[i]] = properties[keys[i]];
        }

        /**
         * NodeProto input.
         * @member {Array.<string>} input
         * @memberof onnx.NodeProto
         * @instance
         */
        NodeProto.prototype.input = $util.emptyArray;

        /**
         * NodeProto output.
         * @member {Array.<string>} output
         * @memberof onnx.NodeProto
         * @instance
         */
        NodeProto.prototype.output = $util.emptyArray;

        /**
         * NodeProto name.
         * @member {string} name
         * @memberof onnx.NodeProto
         * @instance
         */
        NodeProto.prototype.name = "";

        /**
         * NodeProto opType.
         * @member {string} opType
         * @memberof onnx.NodeProto
         * @instance
         */
        NodeProto.prototype.opType = "";

        /**
         * NodeProto domain.
         * @member {string} domain
         * @memberof onnx.NodeProto
         * @instance
         */
        NodeProto.prototype.domain = "";

        /**
         * NodeProto attribute.
         * @member {Array.<onnx.IAttributeProto>} attribute
         * @memberof onnx.NodeProto
         * @instance
         */
        NodeProto.prototype.attribute = $util.emptyArray;

        /**
         * NodeProto docString.
         * @member {string} docString
         * @memberof onnx.NodeProto
         * @instance
         */
        NodeProto.prototype.docString = "";

        /**
         * Creates a new NodeProto instance using the specified properties.
         * @function create
         * @memberof onnx.NodeProto
         * @static
         * @param {onnx.INodeProto=} [properties] Properties to set
         * @returns {onnx.NodeProto} NodeProto instance
         */
        NodeProto.create = function create(properties) {
            return new NodeProto(properties);
        };

        /**
         * Encodes the specified NodeProto message. Does not implicitly {@link onnx.NodeProto.verify|verify} messages.
         * @function encode
         * @memberof onnx.NodeProto
         * @static
         * @param {onnx.INodeProto} message NodeProto message or plain object to encode
         * @param {$protobuf.Writer} [writer] Writer to encode to
         * @returns {$protobuf.Writer} Writer
         */
        NodeProto.encode = function encode(message, writer) {
            if (!writer)
                writer = $Writer.create();
            if (message.input != null && message.input.length)
                for (var i = 0; i < message.input.length; ++i)
                    writer.uint32(/* id 1, wireType 2 =*/10).string(message.input[i]);
            if (message.output != null && message.output.length)
                for (var i = 0; i < message.output.length; ++i)
                    writer.uint32(/* id 2, wireType 2 =*/18).string(message.output[i]);
            if (message.name != null && message.hasOwnProperty("name"))
                writer.uint32(/* id 3, wireType 2 =*/26).string(message.name);
            if (message.opType != null && message.hasOwnProperty("opType"))
                writer.uint32(/* id 4, wireType 2 =*/34).string(message.opType);
            if (message.attribute != null && message.attribute.length)
                for (var i = 0; i < message.attribute.length; ++i)
                    $root.onnx.AttributeProto.encode(message.attribute[i], writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim();
            if (message.docString != null && message.hasOwnProperty("docString"))
                writer.uint32(/* id 6, wireType 2 =*/50).string(message.docString);
            if (message.domain != null && message.hasOwnProperty("domain"))
                writer.uint32(/* id 7, wireType 2 =*/58).string(message.domain);
            return writer;
        };

        /**
         * Encodes the specified NodeProto message, length delimited. Does not implicitly {@link onnx.NodeProto.verify|verify} messages.
         * @function encodeDelimited
         * @memberof onnx.NodeProto
         * @static
         * @param {onnx.INodeProto} message NodeProto message or plain object to encode
         * @param {$protobuf.Writer} [writer] Writer to encode to
         * @returns {$protobuf.Writer} Writer
         */
        NodeProto.encodeDelimited = function encodeDelimited(message, writer) {
            return this.encode(message, writer).ldelim();
        };

        /**
         * Decodes a NodeProto message from the specified reader or buffer.
         * @function decode
         * @memberof onnx.NodeProto
         * @static
         * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
         * @param {number} [length] Message length if known beforehand
         * @returns {onnx.NodeProto} NodeProto
         * @throws {Error} If the payload is not a reader or valid buffer
         * @throws {$protobuf.util.ProtocolError} If required fields are missing
         */
        NodeProto.decode = function decode(reader, length) {
            if (!(reader instanceof $Reader))
                reader = $Reader.create(reader);
            var end = length === undefined ? reader.len : reader.pos + length, message = new $root.onnx.NodeProto();
            while (reader.pos < end) {
                var tag = reader.uint32();
                switch (tag >>> 3) {
                case 1:
                    if (!(message.input && message.input.length))
                        message.input = [];
                    message.input.push(reader.string());
                    break;
                case 2:
                    if (!(message.output && message.output.length))
                        message.output = [];
                    message.output.push(reader.string());
                    break;
                case 3:
                    message.name = reader.string();
                    break;
                case 4:
                    message.opType = reader.string();
                    break;
                case 7:
                    message.domain = reader.string();
                    break;
                case 5:
                    if (!(message.attribute && message.attribute.length))
                        message.attribute = [];
                    message.attribute.push($root.onnx.AttributeProto.decode(reader, reader.uint32()));
                    break;
                case 6:
                    message.docString = reader.string();
                    break;
                default:
                    reader.skipType(tag & 7);
                    break;
                }
            }
            return message;
        };

        /**
         * Decodes a NodeProto message from the specified reader or buffer, length delimited.
         * @function decodeDelimited
         * @memberof onnx.NodeProto
         * @static
         * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
         * @returns {onnx.NodeProto} NodeProto
         * @throws {Error} If the payload is not a reader or valid buffer
         * @throws {$protobuf.util.ProtocolError} If required fields are missing
         */
        NodeProto.decodeDelimited = function decodeDelimited(reader) {
            if (!(reader instanceof $Reader))
                reader = new $Reader(reader);
            return this.decode(reader, reader.uint32());
        };

        /**
         * Verifies a NodeProto message.
         * @function verify
         * @memberof onnx.NodeProto
         * @static
         * @param {Object.<string,*>} message Plain object to verify
         * @returns {string|null} `null` if valid, otherwise the reason why it is not
         */
        NodeProto.verify = function verify(message) {
            if (typeof message !== "object" || message === null)
                return "object expected";
            if (message.input != null && message.hasOwnProperty("input")) {
                if (!Array.isArray(message.input))
                    return "input: array expected";
                for (var i = 0; i < message.input.length; ++i)
                    if (!$util.isString(message.input[i]))
                        return "input: string[] expected";
            }
            if (message.output != null && message.hasOwnProperty("output")) {
                if (!Array.isArray(message.output))
                    return "output: array expected";
                for (var i = 0; i < message.output.length; ++i)
                    if (!$util.isString(message.output[i]))
                        return "output: string[] expected";
            }
            if (message.name != null && message.hasOwnProperty("name"))
                if (!$util.isString(message.name))
                    return "name: string expected";
            if (message.opType != null && message.hasOwnProperty("opType"))
                if (!$util.isString(message.opType))
                    return "opType: string expected";
            if (message.domain != null && message.hasOwnProperty("domain"))
                if (!$util.isString(message.domain))
                    return "domain: string expected";
            if (message.attribute != null && message.hasOwnProperty("attribute")) {
                if (!Array.isArray(message.attribute))
                    return "attribute: array expected";
                for (var i = 0; i < message.attribute.length; ++i) {
                    var error = $root.onnx.AttributeProto.verify(message.attribute[i]);
                    if (error)
                        return "attribute." + error;
                }
            }
            if (message.docString != null && message.hasOwnProperty("docString"))
                if (!$util.isString(message.docString))
                    return "docString: string expected";
            return null;
        };

        /**
         * Creates a NodeProto message from a plain object. Also converts values to their respective internal types.
         * @function fromObject
         * @memberof onnx.NodeProto
         * @static
         * @param {Object.<string,*>} object Plain object
         * @returns {onnx.NodeProto} NodeProto
         */
        NodeProto.fromObject = function fromObject(object) {
            if (object instanceof $root.onnx.NodeProto)
                return object;
            var message = new $root.onnx.NodeProto();
            if (object.input) {
                if (!Array.isArray(object.input))
                    throw TypeError(".onnx.NodeProto.input: array expected");
                message.input = [];
                for (var i = 0; i < object.input.length; ++i)
                    message.input[i] = String(object.input[i]);
            }
            if (object.output) {
                if (!Array.isArray(object.output))
                    throw TypeError(".onnx.NodeProto.output: array expected");
                message.output = [];
                for (var i = 0; i < object.output.length; ++i)
                    message.output[i] = String(object.output[i]);
            }
            if (object.name != null)
                message.name = String(object.name);
            if (object.opType != null)
                message.opType = String(object.opType);
            if (object.domain != null)
                message.domain = String(object.domain);
            if (object.attribute) {
                if (!Array.isArray(object.attribute))
                    throw TypeError(".onnx.NodeProto.attribute: array expected");
                message.attribute = [];
                for (var i = 0; i < object.attribute.length; ++i) {
                    if (typeof object.attribute[i] !== "object")
                        throw TypeError(".onnx.NodeProto.attribute: object expected");
                    message.attribute[i] = $root.onnx.AttributeProto.fromObject(object.attribute[i]);
                }
            }
            if (object.docString != null)
                message.docString = String(object.docString);
            return message;
        };

        /**
         * Creates a plain object from a NodeProto message. Also converts values to other types if specified.
         * @function toObject
         * @memberof onnx.NodeProto
         * @static
         * @param {onnx.NodeProto} message NodeProto
         * @param {$protobuf.IConversionOptions} [options] Conversion options
         * @returns {Object.<string,*>} Plain object
         */
        NodeProto.toObject = function toObject(message, options) {
            if (!options)
                options = {};
            var object = {};
            if (options.arrays || options.defaults) {
                object.input = [];
                object.output = [];
                object.attribute = [];
            }
            if (options.defaults) {
                object.name = "";
                object.opType = "";
                object.docString = "";
                object.domain = "";
            }
            if (message.input && message.input.length) {
                object.input = [];
                for (var j = 0; j < message.input.length; ++j)
                    object.input[j] = message.input[j];
            }
            if (message.output && message.output.length) {
                object.output = [];
                for (var j = 0; j < message.output.length; ++j)
                    object.output[j] = message.output[j];
            }
            if (message.name != null && message.hasOwnProperty("name"))
                object.name = message.name;
            if (message.opType != null && message.hasOwnProperty("opType"))
                object.opType = message.opType;
            if (message.attribute && message.attribute.length) {
                object.attribute = [];
                for (var j = 0; j < message.attribute.length; ++j)
                    object.attribute[j] = $root.onnx.AttributeProto.toObject(message.attribute[j], options);
            }
            if (message.docString != null && message.hasOwnProperty("docString"))
                object.docString = message.docString;
            if (message.domain != null && message.hasOwnProperty("domain"))
                object.domain = message.domain;
            return object;
        };

        /**
         * Converts this NodeProto to JSON.
         * @function toJSON
         * @memberof onnx.NodeProto
         * @instance
         * @returns {Object.<string,*>} JSON object
         */
        NodeProto.prototype.toJSON = function toJSON() {
            return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
        };

        return NodeProto;
    })();

    onnx.ModelProto = (function() {

        /**
         * Properties of a ModelProto.
         * @memberof onnx
         * @interface IModelProto
         * @property {number|Long|null} [irVersion] ModelProto irVersion
         * @property {Array.<onnx.IOperatorSetIdProto>|null} [opsetImport] ModelProto opsetImport
         * @property {string|null} [producerName] ModelProto producerName
         * @property {string|null} [producerVersion] ModelProto producerVersion
         * @property {string|null} [domain] ModelProto domain
         * @property {number|Long|null} [modelVersion] ModelProto modelVersion
         * @property {string|null} [docString] ModelProto docString
         * @property {onnx.IGraphProto|null} [graph] ModelProto graph
         * @property {Array.<onnx.IStringStringEntryProto>|null} [metadataProps] ModelProto metadataProps
         */

        /**
         * Constructs a new ModelProto.
         * @memberof onnx
         * @classdesc Represents a ModelProto.
         * @implements IModelProto
         * @constructor
         * @param {onnx.IModelProto=} [properties] Properties to set
         */
        function ModelProto(properties) {
            this.opsetImport = [];
            this.metadataProps = [];
            if (properties)
                for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                        this[keys[i]] = properties[keys[i]];
        }

        /**
         * ModelProto irVersion.
         * @member {number|Long} irVersion
         * @memberof onnx.ModelProto
         * @instance
         */
        ModelProto.prototype.irVersion = $util.Long ? $util.Long.fromBits(0,0,false) : 0;

        /**
         * ModelProto opsetImport.
         * @member {Array.<onnx.IOperatorSetIdProto>} opsetImport
         * @memberof onnx.ModelProto
         * @instance
         */
        ModelProto.prototype.opsetImport = $util.emptyArray;

        /**
         * ModelProto producerName.
         * @member {string} producerName
         * @memberof onnx.ModelProto
         * @instance
         */
        ModelProto.prototype.producerName = "";

        /**
         * ModelProto producerVersion.
         * @member {string} producerVersion
         * @memberof onnx.ModelProto
         * @instance
         */
        ModelProto.prototype.producerVersion = "";

        /**
         * ModelProto domain.
         * @member {string} domain
         * @memberof onnx.ModelProto
         * @instance
         */
        ModelProto.prototype.domain = "";

        /**
         * ModelProto modelVersion.
         * @member {number|Long} modelVersion
         * @memberof onnx.ModelProto
         * @instance
         */
        ModelProto.prototype.modelVersion = $util.Long ? $util.Long.fromBits(0,0,false) : 0;

        /**
         * ModelProto docString.
         * @member {string} docString
         * @memberof onnx.ModelProto
         * @instance
         */
        ModelProto.prototype.docString = "";

        /**
         * ModelProto graph.
         * @member {onnx.IGraphProto|null|undefined} graph
         * @memberof onnx.ModelProto
         * @instance
         */
        ModelProto.prototype.graph = null;

        /**
         * ModelProto metadataProps.
         * @member {Array.<onnx.IStringStringEntryProto>} metadataProps
         * @memberof onnx.ModelProto
         * @instance
         */
        ModelProto.prototype.metadataProps = $util.emptyArray;

        /**
         * Creates a new ModelProto instance using the specified properties.
         * @function create
         * @memberof onnx.ModelProto
         * @static
         * @param {onnx.IModelProto=} [properties] Properties to set
         * @returns {onnx.ModelProto} ModelProto instance
         */
        ModelProto.create = function create(properties) {
            return new ModelProto(properties);
        };

        /**
         * Encodes the specified ModelProto message. Does not implicitly {@link onnx.ModelProto.verify|verify} messages.
         * @function encode
         * @memberof onnx.ModelProto
         * @static
         * @param {onnx.IModelProto} message ModelProto message or plain object to encode
         * @param {$protobuf.Writer} [writer] Writer to encode to
         * @returns {$protobuf.Writer} Writer
         */
        ModelProto.encode = function encode(message, writer) {
            if (!writer)
                writer = $Writer.create();
            if (message.irVersion != null && message.hasOwnProperty("irVersion"))
                writer.uint32(/* id 1, wireType 0 =*/8).int64(message.irVersion);
            if (message.producerName != null && message.hasOwnProperty("producerName"))
                writer.uint32(/* id 2, wireType 2 =*/18).string(message.producerName);
            if (message.producerVersion != null && message.hasOwnProperty("producerVersion"))
                writer.uint32(/* id 3, wireType 2 =*/26).string(message.producerVersion);
            if (message.domain != null && message.hasOwnProperty("domain"))
                writer.uint32(/* id 4, wireType 2 =*/34).string(message.domain);
            if (message.modelVersion != null && message.hasOwnProperty("modelVersion"))
                writer.uint32(/* id 5, wireType 0 =*/40).int64(message.modelVersion);
            if (message.docString != null && message.hasOwnProperty("docString"))
                writer.uint32(/* id 6, wireType 2 =*/50).string(message.docString);
            if (message.graph != null && message.hasOwnProperty("graph"))
                $root.onnx.GraphProto.encode(message.graph, writer.uint32(/* id 7, wireType 2 =*/58).fork()).ldelim();
            if (message.opsetImport != null && message.opsetImport.length)
                for (var i = 0; i < message.opsetImport.length; ++i)
                    $root.onnx.OperatorSetIdProto.encode(message.opsetImport[i], writer.uint32(/* id 8, wireType 2 =*/66).fork()).ldelim();
            if (message.metadataProps != null && message.metadataProps.length)
                for (var i = 0; i < message.metadataProps.length; ++i)
                    $root.onnx.StringStringEntryProto.encode(message.metadataProps[i], writer.uint32(/* id 14, wireType 2 =*/114).fork()).ldelim();
            return writer;
        };

        /**
         * Encodes the specified ModelProto message, length delimited. Does not implicitly {@link onnx.ModelProto.verify|verify} messages.
         * @function encodeDelimited
         * @memberof onnx.ModelProto
         * @static
         * @param {onnx.IModelProto} message ModelProto message or plain object to encode
         * @param {$protobuf.Writer} [writer] Writer to encode to
         * @returns {$protobuf.Writer} Writer
         */
        ModelProto.encodeDelimited = function encodeDelimited(message, writer) {
            return this.encode(message, writer).ldelim();
        };

        /**
         * Decodes a ModelProto message from the specified reader or buffer.
         * @function decode
         * @memberof onnx.ModelProto
         * @static
         * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
         * @param {number} [length] Message length if known beforehand
         * @returns {onnx.ModelProto} ModelProto
         * @throws {Error} If the payload is not a reader or valid buffer
         * @throws {$protobuf.util.ProtocolError} If required fields are missing
         */
        ModelProto.decode = function decode(reader, length) {
            if (!(reader instanceof $Reader))
                reader = $Reader.create(reader);
            var end = length === undefined ? reader.len : reader.pos + length, message = new $root.onnx.ModelProto();
            while (reader.pos < end) {
                var tag = reader.uint32();
                switch (tag >>> 3) {
                case 1:
                    message.irVersion = reader.int64();
                    break;
                case 8:
                    if (!(message.opsetImport && message.opsetImport.length))
                        message.opsetImport = [];
                    message.opsetImport.push($root.onnx.OperatorSetIdProto.decode(reader, reader.uint32()));
                    break;
                case 2:
                    message.producerName = reader.string();
                    break;
                case 3:
                    message.producerVersion = reader.string();
                    break;
                case 4:
                    message.domain = reader.string();
                    break;
                case 5:
                    message.modelVersion = reader.int64();
                    break;
                case 6:
                    message.docString = reader.string();
                    break;
                case 7:
                    message.graph = $root.onnx.GraphProto.decode(reader, reader.uint32());
                    break;
                case 14:
                    if (!(message.metadataProps && message.metadataProps.length))
                        message.metadataProps = [];
                    message.metadataProps.push($root.onnx.StringStringEntryProto.decode(reader, reader.uint32()));
                    break;
                default:
                    reader.skipType(tag & 7);
                    break;
                }
            }
            return message;
        };

        /**
         * Decodes a ModelProto message from the specified reader or buffer, length delimited.
         * @function decodeDelimited
         * @memberof onnx.ModelProto
         * @static
         * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
         * @returns {onnx.ModelProto} ModelProto
         * @throws {Error} If the payload is not a reader or valid buffer
         * @throws {$protobuf.util.ProtocolError} If required fields are missing
         */
        ModelProto.decodeDelimited = function decodeDelimited(reader) {
            if (!(reader instanceof $Reader))
                reader = new $Reader(reader);
            return this.decode(reader, reader.uint32());
        };

        /**
         * Verifies a ModelProto message.
         * @function verify
         * @memberof onnx.ModelProto
         * @static
         * @param {Object.<string,*>} message Plain object to verify
         * @returns {string|null} `null` if valid, otherwise the reason why it is not
         */
        ModelProto.verify = function verify(message) {
            if (typeof message !== "object" || message === null)
                return "object expected";
            if (message.irVersion != null && message.hasOwnProperty("irVersion"))
                if (!$util.isInteger(message.irVersion) && !(message.irVersion && $util.isInteger(message.irVersion.low) && $util.isInteger(message.irVersion.high)))
                    return "irVersion: integer|Long expected";
            if (message.opsetImport != null && message.hasOwnProperty("opsetImport")) {
                if (!Array.isArray(message.opsetImport))
                    return "opsetImport: array expected";
                for (var i = 0; i < message.opsetImport.length; ++i) {
                    var error = $root.onnx.OperatorSetIdProto.verify(message.opsetImport[i]);
                    if (error)
                        return "opsetImport." + error;
                }
            }
            if (message.producerName != null && message.hasOwnProperty("producerName"))
                if (!$util.isString(message.producerName))
                    return "producerName: string expected";
            if (message.producerVersion != null && message.hasOwnProperty("producerVersion"))
                if (!$util.isString(message.producerVersion))
                    return "producerVersion: string expected";
            if (message.domain != null && message.hasOwnProperty("domain"))
                if (!$util.isString(message.domain))
                    return "domain: string expected";
            if (message.modelVersion != null && message.hasOwnProperty("modelVersion"))
                if (!$util.isInteger(message.modelVersion) && !(message.modelVersion && $util.isInteger(message.modelVersion.low) && $util.isInteger(message.modelVersion.high)))
                    return "modelVersion: integer|Long expected";
            if (message.docString != null && message.hasOwnProperty("docString"))
                if (!$util.isString(message.docString))
                    return "docString: string expected";
            if (message.graph != null && message.hasOwnProperty("graph")) {
                var error = $root.onnx.GraphProto.verify(message.graph);
                if (error)
                    return "graph." + error;
            }
            if (message.metadataProps != null && message.hasOwnProperty("metadataProps")) {
                if (!Array.isArray(message.metadataProps))
                    return "metadataProps: array expected";
                for (var i = 0; i < message.metadataProps.length; ++i) {
                    var error = $root.onnx.StringStringEntryProto.verify(message.metadataProps[i]);
                    if (error)
                        return "metadataProps." + error;
                }
            }
            return null;
        };

        /**
         * Creates a ModelProto message from a plain object. Also converts values to their respective internal types.
         * @function fromObject
         * @memberof onnx.ModelProto
         * @static
         * @param {Object.<string,*>} object Plain object
         * @returns {onnx.ModelProto} ModelProto
         */
        ModelProto.fromObject = function fromObject(object) {
            if (object instanceof $root.onnx.ModelProto)
                return object;
            var message = new $root.onnx.ModelProto();
            if (object.irVersion != null)
                if ($util.Long)
                    (message.irVersion = $util.Long.fromValue(object.irVersion)).unsigned = false;
                else if (typeof object.irVersion === "string")
                    message.irVersion = parseInt(object.irVersion, 10);
                else if (typeof object.irVersion === "number")
                    message.irVersion = object.irVersion;
                else if (typeof object.irVersion === "object")
                    message.irVersion = new $util.LongBits(object.irVersion.low >>> 0, object.irVersion.high >>> 0).toNumber();
            if (object.opsetImport) {
                if (!Array.isArray(object.opsetImport))
                    throw TypeError(".onnx.ModelProto.opsetImport: array expected");
                message.opsetImport = [];
                for (var i = 0; i < object.opsetImport.length; ++i) {
                    if (typeof object.opsetImport[i] !== "object")
                        throw TypeError(".onnx.ModelProto.opsetImport: object expected");
                    message.opsetImport[i] = $root.onnx.OperatorSetIdProto.fromObject(object.opsetImport[i]);
                }
            }
            if (object.producerName != null)
                message.producerName = String(object.producerName);
            if (object.producerVersion != null)
                message.producerVersion = String(object.producerVersion);
            if (object.domain != null)
                message.domain = String(object.domain);
            if (object.modelVersion != null)
                if ($util.Long)
                    (message.modelVersion = $util.Long.fromValue(object.modelVersion)).unsigned = false;
                else if (typeof object.modelVersion === "string")
                    message.modelVersion = parseInt(object.modelVersion, 10);
                else if (typeof object.modelVersion === "number")
                    message.modelVersion = object.modelVersion;
                else if (typeof object.modelVersion === "object")
                    message.modelVersion = new $util.LongBits(object.modelVersion.low >>> 0, object.modelVersion.high >>> 0).toNumber();
            if (object.docString != null)
                message.docString = String(object.docString);
            if (object.graph != null) {
                if (typeof object.graph !== "object")
                    throw TypeError(".onnx.ModelProto.graph: object expected");
                message.graph = $root.onnx.GraphProto.fromObject(object.graph);
            }
            if (object.metadataProps) {
                if (!Array.isArray(object.metadataProps))
                    throw TypeError(".onnx.ModelProto.metadataProps: array expected");
                message.metadataProps = [];
                for (var i = 0; i < object.metadataProps.length; ++i) {
                    if (typeof object.metadataProps[i] !== "object")
                        throw TypeError(".onnx.ModelProto.metadataProps: object expected");
                    message.metadataProps[i] = $root.onnx.StringStringEntryProto.fromObject(object.metadataProps[i]);
                }
            }
            return message;
        };

        /**
         * Creates a plain object from a ModelProto message. Also converts values to other types if specified.
         * @function toObject
         * @memberof onnx.ModelProto
         * @static
         * @param {onnx.ModelProto} message ModelProto
         * @param {$protobuf.IConversionOptions} [options] Conversion options
         * @returns {Object.<string,*>} Plain object
         */
        ModelProto.toObject = function toObject(message, options) {
            if (!options)
                options = {};
            var object = {};
            if (options.arrays || options.defaults) {
                object.opsetImport = [];
                object.metadataProps = [];
            }
            if (options.defaults) {
                if ($util.Long) {
                    var long = new $util.Long(0, 0, false);
                    object.irVersion = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long;
                } else
                    object.irVersion = options.longs === String ? "0" : 0;
                object.producerName = "";
                object.producerVersion = "";
                object.domain = "";
                if ($util.Long) {
                    var long = new $util.Long(0, 0, false);
                    object.modelVersion = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long;
                } else
                    object.modelVersion = options.longs === String ? "0" : 0;
                object.docString = "";
                object.graph = null;
            }
            if (message.irVersion != null && message.hasOwnProperty("irVersion"))
                if (typeof message.irVersion === "number")
                    object.irVersion = options.longs === String ? String(message.irVersion) : message.irVersion;
                else
                    object.irVersion = options.longs === String ? $util.Long.prototype.toString.call(message.irVersion) : options.longs === Number ? new $util.LongBits(message.irVersion.low >>> 0, message.irVersion.high >>> 0).toNumber() : message.irVersion;
            if (message.producerName != null && message.hasOwnProperty("producerName"))
                object.producerName = message.producerName;
            if (message.producerVersion != null && message.hasOwnProperty("producerVersion"))
                object.producerVersion = message.producerVersion;
            if (message.domain != null && message.hasOwnProperty("domain"))
                object.domain = message.domain;
            if (message.modelVersion != null && message.hasOwnProperty("modelVersion"))
                if (typeof message.modelVersion === "number")
                    object.modelVersion = options.longs === String ? String(message.modelVersion) : message.modelVersion;
                else
                    object.modelVersion = options.longs === String ? $util.Long.prototype.toString.call(message.modelVersion) : options.longs === Number ? new $util.LongBits(message.modelVersion.low >>> 0, message.modelVersion.high >>> 0).toNumber() : message.modelVersion;
            if (message.docString != null && message.hasOwnProperty("docString"))
                object.docString = message.docString;
            if (message.graph != null && message.hasOwnProperty("graph"))
                object.graph = $root.onnx.GraphProto.toObject(message.graph, options);
            if (message.opsetImport && message.opsetImport.length) {
                object.opsetImport = [];
                for (var j = 0; j < message.opsetImport.length; ++j)
                    object.opsetImport[j] = $root.onnx.OperatorSetIdProto.toObject(message.opsetImport[j], options);
            }
            if (message.metadataProps && message.metadataProps.length) {
                object.metadataProps = [];
                for (var j = 0; j < message.metadataProps.length; ++j)
                    object.metadataProps[j] = $root.onnx.StringStringEntryProto.toObject(message.metadataProps[j], options);
            }
            return object;
        };

        /**
         * Converts this ModelProto to JSON.
         * @function toJSON
         * @memberof onnx.ModelProto
         * @instance
         * @returns {Object.<string,*>} JSON object
         */
        ModelProto.prototype.toJSON = function toJSON() {
            return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
        };

        return ModelProto;
    })();

    onnx.StringStringEntryProto = (function() {

        /**
         * Properties of a StringStringEntryProto.
         * @memberof onnx
         * @interface IStringStringEntryProto
         * @property {string|null} [key] StringStringEntryProto key
         * @property {string|null} [value] StringStringEntryProto value
         */

        /**
         * Constructs a new StringStringEntryProto.
         * @memberof onnx
         * @classdesc Represents a StringStringEntryProto.
         * @implements IStringStringEntryProto
         * @constructor
         * @param {onnx.IStringStringEntryProto=} [properties] Properties to set
         */
        function StringStringEntryProto(properties) {
            if (properties)
                for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                        this[keys[i]] = properties[keys[i]];
        }

        /**
         * StringStringEntryProto key.
         * @member {string} key
         * @memberof onnx.StringStringEntryProto
         * @instance
         */
        StringStringEntryProto.prototype.key = "";

        /**
         * StringStringEntryProto value.
         * @member {string} value
         * @memberof onnx.StringStringEntryProto
         * @instance
         */
        StringStringEntryProto.prototype.value = "";

        /**
         * Creates a new StringStringEntryProto instance using the specified properties.
         * @function create
         * @memberof onnx.StringStringEntryProto
         * @static
         * @param {onnx.IStringStringEntryProto=} [properties] Properties to set
         * @returns {onnx.StringStringEntryProto} StringStringEntryProto instance
         */
        StringStringEntryProto.create = function create(properties) {
            return new StringStringEntryProto(properties);
        };

        /**
         * Encodes the specified StringStringEntryProto message. Does not implicitly {@link onnx.StringStringEntryProto.verify|verify} messages.
         * @function encode
         * @memberof onnx.StringStringEntryProto
         * @static
         * @param {onnx.IStringStringEntryProto} message StringStringEntryProto message or plain object to encode
         * @param {$protobuf.Writer} [writer] Writer to encode to
         * @returns {$protobuf.Writer} Writer
         */
        StringStringEntryProto.encode = function encode(message, writer) {
            if (!writer)
                writer = $Writer.create();
            if (message.key != null && message.hasOwnProperty("key"))
                writer.uint32(/* id 1, wireType 2 =*/10).string(message.key);
            if (message.value != null && message.hasOwnProperty("value"))
                writer.uint32(/* id 2, wireType 2 =*/18).string(message.value);
            return writer;
        };

        /**
         * Encodes the specified StringStringEntryProto message, length delimited. Does not implicitly {@link onnx.StringStringEntryProto.verify|verify} messages.
         * @function encodeDelimited
         * @memberof onnx.StringStringEntryProto
         * @static
         * @param {onnx.IStringStringEntryProto} message StringStringEntryProto message or plain object to encode
         * @param {$protobuf.Writer} [writer] Writer to encode to
         * @returns {$protobuf.Writer} Writer
         */
        StringStringEntryProto.encodeDelimited = function encodeDelimited(message, writer) {
            return this.encode(message, writer).ldelim();
        };

        /**
         * Decodes a StringStringEntryProto message from the specified reader or buffer.
         * @function decode
         * @memberof onnx.StringStringEntryProto
         * @static
         * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
         * @param {number} [length] Message length if known beforehand
         * @returns {onnx.StringStringEntryProto} StringStringEntryProto
         * @throws {Error} If the payload is not a reader or valid buffer
         * @throws {$protobuf.util.ProtocolError} If required fields are missing
         */
        StringStringEntryProto.decode = function decode(reader, length) {
            if (!(reader instanceof $Reader))
                reader = $Reader.create(reader);
            var end = length === undefined ? reader.len : reader.pos + length, message = new $root.onnx.StringStringEntryProto();
            while (reader.pos < end) {
                var tag = reader.uint32();
                switch (tag >>> 3) {
                case 1:
                    message.key = reader.string();
                    break;
                case 2:
                    message.value = reader.string();
                    break;
                default:
                    reader.skipType(tag & 7);
                    break;
                }
            }
            return message;
        };

        /**
         * Decodes a StringStringEntryProto message from the specified reader or buffer, length delimited.
         * @function decodeDelimited
         * @memberof onnx.StringStringEntryProto
         * @static
         * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
         * @returns {onnx.StringStringEntryProto} StringStringEntryProto
         * @throws {Error} If the payload is not a reader or valid buffer
         * @throws {$protobuf.util.ProtocolError} If required fields are missing
         */
        StringStringEntryProto.decodeDelimited = function decodeDelimited(reader) {
            if (!(reader instanceof $Reader))
                reader = new $Reader(reader);
            return this.decode(reader, reader.uint32());
        };

        /**
         * Verifies a StringStringEntryProto message.
         * @function verify
         * @memberof onnx.StringStringEntryProto
         * @static
         * @param {Object.<string,*>} message Plain object to verify
         * @returns {string|null} `null` if valid, otherwise the reason why it is not
         */
        StringStringEntryProto.verify = function verify(message) {
            if (typeof message !== "object" || message === null)
                return "object expected";
            if (message.key != null && message.hasOwnProperty("key"))
                if (!$util.isString(message.key))
                    return "key: string expected";
            if (message.value != null && message.hasOwnProperty("value"))
                if (!$util.isString(message.value))
                    return "value: string expected";
            return null;
        };

        /**
         * Creates a StringStringEntryProto message from a plain object. Also converts values to their respective internal types.
         * @function fromObject
         * @memberof onnx.StringStringEntryProto
         * @static
         * @param {Object.<string,*>} object Plain object
         * @returns {onnx.StringStringEntryProto} StringStringEntryProto
         */
        StringStringEntryProto.fromObject = function fromObject(object) {
            if (object instanceof $root.onnx.StringStringEntryProto)
                return object;
            var message = new $root.onnx.StringStringEntryProto();
            if (object.key != null)
                message.key = String(object.key);
            if (object.value != null)
                message.value = String(object.value);
            return message;
        };

        /**
         * Creates a plain object from a StringStringEntryProto message. Also converts values to other types if specified.
         * @function toObject
         * @memberof onnx.StringStringEntryProto
         * @static
         * @param {onnx.StringStringEntryProto} message StringStringEntryProto
         * @param {$protobuf.IConversionOptions} [options] Conversion options
         * @returns {Object.<string,*>} Plain object
         */
        StringStringEntryProto.toObject = function toObject(message, options) {
            if (!options)
                options = {};
            var object = {};
            if (options.defaults) {
                object.key = "";
                object.value = "";
            }
            if (message.key != null && message.hasOwnProperty("key"))
                object.key = message.key;
            if (message.value != null && message.hasOwnProperty("value"))
                object.value = message.value;
            return object;
        };

        /**
         * Converts this StringStringEntryProto to JSON.
         * @function toJSON
         * @memberof onnx.StringStringEntryProto
         * @instance
         * @returns {Object.<string,*>} JSON object
         */
        StringStringEntryProto.prototype.toJSON = function toJSON() {
            return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
        };

        return StringStringEntryProto;
    })();

    onnx.TensorAnnotation = (function() {

        /**
         * Properties of a TensorAnnotation.
         * @memberof onnx
         * @interface ITensorAnnotation
         * @property {string|null} [tensorName] TensorAnnotation tensorName
         * @property {Array.<onnx.IStringStringEntryProto>|null} [quantParameterTensorNames] TensorAnnotation quantParameterTensorNames
         */

        /**
         * Constructs a new TensorAnnotation.
         * @memberof onnx
         * @classdesc Represents a TensorAnnotation.
         * @implements ITensorAnnotation
         * @constructor
         * @param {onnx.ITensorAnnotation=} [properties] Properties to set
         */
        function TensorAnnotation(properties) {
            this.quantParameterTensorNames = [];
            if (properties)
                for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                        this[keys[i]] = properties[keys[i]];
        }

        /**
         * TensorAnnotation tensorName.
         * @member {string} tensorName
         * @memberof onnx.TensorAnnotation
         * @instance
         */
        TensorAnnotation.prototype.tensorName = "";

        /**
         * TensorAnnotation quantParameterTensorNames.
         * @member {Array.<onnx.IStringStringEntryProto>} quantParameterTensorNames
         * @memberof onnx.TensorAnnotation
         * @instance
         */
        TensorAnnotation.prototype.quantParameterTensorNames = $util.emptyArray;

        /**
         * Creates a new TensorAnnotation instance using the specified properties.
         * @function create
         * @memberof onnx.TensorAnnotation
         * @static
         * @param {onnx.ITensorAnnotation=} [properties] Properties to set
         * @returns {onnx.TensorAnnotation} TensorAnnotation instance
         */
        TensorAnnotation.create = function create(properties) {
            return new TensorAnnotation(properties);
        };

        /**
         * Encodes the specified TensorAnnotation message. Does not implicitly {@link onnx.TensorAnnotation.verify|verify} messages.
         * @function encode
         * @memberof onnx.TensorAnnotation
         * @static
         * @param {onnx.ITensorAnnotation} message TensorAnnotation message or plain object to encode
         * @param {$protobuf.Writer} [writer] Writer to encode to
         * @returns {$protobuf.Writer} Writer
         */
        TensorAnnotation.encode = function encode(message, writer) {
            if (!writer)
                writer = $Writer.create();
            if (message.tensorName != null && message.hasOwnProperty("tensorName"))
                writer.uint32(/* id 1, wireType 2 =*/10).string(message.tensorName);
            if (message.quantParameterTensorNames != null && message.quantParameterTensorNames.length)
                for (var i = 0; i < message.quantParameterTensorNames.length; ++i)
                    $root.onnx.StringStringEntryProto.encode(message.quantParameterTensorNames[i], writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim();
            return writer;
        };

        /**
         * Encodes the specified TensorAnnotation message, length delimited. Does not implicitly {@link onnx.TensorAnnotation.verify|verify} messages.
         * @function encodeDelimited
         * @memberof onnx.TensorAnnotation
         * @static
         * @param {onnx.ITensorAnnotation} message TensorAnnotation message or plain object to encode
         * @param {$protobuf.Writer} [writer] Writer to encode to
         * @returns {$protobuf.Writer} Writer
         */
        TensorAnnotation.encodeDelimited = function encodeDelimited(message, writer) {
            return this.encode(message, writer).ldelim();
        };

        /**
         * Decodes a TensorAnnotation message from the specified reader or buffer.
         * @function decode
         * @memberof onnx.TensorAnnotation
         * @static
         * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
         * @param {number} [length] Message length if known beforehand
         * @returns {onnx.TensorAnnotation} TensorAnnotation
         * @throws {Error} If the payload is not a reader or valid buffer
         * @throws {$protobuf.util.ProtocolError} If required fields are missing
         */
        TensorAnnotation.decode = function decode(reader, length) {
            if (!(reader instanceof $Reader))
                reader = $Reader.create(reader);
            var end = length === undefined ? reader.len : reader.pos + length, message = new $root.onnx.TensorAnnotation();
            while (reader.pos < end) {
                var tag = reader.uint32();
                switch (tag >>> 3) {
                case 1:
                    message.tensorName = reader.string();
                    break;
                case 2:
                    if (!(message.quantParameterTensorNames && message.quantParameterTensorNames.length))
                        message.quantParameterTensorNames = [];
                    message.quantParameterTensorNames.push($root.onnx.StringStringEntryProto.decode(reader, reader.uint32()));
                    break;
                default:
                    reader.skipType(tag & 7);
                    break;
                }
            }
            return message;
        };

        /**
         * Decodes a TensorAnnotation message from the specified reader or buffer, length delimited.
         * @function decodeDelimited
         * @memberof onnx.TensorAnnotation
         * @static
         * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
         * @returns {onnx.TensorAnnotation} TensorAnnotation
         * @throws {Error} If the payload is not a reader or valid buffer
         * @throws {$protobuf.util.ProtocolError} If required fields are missing
         */
        TensorAnnotation.decodeDelimited = function decodeDelimited(reader) {
            if (!(reader instanceof $Reader))
                reader = new $Reader(reader);
            return this.decode(reader, reader.uint32());
        };

        /**
         * Verifies a TensorAnnotation message.
         * @function verify
         * @memberof onnx.TensorAnnotation
         * @static
         * @param {Object.<string,*>} message Plain object to verify
         * @returns {string|null} `null` if valid, otherwise the reason why it is not
         */
        TensorAnnotation.verify = function verify(message) {
            if (typeof message !== "object" || message === null)
                return "object expected";
            if (message.tensorName != null && message.hasOwnProperty("tensorName"))
                if (!$util.isString(message.tensorName))
                    return "tensorName: string expected";
            if (message.quantParameterTensorNames != null && message.hasOwnProperty("quantParameterTensorNames")) {
                if (!Array.isArray(message.quantParameterTensorNames))
                    return "quantParameterTensorNames: array expected";
                for (var i = 0; i < message.quantParameterTensorNames.length; ++i) {
                    var error = $root.onnx.StringStringEntryProto.verify(message.quantParameterTensorNames[i]);
                    if (error)
                        return "quantParameterTensorNames." + error;
                }
            }
            return null;
        };

        /**
         * Creates a TensorAnnotation message from a plain object. Also converts values to their respective internal types.
         * @function fromObject
         * @memberof onnx.TensorAnnotation
         * @static
         * @param {Object.<string,*>} object Plain object
         * @returns {onnx.TensorAnnotation} TensorAnnotation
         */
        TensorAnnotation.fromObject = function fromObject(object) {
            if (object instanceof $root.onnx.TensorAnnotation)
                return object;
            var message = new $root.onnx.TensorAnnotation();
            if (object.tensorName != null)
                message.tensorName = String(object.tensorName);
            if (object.quantParameterTensorNames) {
                if (!Array.isArray(object.quantParameterTensorNames))
                    throw TypeError(".onnx.TensorAnnotation.quantParameterTensorNames: array expected");
                message.quantParameterTensorNames = [];
                for (var i = 0; i < object.quantParameterTensorNames.length; ++i) {
                    if (typeof object.quantParameterTensorNames[i] !== "object")
                        throw TypeError(".onnx.TensorAnnotation.quantParameterTensorNames: object expected");
                    message.quantParameterTensorNames[i] = $root.onnx.StringStringEntryProto.fromObject(object.quantParameterTensorNames[i]);
                }
            }
            return message;
        };

        /**
         * Creates a plain object from a TensorAnnotation message. Also converts values to other types if specified.
         * @function toObject
         * @memberof onnx.TensorAnnotation
         * @static
         * @param {onnx.TensorAnnotation} message TensorAnnotation
         * @param {$protobuf.IConversionOptions} [options] Conversion options
         * @returns {Object.<string,*>} Plain object
         */
        TensorAnnotation.toObject = function toObject(message, options) {
            if (!options)
                options = {};
            var object = {};
            if (options.arrays || options.defaults)
                object.quantParameterTensorNames = [];
            if (options.defaults)
                object.tensorName = "";
            if (message.tensorName != null && message.hasOwnProperty("tensorName"))
                object.tensorName = message.tensorName;
            if (message.quantParameterTensorNames && message.quantParameterTensorNames.length) {
                object.quantParameterTensorNames = [];
                for (var j = 0; j < message.quantParameterTensorNames.length; ++j)
                    object.quantParameterTensorNames[j] = $root.onnx.StringStringEntryProto.toObject(message.quantParameterTensorNames[j], options);
            }
            return object;
        };

        /**
         * Converts this TensorAnnotation to JSON.
         * @function toJSON
         * @memberof onnx.TensorAnnotation
         * @instance
         * @returns {Object.<string,*>} JSON object
         */
        TensorAnnotation.prototype.toJSON = function toJSON() {
            return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
        };

        return TensorAnnotation;
    })();

    onnx.GraphProto = (function() {

        /**
         * Properties of a GraphProto.
         * @memberof onnx
         * @interface IGraphProto
         * @property {Array.<onnx.INodeProto>|null} [node] GraphProto node
         * @property {string|null} [name] GraphProto name
         * @property {Array.<onnx.ITensorProto>|null} [initializer] GraphProto initializer
         * @property {string|null} [docString] GraphProto docString
         * @property {Array.<onnx.IValueInfoProto>|null} [input] GraphProto input
         * @property {Array.<onnx.IValueInfoProto>|null} [output] GraphProto output
         * @property {Array.<onnx.IValueInfoProto>|null} [valueInfo] GraphProto valueInfo
         * @property {Array.<onnx.ITensorAnnotation>|null} [quantizationAnnotation] GraphProto quantizationAnnotation
         */

        /**
         * Constructs a new GraphProto.
         * @memberof onnx
         * @classdesc Represents a GraphProto.
         * @implements IGraphProto
         * @constructor
         * @param {onnx.IGraphProto=} [properties] Properties to set
         */
        function GraphProto(properties) {
            this.node = [];
            this.initializer = [];
            this.input = [];
            this.output = [];
            this.valueInfo = [];
            this.quantizationAnnotation = [];
            if (properties)
                for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                        this[keys[i]] = properties[keys[i]];
        }

        /**
         * GraphProto node.
         * @member {Array.<onnx.INodeProto>} node
         * @memberof onnx.GraphProto
         * @instance
         */
        GraphProto.prototype.node = $util.emptyArray;

        /**
         * GraphProto name.
         * @member {string} name
         * @memberof onnx.GraphProto
         * @instance
         */
        GraphProto.prototype.name = "";

        /**
         * GraphProto initializer.
         * @member {Array.<onnx.ITensorProto>} initializer
         * @memberof onnx.GraphProto
         * @instance
         */
        GraphProto.prototype.initializer = $util.emptyArray;

        /**
         * GraphProto docString.
         * @member {string} docString
         * @memberof onnx.GraphProto
         * @instance
         */
        GraphProto.prototype.docString = "";

        /**
         * GraphProto input.
         * @member {Array.<onnx.IValueInfoProto>} input
         * @memberof onnx.GraphProto
         * @instance
         */
        GraphProto.prototype.input = $util.emptyArray;

        /**
         * GraphProto output.
         * @member {Array.<onnx.IValueInfoProto>} output
         * @memberof onnx.GraphProto
         * @instance
         */
        GraphProto.prototype.output = $util.emptyArray;

        /**
         * GraphProto valueInfo.
         * @member {Array.<onnx.IValueInfoProto>} valueInfo
         * @memberof onnx.GraphProto
         * @instance
         */
        GraphProto.prototype.valueInfo = $util.emptyArray;

        /**
         * GraphProto quantizationAnnotation.
         * @member {Array.<onnx.ITensorAnnotation>} quantizationAnnotation
         * @memberof onnx.GraphProto
         * @instance
         */
        GraphProto.prototype.quantizationAnnotation = $util.emptyArray;

        /**
         * Creates a new GraphProto instance using the specified properties.
         * @function create
         * @memberof onnx.GraphProto
         * @static
         * @param {onnx.IGraphProto=} [properties] Properties to set
         * @returns {onnx.GraphProto} GraphProto instance
         */
        GraphProto.create = function create(properties) {
            return new GraphProto(properties);
        };

        /**
         * Encodes the specified GraphProto message. Does not implicitly {@link onnx.GraphProto.verify|verify} messages.
         * @function encode
         * @memberof onnx.GraphProto
         * @static
         * @param {onnx.IGraphProto} message GraphProto message or plain object to encode
         * @param {$protobuf.Writer} [writer] Writer to encode to
         * @returns {$protobuf.Writer} Writer
         */
        GraphProto.encode = function encode(message, writer) {
            if (!writer)
                writer = $Writer.create();
            if (message.node != null && message.node.length)
                for (var i = 0; i < message.node.length; ++i)
                    $root.onnx.NodeProto.encode(message.node[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim();
            if (message.name != null && message.hasOwnProperty("name"))
                writer.uint32(/* id 2, wireType 2 =*/18).string(message.name);
            if (message.initializer != null && message.initializer.length)
                for (var i = 0; i < message.initializer.length; ++i)
                    $root.onnx.TensorProto.encode(message.initializer[i], writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim();
            if (message.docString != null && message.hasOwnProperty("docString"))
                writer.uint32(/* id 10, wireType 2 =*/82).string(message.docString);
            if (message.input != null && message.input.length)
                for (var i = 0; i < message.input.length; ++i)
                    $root.onnx.ValueInfoProto.encode(message.input[i], writer.uint32(/* id 11, wireType 2 =*/90).fork()).ldelim();
            if (message.output != null && message.output.length)
                for (var i = 0; i < message.output.length; ++i)
                    $root.onnx.ValueInfoProto.encode(message.output[i], writer.uint32(/* id 12, wireType 2 =*/98).fork()).ldelim();
            if (message.valueInfo != null && message.valueInfo.length)
                for (var i = 0; i < message.valueInfo.length; ++i)
                    $root.onnx.ValueInfoProto.encode(message.valueInfo[i], writer.uint32(/* id 13, wireType 2 =*/106).fork()).ldelim();
            if (message.quantizationAnnotation != null && message.quantizationAnnotation.length)
                for (var i = 0; i < message.quantizationAnnotation.length; ++i)
                    $root.onnx.TensorAnnotation.encode(message.quantizationAnnotation[i], writer.uint32(/* id 14, wireType 2 =*/114).fork()).ldelim();
            return writer;
        };

        /**
         * Encodes the specified GraphProto message, length delimited. Does not implicitly {@link onnx.GraphProto.verify|verify} messages.
         * @function encodeDelimited
         * @memberof onnx.GraphProto
         * @static
         * @param {onnx.IGraphProto} message GraphProto message or plain object to encode
         * @param {$protobuf.Writer} [writer] Writer to encode to
         * @returns {$protobuf.Writer} Writer
         */
        GraphProto.encodeDelimited = function encodeDelimited(message, writer) {
            return this.encode(message, writer).ldelim();
        };

        /**
         * Decodes a GraphProto message from the specified reader or buffer.
         * @function decode
         * @memberof onnx.GraphProto
         * @static
         * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
         * @param {number} [length] Message length if known beforehand
         * @returns {onnx.GraphProto} GraphProto
         * @throws {Error} If the payload is not a reader or valid buffer
         * @throws {$protobuf.util.ProtocolError} If required fields are missing
         */
        GraphProto.decode = function decode(reader, length) {
            if (!(reader instanceof $Reader))
                reader = $Reader.create(reader);
            var end = length === undefined ? reader.len : reader.pos + length, message = new $root.onnx.GraphProto();
            while (reader.pos < end) {
                var tag = reader.uint32();
                switch (tag >>> 3) {
                case 1:
                    if (!(message.node && message.node.length))
                        message.node = [];
                    message.node.push($root.onnx.NodeProto.decode(reader, reader.uint32()));
                    break;
                case 2:
                    message.name = reader.string();
                    break;
                case 5:
                    if (!(message.initializer && message.initializer.length))
                        message.initializer = [];
                    message.initializer.push($root.onnx.TensorProto.decode(reader, reader.uint32()));
                    break;
                case 10:
                    message.docString = reader.string();
                    break;
                case 11:
                    if (!(message.input && message.input.length))
                        message.input = [];
                    message.input.push($root.onnx.ValueInfoProto.decode(reader, reader.uint32()));
                    break;
                case 12:
                    if (!(message.output && message.output.length))
                        message.output = [];
                    message.output.push($root.onnx.ValueInfoProto.decode(reader, reader.uint32()));
                    break;
                case 13:
                    if (!(message.valueInfo && message.valueInfo.length))
                        message.valueInfo = [];
                    message.valueInfo.push($root.onnx.ValueInfoProto.decode(reader, reader.uint32()));
                    break;
                case 14:
                    if (!(message.quantizationAnnotation && message.quantizationAnnotation.length))
                        message.quantizationAnnotation = [];
                    message.quantizationAnnotation.push($root.onnx.TensorAnnotation.decode(reader, reader.uint32()));
                    break;
                default:
                    reader.skipType(tag & 7);
                    break;
                }
            }
            return message;
        };

        /**
         * Decodes a GraphProto message from the specified reader or buffer, length delimited.
         * @function decodeDelimited
         * @memberof onnx.GraphProto
         * @static
         * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
         * @returns {onnx.GraphProto} GraphProto
         * @throws {Error} If the payload is not a reader or valid buffer
         * @throws {$protobuf.util.ProtocolError} If required fields are missing
         */
        GraphProto.decodeDelimited = function decodeDelimited(reader) {
            if (!(reader instanceof $Reader))
                reader = new $Reader(reader);
            return this.decode(reader, reader.uint32());
        };

        /**
         * Verifies a GraphProto message.
         * @function verify
         * @memberof onnx.GraphProto
         * @static
         * @param {Object.<string,*>} message Plain object to verify
         * @returns {string|null} `null` if valid, otherwise the reason why it is not
         */
        GraphProto.verify = function verify(message) {
            if (typeof message !== "object" || message === null)
                return "object expected";
            if (message.node != null && message.hasOwnProperty("node")) {
                if (!Array.isArray(message.node))
                    return "node: array expected";
                for (var i = 0; i < message.node.length; ++i) {
                    var error = $root.onnx.NodeProto.verify(message.node[i]);
                    if (error)
                        return "node." + error;
                }
            }
            if (message.name != null && message.hasOwnProperty("name"))
                if (!$util.isString(message.name))
                    return "name: string expected";
            if (message.initializer != null && message.hasOwnProperty("initializer")) {
                if (!Array.isArray(message.initializer))
                    return "initializer: array expected";
                for (var i = 0; i < message.initializer.length; ++i) {
                    var error = $root.onnx.TensorProto.verify(message.initializer[i]);
                    if (error)
                        return "initializer." + error;
                }
            }
            if (message.docString != null && message.hasOwnProperty("docString"))
                if (!$util.isString(message.docString))
                    return "docString: string expected";
            if (message.input != null && message.hasOwnProperty("input")) {
                if (!Array.isArray(message.input))
                    return "input: array expected";
                for (var i = 0; i < message.input.length; ++i) {
                    var error = $root.onnx.ValueInfoProto.verify(message.input[i]);
                    if (error)
                        return "input." + error;
                }
            }
            if (message.output != null && message.hasOwnProperty("output")) {
                if (!Array.isArray(message.output))
                    return "output: array expected";
                for (var i = 0; i < message.output.length; ++i) {
                    var error = $root.onnx.ValueInfoProto.verify(message.output[i]);
                    if (error)
                        return "output." + error;
                }
            }
            if (message.valueInfo != null && message.hasOwnProperty("valueInfo")) {
                if (!Array.isArray(message.valueInfo))
                    return "valueInfo: array expected";
                for (var i = 0; i < message.valueInfo.length; ++i) {
                    var error = $root.onnx.ValueInfoProto.verify(message.valueInfo[i]);
                    if (error)
                        return "valueInfo." + error;
                }
            }
            if (message.quantizationAnnotation != null && message.hasOwnProperty("quantizationAnnotation")) {
                if (!Array.isArray(message.quantizationAnnotation))
                    return "quantizationAnnotation: array expected";
                for (var i = 0; i < message.quantizationAnnotation.length; ++i) {
                    var error = $root.onnx.TensorAnnotation.verify(message.quantizationAnnotation[i]);
                    if (error)
                        return "quantizationAnnotation." + error;
                }
            }
            return null;
        };

        /**
         * Creates a GraphProto message from a plain object. Also converts values to their respective internal types.
         * @function fromObject
         * @memberof onnx.GraphProto
         * @static
         * @param {Object.<string,*>} object Plain object
         * @returns {onnx.GraphProto} GraphProto
         */
        GraphProto.fromObject = function fromObject(object) {
            if (object instanceof $root.onnx.GraphProto)
                return object;
            var message = new $root.onnx.GraphProto();
            if (object.node) {
                if (!Array.isArray(object.node))
                    throw TypeError(".onnx.GraphProto.node: array expected");
                message.node = [];
                for (var i = 0; i < object.node.length; ++i) {
                    if (typeof object.node[i] !== "object")
                        throw TypeError(".onnx.GraphProto.node: object expected");
                    message.node[i] = $root.onnx.NodeProto.fromObject(object.node[i]);
                }
            }
            if (object.name != null)
                message.name = String(object.name);
            if (object.initializer) {
                if (!Array.isArray(object.initializer))
                    throw TypeError(".onnx.GraphProto.initializer: array expected");
                message.initializer = [];
                for (var i = 0; i < object.initializer.length; ++i) {
                    if (typeof object.initializer[i] !== "object")
                        throw TypeError(".onnx.GraphProto.initializer: object expected");
                    message.initializer[i] = $root.onnx.TensorProto.fromObject(object.initializer[i]);
                }
            }
            if (object.docString != null)
                message.docString = String(object.docString);
            if (object.input) {
                if (!Array.isArray(object.input))
                    throw TypeError(".onnx.GraphProto.input: array expected");
                message.input = [];
                for (var i = 0; i < object.input.length; ++i) {
                    if (typeof object.input[i] !== "object")
                        throw TypeError(".onnx.GraphProto.input: object expected");
                    message.input[i] = $root.onnx.ValueInfoProto.fromObject(object.input[i]);
                }
            }
            if (object.output) {
                if (!Array.isArray(object.output))
                    throw TypeError(".onnx.GraphProto.output: array expected");
                message.output = [];
                for (var i = 0; i < object.output.length; ++i) {
                    if (typeof object.output[i] !== "object")
                        throw TypeError(".onnx.GraphProto.output: object expected");
                    message.output[i] = $root.onnx.ValueInfoProto.fromObject(object.output[i]);
                }
            }
            if (object.valueInfo) {
                if (!Array.isArray(object.valueInfo))
                    throw TypeError(".onnx.GraphProto.valueInfo: array expected");
                message.valueInfo = [];
                for (var i = 0; i < object.valueInfo.length; ++i) {
                    if (typeof object.valueInfo[i] !== "object")
                        throw TypeError(".onnx.GraphProto.valueInfo: object expected");
                    message.valueInfo[i] = $root.onnx.ValueInfoProto.fromObject(object.valueInfo[i]);
                }
            }
            if (object.quantizationAnnotation) {
                if (!Array.isArray(object.quantizationAnnotation))
                    throw TypeError(".onnx.GraphProto.quantizationAnnotation: array expected");
                message.quantizationAnnotation = [];
                for (var i = 0; i < object.quantizationAnnotation.length; ++i) {
                    if (typeof object.quantizationAnnotation[i] !== "object")
                        throw TypeError(".onnx.GraphProto.quantizationAnnotation: object expected");
                    message.quantizationAnnotation[i] = $root.onnx.TensorAnnotation.fromObject(object.quantizationAnnotation[i]);
                }
            }
            return message;
        };

        /**
         * Creates a plain object from a GraphProto message. Also converts values to other types if specified.
         * @function toObject
         * @memberof onnx.GraphProto
         * @static
         * @param {onnx.GraphProto} message GraphProto
         * @param {$protobuf.IConversionOptions} [options] Conversion options
         * @returns {Object.<string,*>} Plain object
         */
        GraphProto.toObject = function toObject(message, options) {
            if (!options)
                options = {};
            var object = {};
            if (options.arrays || options.defaults) {
                object.node = [];
                object.initializer = [];
                object.input = [];
                object.output = [];
                object.valueInfo = [];
                object.quantizationAnnotation = [];
            }
            if (options.defaults) {
                object.name = "";
                object.docString = "";
            }
            if (message.node && message.node.length) {
                object.node = [];
                for (var j = 0; j < message.node.length; ++j)
                    object.node[j] = $root.onnx.NodeProto.toObject(message.node[j], options);
            }
            if (message.name != null && message.hasOwnProperty("name"))
                object.name = message.name;
            if (message.initializer && message.initializer.length) {
                object.initializer = [];
                for (var j = 0; j < message.initializer.length; ++j)
                    object.initializer[j] = $root.onnx.TensorProto.toObject(message.initializer[j], options);
            }
            if (message.docString != null && message.hasOwnProperty("docString"))
                object.docString = message.docString;
            if (message.input && message.input.length) {
                object.input = [];
                for (var j = 0; j < message.input.length; ++j)
                    object.input[j] = $root.onnx.ValueInfoProto.toObject(message.input[j], options);
            }
            if (message.output && message.output.length) {
                object.output = [];
                for (var j = 0; j < message.output.length; ++j)
                    object.output[j] = $root.onnx.ValueInfoProto.toObject(message.output[j], options);
            }
            if (message.valueInfo && message.valueInfo.length) {
                object.valueInfo = [];
                for (var j = 0; j < message.valueInfo.length; ++j)
                    object.valueInfo[j] = $root.onnx.ValueInfoProto.toObject(message.valueInfo[j], options);
            }
            if (message.quantizationAnnotation && message.quantizationAnnotation.length) {
                object.quantizationAnnotation = [];
                for (var j = 0; j < message.quantizationAnnotation.length; ++j)
                    object.quantizationAnnotation[j] = $root.onnx.TensorAnnotation.toObject(message.quantizationAnnotation[j], options);
            }
            return object;
        };

        /**
         * Converts this GraphProto to JSON.
         * @function toJSON
         * @memberof onnx.GraphProto
         * @instance
         * @returns {Object.<string,*>} JSON object
         */
        GraphProto.prototype.toJSON = function toJSON() {
            return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
        };

        return GraphProto;
    })();

    onnx.TensorProto = (function() {

        /**
         * Properties of a TensorProto.
         * @memberof onnx
         * @interface ITensorProto
         * @property {Array.<number|Long>|null} [dims] TensorProto dims
         * @property {number|null} [dataType] TensorProto dataType
         * @property {onnx.TensorProto.ISegment|null} [segment] TensorProto segment
         * @property {Array.<number>|null} [floatData] TensorProto floatData
         * @property {Array.<number>|null} [int32Data] TensorProto int32Data
         * @property {Array.<Uint8Array>|null} [stringData] TensorProto stringData
         * @property {Array.<number|Long>|null} [int64Data] TensorProto int64Data
         * @property {string|null} [name] TensorProto name
         * @property {string|null} [docString] TensorProto docString
         * @property {Uint8Array|null} [rawData] TensorProto rawData
         * @property {Array.<onnx.IStringStringEntryProto>|null} [externalData] TensorProto externalData
         * @property {onnx.TensorProto.DataLocation|null} [dataLocation] TensorProto dataLocation
         * @property {Array.<number>|null} [doubleData] TensorProto doubleData
         * @property {Array.<number|Long>|null} [uint64Data] TensorProto uint64Data
         */

        /**
         * Constructs a new TensorProto.
         * @memberof onnx
         * @classdesc Represents a TensorProto.
         * @implements ITensorProto
         * @constructor
         * @param {onnx.ITensorProto=} [properties] Properties to set
         */
        function TensorProto(properties) {
            this.dims = [];
            this.floatData = [];
            this.int32Data = [];
            this.stringData = [];
            this.int64Data = [];
            this.externalData = [];
            this.doubleData = [];
            this.uint64Data = [];
            if (properties)
                for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                        this[keys[i]] = properties[keys[i]];
        }

        /**
         * TensorProto dims.
         * @member {Array.<number|Long>} dims
         * @memberof onnx.TensorProto
         * @instance
         */
        TensorProto.prototype.dims = $util.emptyArray;

        /**
         * TensorProto dataType.
         * @member {number} dataType
         * @memberof onnx.TensorProto
         * @instance
         */
        TensorProto.prototype.dataType = 0;

        /**
         * TensorProto segment.
         * @member {onnx.TensorProto.ISegment|null|undefined} segment
         * @memberof onnx.TensorProto
         * @instance
         */
        TensorProto.prototype.segment = null;

        /**
         * TensorProto floatData.
         * @member {Array.<number>} floatData
         * @memberof onnx.TensorProto
         * @instance
         */
        TensorProto.prototype.floatData = $util.emptyArray;

        /**
         * TensorProto int32Data.
         * @member {Array.<number>} int32Data
         * @memberof onnx.TensorProto
         * @instance
         */
        TensorProto.prototype.int32Data = $util.emptyArray;

        /**
         * TensorProto stringData.
         * @member {Array.<Uint8Array>} stringData
         * @memberof onnx.TensorProto
         * @instance
         */
        TensorProto.prototype.stringData = $util.emptyArray;

        /**
         * TensorProto int64Data.
         * @member {Array.<number|Long>} int64Data
         * @memberof onnx.TensorProto
         * @instance
         */
        TensorProto.prototype.int64Data = $util.emptyArray;

        /**
         * TensorProto name.
         * @member {string} name
         * @memberof onnx.TensorProto
         * @instance
         */
        TensorProto.prototype.name = "";

        /**
         * TensorProto docString.
         * @member {string} docString
         * @memberof onnx.TensorProto
         * @instance
         */
        TensorProto.prototype.docString = "";

        /**
         * TensorProto rawData.
         * @member {Uint8Array} rawData
         * @memberof onnx.TensorProto
         * @instance
         */
        TensorProto.prototype.rawData = $util.newBuffer([]);

        /**
         * TensorProto externalData.
         * @member {Array.<onnx.IStringStringEntryProto>} externalData
         * @memberof onnx.TensorProto
         * @instance
         */
        TensorProto.prototype.externalData = $util.emptyArray;

        /**
         * TensorProto dataLocation.
         * @member {onnx.TensorProto.DataLocation} dataLocation
         * @memberof onnx.TensorProto
         * @instance
         */
        TensorProto.prototype.dataLocation = 0;

        /**
         * TensorProto doubleData.
         * @member {Array.<number>} doubleData
         * @memberof onnx.TensorProto
         * @instance
         */
        TensorProto.prototype.doubleData = $util.emptyArray;

        /**
         * TensorProto uint64Data.
         * @member {Array.<number|Long>} uint64Data
         * @memberof onnx.TensorProto
         * @instance
         */
        TensorProto.prototype.uint64Data = $util.emptyArray;

        /**
         * Creates a new TensorProto instance using the specified properties.
         * @function create
         * @memberof onnx.TensorProto
         * @static
         * @param {onnx.ITensorProto=} [properties] Properties to set
         * @returns {onnx.TensorProto} TensorProto instance
         */
        TensorProto.create = function create(properties) {
            return new TensorProto(properties);
        };

        /**
         * Encodes the specified TensorProto message. Does not implicitly {@link onnx.TensorProto.verify|verify} messages.
         * @function encode
         * @memberof onnx.TensorProto
         * @static
         * @param {onnx.ITensorProto} message TensorProto message or plain object to encode
         * @param {$protobuf.Writer} [writer] Writer to encode to
         * @returns {$protobuf.Writer} Writer
         */
        TensorProto.encode = function encode(message, writer) {
            if (!writer)
                writer = $Writer.create();
            if (message.dims != null && message.dims.length) {
                writer.uint32(/* id 1, wireType 2 =*/10).fork();
                for (var i = 0; i < message.dims.length; ++i)
                    writer.int64(message.dims[i]);
                writer.ldelim();
            }
            if (message.dataType != null && message.hasOwnProperty("dataType"))
                writer.uint32(/* id 2, wireType 0 =*/16).int32(message.dataType);
            if (message.segment != null && message.hasOwnProperty("segment"))
                $root.onnx.TensorProto.Segment.encode(message.segment, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim();
            if (message.floatData != null && message.floatData.length) {
                writer.uint32(/* id 4, wireType 2 =*/34).fork();
                for (var i = 0; i < message.floatData.length; ++i)
                    writer.float(message.floatData[i]);
                writer.ldelim();
            }
            if (message.int32Data != null && message.int32Data.length) {
                writer.uint32(/* id 5, wireType 2 =*/42).fork();
                for (var i = 0; i < message.int32Data.length; ++i)
                    writer.int32(message.int32Data[i]);
                writer.ldelim();
            }
            if (message.stringData != null && message.stringData.length)
                for (var i = 0; i < message.stringData.length; ++i)
                    writer.uint32(/* id 6, wireType 2 =*/50).bytes(message.stringData[i]);
            if (message.int64Data != null && message.int64Data.length) {
                writer.uint32(/* id 7, wireType 2 =*/58).fork();
                for (var i = 0; i < message.int64Data.length; ++i)
                    writer.int64(message.int64Data[i]);
                writer.ldelim();
            }
            if (message.name != null && message.hasOwnProperty("name"))
                writer.uint32(/* id 8, wireType 2 =*/66).string(message.name);
            if (message.rawData != null && message.hasOwnProperty("rawData"))
                writer.uint32(/* id 9, wireType 2 =*/74).bytes(message.rawData);
            if (message.doubleData != null && message.doubleData.length) {
                writer.uint32(/* id 10, wireType 2 =*/82).fork();
                for (var i = 0; i < message.doubleData.length; ++i)
                    writer.double(message.doubleData[i]);
                writer.ldelim();
            }
            if (message.uint64Data != null && message.uint64Data.length) {
                writer.uint32(/* id 11, wireType 2 =*/90).fork();
                for (var i = 0; i < message.uint64Data.length; ++i)
                    writer.uint64(message.uint64Data[i]);
                writer.ldelim();
            }
            if (message.docString != null && message.hasOwnProperty("docString"))
                writer.uint32(/* id 12, wireType 2 =*/98).string(message.docString);
            if (message.externalData != null && message.externalData.length)
                for (var i = 0; i < message.externalData.length; ++i)
                    $root.onnx.StringStringEntryProto.encode(message.externalData[i], writer.uint32(/* id 13, wireType 2 =*/106).fork()).ldelim();
            if (message.dataLocation != null && message.hasOwnProperty("dataLocation"))
                writer.uint32(/* id 14, wireType 0 =*/112).int32(message.dataLocation);
            return writer;
        };

        /**
         * Encodes the specified TensorProto message, length delimited. Does not implicitly {@link onnx.TensorProto.verify|verify} messages.
         * @function encodeDelimited
         * @memberof onnx.TensorProto
         * @static
         * @param {onnx.ITensorProto} message TensorProto message or plain object to encode
         * @param {$protobuf.Writer} [writer] Writer to encode to
         * @returns {$protobuf.Writer} Writer
         */
        TensorProto.encodeDelimited = function encodeDelimited(message, writer) {
            return this.encode(message, writer).ldelim();
        };

        /**
         * Decodes a TensorProto message from the specified reader or buffer.
         * @function decode
         * @memberof onnx.TensorProto
         * @static
         * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
         * @param {number} [length] Message length if known beforehand
         * @returns {onnx.TensorProto} TensorProto
         * @throws {Error} If the payload is not a reader or valid buffer
         * @throws {$protobuf.util.ProtocolError} If required fields are missing
         */
        TensorProto.decode = function decode(reader, length) {
            if (!(reader instanceof $Reader))
                reader = $Reader.create(reader);
            var end = length === undefined ? reader.len : reader.pos + length, message = new $root.onnx.TensorProto();
            while (reader.pos < end) {
                var tag = reader.uint32();
                switch (tag >>> 3) {
                case 1:
                    if (!(message.dims && message.dims.length))
                        message.dims = [];
                    if ((tag & 7) === 2) {
                        var end2 = reader.uint32() + reader.pos;
                        while (reader.pos < end2)
                            message.dims.push(reader.int64());
                    } else
                        message.dims.push(reader.int64());
                    break;
                case 2:
                    message.dataType = reader.int32();
                    break;
                case 3:
                    message.segment = $root.onnx.TensorProto.Segment.decode(reader, reader.uint32());
                    break;
                case 4:
                    if (!(message.floatData && message.floatData.length))
                        message.floatData = [];
                    if ((tag & 7) === 2) {
                        var end2 = reader.uint32() + reader.pos;
                        while (reader.pos < end2)
                            message.floatData.push(reader.float());
                    } else
                        message.floatData.push(reader.float());
                    break;
                case 5:
                    if (!(message.int32Data && message.int32Data.length))
                        message.int32Data = [];
                    if ((tag & 7) === 2) {
                        var end2 = reader.uint32() + reader.pos;
                        while (reader.pos < end2)
                            message.int32Data.push(reader.int32());
                    } else
                        message.int32Data.push(reader.int32());
                    break;
                case 6:
                    if (!(message.stringData && message.stringData.length))
                        message.stringData = [];
                    message.stringData.push(reader.bytes());
                    break;
                case 7:
                    if (!(message.int64Data && message.int64Data.length))
                        message.int64Data = [];
                    if ((tag & 7) === 2) {
                        var end2 = reader.uint32() + reader.pos;
                        while (reader.pos < end2)
                            message.int64Data.push(reader.int64());
                    } else
                        message.int64Data.push(reader.int64());
                    break;
                case 8:
                    message.name = reader.string();
                    break;
                case 12:
                    message.docString = reader.string();
                    break;
                case 9:
                    message.rawData = reader.bytes();
                    break;
                case 13:
                    if (!(message.externalData && message.externalData.length))
                        message.externalData = [];
                    message.externalData.push($root.onnx.StringStringEntryProto.decode(reader, reader.uint32()));
                    break;
                case 14:
                    message.dataLocation = reader.int32();
                    break;
                case 10:
                    if (!(message.doubleData && message.doubleData.length))
                        message.doubleData = [];
                    if ((tag & 7) === 2) {
                        var end2 = reader.uint32() + reader.pos;
                        while (reader.pos < end2)
                            message.doubleData.push(reader.double());
                    } else
                        message.doubleData.push(reader.double());
                    break;
                case 11:
                    if (!(message.uint64Data && message.uint64Data.length))
                        message.uint64Data = [];
                    if ((tag & 7) === 2) {
                        var end2 = reader.uint32() + reader.pos;
                        while (reader.pos < end2)
                            message.uint64Data.push(reader.uint64());
                    } else
                        message.uint64Data.push(reader.uint64());
                    break;
                default:
                    reader.skipType(tag & 7);
                    break;
                }
            }
            return message;
        };

        /**
         * Decodes a TensorProto message from the specified reader or buffer, length delimited.
         * @function decodeDelimited
         * @memberof onnx.TensorProto
         * @static
         * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
         * @returns {onnx.TensorProto} TensorProto
         * @throws {Error} If the payload is not a reader or valid buffer
         * @throws {$protobuf.util.ProtocolError} If required fields are missing
         */
        TensorProto.decodeDelimited = function decodeDelimited(reader) {
            if (!(reader instanceof $Reader))
                reader = new $Reader(reader);
            return this.decode(reader, reader.uint32());
        };

        /**
         * Verifies a TensorProto message.
         * @function verify
         * @memberof onnx.TensorProto
         * @static
         * @param {Object.<string,*>} message Plain object to verify
         * @returns {string|null} `null` if valid, otherwise the reason why it is not
         */
        TensorProto.verify = function verify(message) {
            if (typeof message !== "object" || message === null)
                return "object expected";
            if (message.dims != null && message.hasOwnProperty("dims")) {
                if (!Array.isArray(message.dims))
                    return "dims: array expected";
                for (var i = 0; i < message.dims.length; ++i)
                    if (!$util.isInteger(message.dims[i]) && !(message.dims[i] && $util.isInteger(message.dims[i].low) && $util.isInteger(message.dims[i].high)))
                        return "dims: integer|Long[] expected";
            }
            if (message.dataType != null && message.hasOwnProperty("dataType"))
                if (!$util.isInteger(message.dataType))
                    return "dataType: integer expected";
            if (message.segment != null && message.hasOwnProperty("segment")) {
                var error = $root.onnx.TensorProto.Segment.verify(message.segment);
                if (error)
                    return "segment." + error;
            }
            if (message.floatData != null && message.hasOwnProperty("floatData")) {
                if (!Array.isArray(message.floatData))
                    return "floatData: array expected";
                for (var i = 0; i < message.floatData.length; ++i)
                    if (typeof message.floatData[i] !== "number")
                        return "floatData: number[] expected";
            }
            if (message.int32Data != null && message.hasOwnProperty("int32Data")) {
                if (!Array.isArray(message.int32Data))
                    return "int32Data: array expected";
                for (var i = 0; i < message.int32Data.length; ++i)
                    if (!$util.isInteger(message.int32Data[i]))
                        return "int32Data: integer[] expected";
            }
            if (message.stringData != null && message.hasOwnProperty("stringData")) {
                if (!Array.isArray(message.stringData))
                    return "stringData: array expected";
                for (var i = 0; i < message.stringData.length; ++i)
                    if (!(message.stringData[i] && typeof message.stringData[i].length === "number" || $util.isString(message.stringData[i])))
                        return "stringData: buffer[] expected";
            }
            if (message.int64Data != null && message.hasOwnProperty("int64Data")) {
                if (!Array.isArray(message.int64Data))
                    return "int64Data: array expected";
                for (var i = 0; i < message.int64Data.length; ++i)
                    if (!$util.isInteger(message.int64Data[i]) && !(message.int64Data[i] && $util.isInteger(message.int64Data[i].low) && $util.isInteger(message.int64Data[i].high)))
                        return "int64Data: integer|Long[] expected";
            }
            if (message.name != null && message.hasOwnProperty("name"))
                if (!$util.isString(message.name))
                    return "name: string expected";
            if (message.docString != null && message.hasOwnProperty("docString"))
                if (!$util.isString(message.docString))
                    return "docString: string expected";
            if (message.rawData != null && message.hasOwnProperty("rawData"))
                if (!(message.rawData && typeof message.rawData.length === "number" || $util.isString(message.rawData)))
                    return "rawData: buffer expected";
            if (message.externalData != null && message.hasOwnProperty("externalData")) {
                if (!Array.isArray(message.externalData))
                    return "externalData: array expected";
                for (var i = 0; i < message.externalData.length; ++i) {
                    var error = $root.onnx.StringStringEntryProto.verify(message.externalData[i]);
                    if (error)
                        return "externalData." + error;
                }
            }
            if (message.dataLocation != null && message.hasOwnProperty("dataLocation"))
                switch (message.dataLocation) {
                default:
                    return "dataLocation: enum value expected";
                case 0:
                case 1:
                    break;
                }
            if (message.doubleData != null && message.hasOwnProperty("doubleData")) {
                if (!Array.isArray(message.doubleData))
                    return "doubleData: array expected";
                for (var i = 0; i < message.doubleData.length; ++i)
                    if (typeof message.doubleData[i] !== "number")
                        return "doubleData: number[] expected";
            }
            if (message.uint64Data != null && message.hasOwnProperty("uint64Data")) {
                if (!Array.isArray(message.uint64Data))
                    return "uint64Data: array expected";
                for (var i = 0; i < message.uint64Data.length; ++i)
                    if (!$util.isInteger(message.uint64Data[i]) && !(message.uint64Data[i] && $util.isInteger(message.uint64Data[i].low) && $util.isInteger(message.uint64Data[i].high)))
                        return "uint64Data: integer|Long[] expected";
            }
            return null;
        };

        /**
         * Creates a TensorProto message from a plain object. Also converts values to their respective internal types.
         * @function fromObject
         * @memberof onnx.TensorProto
         * @static
         * @param {Object.<string,*>} object Plain object
         * @returns {onnx.TensorProto} TensorProto
         */
        TensorProto.fromObject = function fromObject(object) {
            if (object instanceof $root.onnx.TensorProto)
                return object;
            var message = new $root.onnx.TensorProto();
            if (object.dims) {
                if (!Array.isArray(object.dims))
                    throw TypeError(".onnx.TensorProto.dims: array expected");
                message.dims = [];
                for (var i = 0; i < object.dims.length; ++i)
                    if ($util.Long)
                        (message.dims[i] = $util.Long.fromValue(object.dims[i])).unsigned = false;
                    else if (typeof object.dims[i] === "string")
                        message.dims[i] = parseInt(object.dims[i], 10);
                    else if (typeof object.dims[i] === "number")
                        message.dims[i] = object.dims[i];
                    else if (typeof object.dims[i] === "object")
                        message.dims[i] = new $util.LongBits(object.dims[i].low >>> 0, object.dims[i].high >>> 0).toNumber();
            }
            if (object.dataType != null)
                message.dataType = object.dataType | 0;
            if (object.segment != null) {
                if (typeof object.segment !== "object")
                    throw TypeError(".onnx.TensorProto.segment: object expected");
                message.segment = $root.onnx.TensorProto.Segment.fromObject(object.segment);
            }
            if (object.floatData) {
                if (!Array.isArray(object.floatData))
                    throw TypeError(".onnx.TensorProto.floatData: array expected");
                message.floatData = [];
                for (var i = 0; i < object.floatData.length; ++i)
                    message.floatData[i] = Number(object.floatData[i]);
            }
            if (object.int32Data) {
                if (!Array.isArray(object.int32Data))
                    throw TypeError(".onnx.TensorProto.int32Data: array expected");
                message.int32Data = [];
                for (var i = 0; i < object.int32Data.length; ++i)
                    message.int32Data[i] = object.int32Data[i] | 0;
            }
            if (object.stringData) {
                if (!Array.isArray(object.stringData))
                    throw TypeError(".onnx.TensorProto.stringData: array expected");
                message.stringData = [];
                for (var i = 0; i < object.stringData.length; ++i)
                    if (typeof object.stringData[i] === "string")
                        $util.base64.decode(object.stringData[i], message.stringData[i] = $util.newBuffer($util.base64.length(object.stringData[i])), 0);
                    else if (object.stringData[i].length)
                        message.stringData[i] = object.stringData[i];
            }
            if (object.int64Data) {
                if (!Array.isArray(object.int64Data))
                    throw TypeError(".onnx.TensorProto.int64Data: array expected");
                message.int64Data = [];
                for (var i = 0; i < object.int64Data.length; ++i)
                    if ($util.Long)
                        (message.int64Data[i] = $util.Long.fromValue(object.int64Data[i])).unsigned = false;
                    else if (typeof object.int64Data[i] === "string")
                        message.int64Data[i] = parseInt(object.int64Data[i], 10);
                    else if (typeof object.int64Data[i] === "number")
                        message.int64Data[i] = object.int64Data[i];
                    else if (typeof object.int64Data[i] === "object")
                        message.int64Data[i] = new $util.LongBits(object.int64Data[i].low >>> 0, object.int64Data[i].high >>> 0).toNumber();
            }
            if (object.name != null)
                message.name = String(object.name);
            if (object.docString != null)
                message.docString = String(object.docString);
            if (object.rawData != null)
                if (typeof object.rawData === "string")
                    $util.base64.decode(object.rawData, message.rawData = $util.newBuffer($util.base64.length(object.rawData)), 0);
                else if (object.rawData.length)
                    message.rawData = object.rawData;
            if (object.externalData) {
                if (!Array.isArray(object.externalData))
                    throw TypeError(".onnx.TensorProto.externalData: array expected");
                message.externalData = [];
                for (var i = 0; i < object.externalData.length; ++i) {
                    if (typeof object.externalData[i] !== "object")
                        throw TypeError(".onnx.TensorProto.externalData: object expected");
                    message.externalData[i] = $root.onnx.StringStringEntryProto.fromObject(object.externalData[i]);
                }
            }
            switch (object.dataLocation) {
            case "DEFAULT":
            case 0:
                message.dataLocation = 0;
                break;
            case "EXTERNAL":
            case 1:
                message.dataLocation = 1;
                break;
            }
            if (object.doubleData) {
                if (!Array.isArray(object.doubleData))
                    throw TypeError(".onnx.TensorProto.doubleData: array expected");
                message.doubleData = [];
                for (var i = 0; i < object.doubleData.length; ++i)
                    message.doubleData[i] = Number(object.doubleData[i]);
            }
            if (object.uint64Data) {
                if (!Array.isArray(object.uint64Data))
                    throw TypeError(".onnx.TensorProto.uint64Data: array expected");
                message.uint64Data = [];
                for (var i = 0; i < object.uint64Data.length; ++i)
                    if ($util.Long)
                        (message.uint64Data[i] = $util.Long.fromValue(object.uint64Data[i])).unsigned = true;
                    else if (typeof object.uint64Data[i] === "string")
                        message.uint64Data[i] = parseInt(object.uint64Data[i], 10);
                    else if (typeof object.uint64Data[i] === "number")
                        message.uint64Data[i] = object.uint64Data[i];
                    else if (typeof object.uint64Data[i] === "object")
                        message.uint64Data[i] = new $util.LongBits(object.uint64Data[i].low >>> 0, object.uint64Data[i].high >>> 0).toNumber(true);
            }
            return message;
        };

        /**
         * Creates a plain object from a TensorProto message. Also converts values to other types if specified.
         * @function toObject
         * @memberof onnx.TensorProto
         * @static
         * @param {onnx.TensorProto} message TensorProto
         * @param {$protobuf.IConversionOptions} [options] Conversion options
         * @returns {Object.<string,*>} Plain object
         */
        TensorProto.toObject = function toObject(message, options) {
            if (!options)
                options = {};
            var object = {};
            if (options.arrays || options.defaults) {
                object.dims = [];
                object.floatData = [];
                object.int32Data = [];
                object.stringData = [];
                object.int64Data = [];
                object.doubleData = [];
                object.uint64Data = [];
                object.externalData = [];
            }
            if (options.defaults) {
                object.dataType = 0;
                object.segment = null;
                object.name = "";
                if (options.bytes === String)
                    object.rawData = "";
                else {
                    object.rawData = [];
                    if (options.bytes !== Array)
                        object.rawData = $util.newBuffer(object.rawData);
                }
                object.docString = "";
                object.dataLocation = options.enums === String ? "DEFAULT" : 0;
            }
            if (message.dims && message.dims.length) {
                object.dims = [];
                for (var j = 0; j < message.dims.length; ++j)
                    if (typeof message.dims[j] === "number")
                        object.dims[j] = options.longs === String ? String(message.dims[j]) : message.dims[j];
                    else
                        object.dims[j] = options.longs === String ? $util.Long.prototype.toString.call(message.dims[j]) : options.longs === Number ? new $util.LongBits(message.dims[j].low >>> 0, message.dims[j].high >>> 0).toNumber() : message.dims[j];
            }
            if (message.dataType != null && message.hasOwnProperty("dataType"))
                object.dataType = message.dataType;
            if (message.segment != null && message.hasOwnProperty("segment"))
                object.segment = $root.onnx.TensorProto.Segment.toObject(message.segment, options);
            if (message.floatData && message.floatData.length) {
                object.floatData = [];
                for (var j = 0; j < message.floatData.length; ++j)
                    object.floatData[j] = options.json && !isFinite(message.floatData[j]) ? String(message.floatData[j]) : message.floatData[j];
            }
            if (message.int32Data && message.int32Data.length) {
                object.int32Data = [];
                for (var j = 0; j < message.int32Data.length; ++j)
                    object.int32Data[j] = message.int32Data[j];
            }
            if (message.stringData && message.stringData.length) {
                object.stringData = [];
                for (var j = 0; j < message.stringData.length; ++j)
                    object.stringData[j] = options.bytes === String ? $util.base64.encode(message.stringData[j], 0, message.stringData[j].length) : options.bytes === Array ? Array.prototype.slice.call(message.stringData[j]) : message.stringData[j];
            }
            if (message.int64Data && message.int64Data.length) {
                object.int64Data = [];
                for (var j = 0; j < message.int64Data.length; ++j)
                    if (typeof message.int64Data[j] === "number")
                        object.int64Data[j] = options.longs === String ? String(message.int64Data[j]) : message.int64Data[j];
                    else
                        object.int64Data[j] = options.longs === String ? $util.Long.prototype.toString.call(message.int64Data[j]) : options.longs === Number ? new $util.LongBits(message.int64Data[j].low >>> 0, message.int64Data[j].high >>> 0).toNumber() : message.int64Data[j];
            }
            if (message.name != null && message.hasOwnProperty("name"))
                object.name = message.name;
            if (message.rawData != null && message.hasOwnProperty("rawData"))
                object.rawData = options.bytes === String ? $util.base64.encode(message.rawData, 0, message.rawData.length) : options.bytes === Array ? Array.prototype.slice.call(message.rawData) : message.rawData;
            if (message.doubleData && message.doubleData.length) {
                object.doubleData = [];
                for (var j = 0; j < message.doubleData.length; ++j)
                    object.doubleData[j] = options.json && !isFinite(message.doubleData[j]) ? String(message.doubleData[j]) : message.doubleData[j];
            }
            if (message.uint64Data && message.uint64Data.length) {
                object.uint64Data = [];
                for (var j = 0; j < message.uint64Data.length; ++j)
                    if (typeof message.uint64Data[j] === "number")
                        object.uint64Data[j] = options.longs === String ? String(message.uint64Data[j]) : message.uint64Data[j];
                    else
                        object.uint64Data[j] = options.longs === String ? $util.Long.prototype.toString.call(message.uint64Data[j]) : options.longs === Number ? new $util.LongBits(message.uint64Data[j].low >>> 0, message.uint64Data[j].high >>> 0).toNumber(true) : message.uint64Data[j];
            }
            if (message.docString != null && message.hasOwnProperty("docString"))
                object.docString = message.docString;
            if (message.externalData && message.externalData.length) {
                object.externalData = [];
                for (var j = 0; j < message.externalData.length; ++j)
                    object.externalData[j] = $root.onnx.StringStringEntryProto.toObject(message.externalData[j], options);
            }
            if (message.dataLocation != null && message.hasOwnProperty("dataLocation"))
                object.dataLocation = options.enums === String ? $root.onnx.TensorProto.DataLocation[message.dataLocation] : message.dataLocation;
            return object;
        };

        /**
         * Converts this TensorProto to JSON.
         * @function toJSON
         * @memberof onnx.TensorProto
         * @instance
         * @returns {Object.<string,*>} JSON object
         */
        TensorProto.prototype.toJSON = function toJSON() {
            return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
        };

        /**
         * DataType enum.
         * @name onnx.TensorProto.DataType
         * @enum {string}
         * @property {number} UNDEFINED=0 UNDEFINED value
         * @property {number} FLOAT=1 FLOAT value
         * @property {number} UINT8=2 UINT8 value
         * @property {number} INT8=3 INT8 value
         * @property {number} UINT16=4 UINT16 value
         * @property {number} INT16=5 INT16 value
         * @property {number} INT32=6 INT32 value
         * @property {number} INT64=7 INT64 value
         * @property {number} STRING=8 STRING value
         * @property {number} BOOL=9 BOOL value
         * @property {number} FLOAT16=10 FLOAT16 value
         * @property {number} DOUBLE=11 DOUBLE value
         * @property {number} UINT32=12 UINT32 value
         * @property {number} UINT64=13 UINT64 value
         * @property {number} COMPLEX64=14 COMPLEX64 value
         * @property {number} COMPLEX128=15 COMPLEX128 value
         * @property {number} BFLOAT16=16 BFLOAT16 value
         */
        TensorProto.DataType = (function() {
            var valuesById = {}, values = Object.create(valuesById);
            values[valuesById[0] = "UNDEFINED"] = 0;
            values[valuesById[1] = "FLOAT"] = 1;
            values[valuesById[2] = "UINT8"] = 2;
            values[valuesById[3] = "INT8"] = 3;
            values[valuesById[4] = "UINT16"] = 4;
            values[valuesById[5] = "INT16"] = 5;
            values[valuesById[6] = "INT32"] = 6;
            values[valuesById[7] = "INT64"] = 7;
            values[valuesById[8] = "STRING"] = 8;
            values[valuesById[9] = "BOOL"] = 9;
            values[valuesById[10] = "FLOAT16"] = 10;
            values[valuesById[11] = "DOUBLE"] = 11;
            values[valuesById[12] = "UINT32"] = 12;
            values[valuesById[13] = "UINT64"] = 13;
            values[valuesById[14] = "COMPLEX64"] = 14;
            values[valuesById[15] = "COMPLEX128"] = 15;
            values[valuesById[16] = "BFLOAT16"] = 16;
            return values;
        })();

        TensorProto.Segment = (function() {

            /**
             * Properties of a Segment.
             * @memberof onnx.TensorProto
             * @interface ISegment
             * @property {number|Long|null} [begin] Segment begin
             * @property {number|Long|null} [end] Segment end
             */

            /**
             * Constructs a new Segment.
             * @memberof onnx.TensorProto
             * @classdesc Represents a Segment.
             * @implements ISegment
             * @constructor
             * @param {onnx.TensorProto.ISegment=} [properties] Properties to set
             */
            function Segment(properties) {
                if (properties)
                    for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                        if (properties[keys[i]] != null)
                            this[keys[i]] = properties[keys[i]];
            }

            /**
             * Segment begin.
             * @member {number|Long} begin
             * @memberof onnx.TensorProto.Segment
             * @instance
             */
            Segment.prototype.begin = $util.Long ? $util.Long.fromBits(0,0,false) : 0;

            /**
             * Segment end.
             * @member {number|Long} end
             * @memberof onnx.TensorProto.Segment
             * @instance
             */
            Segment.prototype.end = $util.Long ? $util.Long.fromBits(0,0,false) : 0;

            /**
             * Creates a new Segment instance using the specified properties.
             * @function create
             * @memberof onnx.TensorProto.Segment
             * @static
             * @param {onnx.TensorProto.ISegment=} [properties] Properties to set
             * @returns {onnx.TensorProto.Segment} Segment instance
             */
            Segment.create = function create(properties) {
                return new Segment(properties);
            };

            /**
             * Encodes the specified Segment message. Does not implicitly {@link onnx.TensorProto.Segment.verify|verify} messages.
             * @function encode
             * @memberof onnx.TensorProto.Segment
             * @static
             * @param {onnx.TensorProto.ISegment} message Segment message or plain object to encode
             * @param {$protobuf.Writer} [writer] Writer to encode to
             * @returns {$protobuf.Writer} Writer
             */
            Segment.encode = function encode(message, writer) {
                if (!writer)
                    writer = $Writer.create();
                if (message.begin != null && message.hasOwnProperty("begin"))
                    writer.uint32(/* id 1, wireType 0 =*/8).int64(message.begin);
                if (message.end != null && message.hasOwnProperty("end"))
                    writer.uint32(/* id 2, wireType 0 =*/16).int64(message.end);
                return writer;
            };

            /**
             * Encodes the specified Segment message, length delimited. Does not implicitly {@link onnx.TensorProto.Segment.verify|verify} messages.
             * @function encodeDelimited
             * @memberof onnx.TensorProto.Segment
             * @static
             * @param {onnx.TensorProto.ISegment} message Segment message or plain object to encode
             * @param {$protobuf.Writer} [writer] Writer to encode to
             * @returns {$protobuf.Writer} Writer
             */
            Segment.encodeDelimited = function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
            };

            /**
             * Decodes a Segment message from the specified reader or buffer.
             * @function decode
             * @memberof onnx.TensorProto.Segment
             * @static
             * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
             * @param {number} [length] Message length if known beforehand
             * @returns {onnx.TensorProto.Segment} Segment
             * @throws {Error} If the payload is not a reader or valid buffer
             * @throws {$protobuf.util.ProtocolError} If required fields are missing
             */
            Segment.decode = function decode(reader, length) {
                if (!(reader instanceof $Reader))
                    reader = $Reader.create(reader);
                var end = length === undefined ? reader.len : reader.pos + length, message = new $root.onnx.TensorProto.Segment();
                while (reader.pos < end) {
                    var tag = reader.uint32();
                    switch (tag >>> 3) {
                    case 1:
                        message.begin = reader.int64();
                        break;
                    case 2:
                        message.end = reader.int64();
                        break;
                    default:
                        reader.skipType(tag & 7);
                        break;
                    }
                }
                return message;
            };

            /**
             * Decodes a Segment message from the specified reader or buffer, length delimited.
             * @function decodeDelimited
             * @memberof onnx.TensorProto.Segment
             * @static
             * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
             * @returns {onnx.TensorProto.Segment} Segment
             * @throws {Error} If the payload is not a reader or valid buffer
             * @throws {$protobuf.util.ProtocolError} If required fields are missing
             */
            Segment.decodeDelimited = function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                    reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
            };

            /**
             * Verifies a Segment message.
             * @function verify
             * @memberof onnx.TensorProto.Segment
             * @static
             * @param {Object.<string,*>} message Plain object to verify
             * @returns {string|null} `null` if valid, otherwise the reason why it is not
             */
            Segment.verify = function verify(message) {
                if (typeof message !== "object" || message === null)
                    return "object expected";
                if (message.begin != null && message.hasOwnProperty("begin"))
                    if (!$util.isInteger(message.begin) && !(message.begin && $util.isInteger(message.begin.low) && $util.isInteger(message.begin.high)))
                        return "begin: integer|Long expected";
                if (message.end != null && message.hasOwnProperty("end"))
                    if (!$util.isInteger(message.end) && !(message.end && $util.isInteger(message.end.low) && $util.isInteger(message.end.high)))
                        return "end: integer|Long expected";
                return null;
            };

            /**
             * Creates a Segment message from a plain object. Also converts values to their respective internal types.
             * @function fromObject
             * @memberof onnx.TensorProto.Segment
             * @static
             * @param {Object.<string,*>} object Plain object
             * @returns {onnx.TensorProto.Segment} Segment
             */
            Segment.fromObject = function fromObject(object) {
                if (object instanceof $root.onnx.TensorProto.Segment)
                    return object;
                var message = new $root.onnx.TensorProto.Segment();
                if (object.begin != null)
                    if ($util.Long)
                        (message.begin = $util.Long.fromValue(object.begin)).unsigned = false;
                    else if (typeof object.begin === "string")
                        message.begin = parseInt(object.begin, 10);
                    else if (typeof object.begin === "number")
                        message.begin = object.begin;
                    else if (typeof object.begin === "object")
                        message.begin = new $util.LongBits(object.begin.low >>> 0, object.begin.high >>> 0).toNumber();
                if (object.end != null)
                    if ($util.Long)
                        (message.end = $util.Long.fromValue(object.end)).unsigned = false;
                    else if (typeof object.end === "string")
                        message.end = parseInt(object.end, 10);
                    else if (typeof object.end === "number")
                        message.end = object.end;
                    else if (typeof object.end === "object")
                        message.end = new $util.LongBits(object.end.low >>> 0, object.end.high >>> 0).toNumber();
                return message;
            };

            /**
             * Creates a plain object from a Segment message. Also converts values to other types if specified.
             * @function toObject
             * @memberof onnx.TensorProto.Segment
             * @static
             * @param {onnx.TensorProto.Segment} message Segment
             * @param {$protobuf.IConversionOptions} [options] Conversion options
             * @returns {Object.<string,*>} Plain object
             */
            Segment.toObject = function toObject(message, options) {
                if (!options)
                    options = {};
                var object = {};
                if (options.defaults) {
                    if ($util.Long) {
                        var long = new $util.Long(0, 0, false);
                        object.begin = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long;
                    } else
                        object.begin = options.longs === String ? "0" : 0;
                    if ($util.Long) {
                        var long = new $util.Long(0, 0, false);
                        object.end = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long;
                    } else
                        object.end = options.longs === String ? "0" : 0;
                }
                if (message.begin != null && message.hasOwnProperty("begin"))
                    if (typeof message.begin === "number")
                        object.begin = options.longs === String ? String(message.begin) : message.begin;
                    else
                        object.begin = options.longs === String ? $util.Long.prototype.toString.call(message.begin) : options.longs === Number ? new $util.LongBits(message.begin.low >>> 0, message.begin.high >>> 0).toNumber() : message.begin;
                if (message.end != null && message.hasOwnProperty("end"))
                    if (typeof message.end === "number")
                        object.end = options.longs === String ? String(message.end) : message.end;
                    else
                        object.end = options.longs === String ? $util.Long.prototype.toString.call(message.end) : options.longs === Number ? new $util.LongBits(message.end.low >>> 0, message.end.high >>> 0).toNumber() : message.end;
                return object;
            };

            /**
             * Converts this Segment to JSON.
             * @function toJSON
             * @memberof onnx.TensorProto.Segment
             * @instance
             * @returns {Object.<string,*>} JSON object
             */
            Segment.prototype.toJSON = function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
            };

            return Segment;
        })();

        /**
         * DataLocation enum.
         * @name onnx.TensorProto.DataLocation
         * @enum {string}
         * @property {number} DEFAULT=0 DEFAULT value
         * @property {number} EXTERNAL=1 EXTERNAL value
         */
        TensorProto.DataLocation = (function() {
            var valuesById = {}, values = Object.create(valuesById);
            values[valuesById[0] = "DEFAULT"] = 0;
            values[valuesById[1] = "EXTERNAL"] = 1;
            return values;
        })();

        return TensorProto;
    })();

    onnx.TensorShapeProto = (function() {

        /**
         * Properties of a TensorShapeProto.
         * @memberof onnx
         * @interface ITensorShapeProto
         * @property {Array.<onnx.TensorShapeProto.IDimension>|null} [dim] TensorShapeProto dim
         */

        /**
         * Constructs a new TensorShapeProto.
         * @memberof onnx
         * @classdesc Represents a TensorShapeProto.
         * @implements ITensorShapeProto
         * @constructor
         * @param {onnx.ITensorShapeProto=} [properties] Properties to set
         */
        function TensorShapeProto(properties) {
            this.dim = [];
            if (properties)
                for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                        this[keys[i]] = properties[keys[i]];
        }

        /**
         * TensorShapeProto dim.
         * @member {Array.<onnx.TensorShapeProto.IDimension>} dim
         * @memberof onnx.TensorShapeProto
         * @instance
         */
        TensorShapeProto.prototype.dim = $util.emptyArray;

        /**
         * Creates a new TensorShapeProto instance using the specified properties.
         * @function create
         * @memberof onnx.TensorShapeProto
         * @static
         * @param {onnx.ITensorShapeProto=} [properties] Properties to set
         * @returns {onnx.TensorShapeProto} TensorShapeProto instance
         */
        TensorShapeProto.create = function create(properties) {
            return new TensorShapeProto(properties);
        };

        /**
         * Encodes the specified TensorShapeProto message. Does not implicitly {@link onnx.TensorShapeProto.verify|verify} messages.
         * @function encode
         * @memberof onnx.TensorShapeProto
         * @static
         * @param {onnx.ITensorShapeProto} message TensorShapeProto message or plain object to encode
         * @param {$protobuf.Writer} [writer] Writer to encode to
         * @returns {$protobuf.Writer} Writer
         */
        TensorShapeProto.encode = function encode(message, writer) {
            if (!writer)
                writer = $Writer.create();
            if (message.dim != null && message.dim.length)
                for (var i = 0; i < message.dim.length; ++i)
                    $root.onnx.TensorShapeProto.Dimension.encode(message.dim[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim();
            return writer;
        };

        /**
         * Encodes the specified TensorShapeProto message, length delimited. Does not implicitly {@link onnx.TensorShapeProto.verify|verify} messages.
         * @function encodeDelimited
         * @memberof onnx.TensorShapeProto
         * @static
         * @param {onnx.ITensorShapeProto} message TensorShapeProto message or plain object to encode
         * @param {$protobuf.Writer} [writer] Writer to encode to
         * @returns {$protobuf.Writer} Writer
         */
        TensorShapeProto.encodeDelimited = function encodeDelimited(message, writer) {
            return this.encode(message, writer).ldelim();
        };

        /**
         * Decodes a TensorShapeProto message from the specified reader or buffer.
         * @function decode
         * @memberof onnx.TensorShapeProto
         * @static
         * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
         * @param {number} [length] Message length if known beforehand
         * @returns {onnx.TensorShapeProto} TensorShapeProto
         * @throws {Error} If the payload is not a reader or valid buffer
         * @throws {$protobuf.util.ProtocolError} If required fields are missing
         */
        TensorShapeProto.decode = function decode(reader, length) {
            if (!(reader instanceof $Reader))
                reader = $Reader.create(reader);
            var end = length === undefined ? reader.len : reader.pos + length, message = new $root.onnx.TensorShapeProto();
            while (reader.pos < end) {
                var tag = reader.uint32();
                switch (tag >>> 3) {
                case 1:
                    if (!(message.dim && message.dim.length))
                        message.dim = [];
                    message.dim.push($root.onnx.TensorShapeProto.Dimension.decode(reader, reader.uint32()));
                    break;
                default:
                    reader.skipType(tag & 7);
                    break;
                }
            }
            return message;
        };

        /**
         * Decodes a TensorShapeProto message from the specified reader or buffer, length delimited.
         * @function decodeDelimited
         * @memberof onnx.TensorShapeProto
         * @static
         * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
         * @returns {onnx.TensorShapeProto} TensorShapeProto
         * @throws {Error} If the payload is not a reader or valid buffer
         * @throws {$protobuf.util.ProtocolError} If required fields are missing
         */
        TensorShapeProto.decodeDelimited = function decodeDelimited(reader) {
            if (!(reader instanceof $Reader))
                reader = new $Reader(reader);
            return this.decode(reader, reader.uint32());
        };

        /**
         * Verifies a TensorShapeProto message.
         * @function verify
         * @memberof onnx.TensorShapeProto
         * @static
         * @param {Object.<string,*>} message Plain object to verify
         * @returns {string|null} `null` if valid, otherwise the reason why it is not
         */
        TensorShapeProto.verify = function verify(message) {
            if (typeof message !== "object" || message === null)
                return "object expected";
            if (message.dim != null && message.hasOwnProperty("dim")) {
                if (!Array.isArray(message.dim))
                    return "dim: array expected";
                for (var i = 0; i < message.dim.length; ++i) {
                    var error = $root.onnx.TensorShapeProto.Dimension.verify(message.dim[i]);
                    if (error)
                        return "dim." + error;
                }
            }
            return null;
        };

        /**
         * Creates a TensorShapeProto message from a plain object. Also converts values to their respective internal types.
         * @function fromObject
         * @memberof onnx.TensorShapeProto
         * @static
         * @param {Object.<string,*>} object Plain object
         * @returns {onnx.TensorShapeProto} TensorShapeProto
         */
        TensorShapeProto.fromObject = function fromObject(object) {
            if (object instanceof $root.onnx.TensorShapeProto)
                return object;
            var message = new $root.onnx.TensorShapeProto();
            if (object.dim) {
                if (!Array.isArray(object.dim))
                    throw TypeError(".onnx.TensorShapeProto.dim: array expected");
                message.dim = [];
                for (var i = 0; i < object.dim.length; ++i) {
                    if (typeof object.dim[i] !== "object")
                        throw TypeError(".onnx.TensorShapeProto.dim: object expected");
                    message.dim[i] = $root.onnx.TensorShapeProto.Dimension.fromObject(object.dim[i]);
                }
            }
            return message;
        };

        /**
         * Creates a plain object from a TensorShapeProto message. Also converts values to other types if specified.
         * @function toObject
         * @memberof onnx.TensorShapeProto
         * @static
         * @param {onnx.TensorShapeProto} message TensorShapeProto
         * @param {$protobuf.IConversionOptions} [options] Conversion options
         * @returns {Object.<string,*>} Plain object
         */
        TensorShapeProto.toObject = function toObject(message, options) {
            if (!options)
                options = {};
            var object = {};
            if (options.arrays || options.defaults)
                object.dim = [];
            if (message.dim && message.dim.length) {
                object.dim = [];
                for (var j = 0; j < message.dim.length; ++j)
                    object.dim[j] = $root.onnx.TensorShapeProto.Dimension.toObject(message.dim[j], options);
            }
            return object;
        };

        /**
         * Converts this TensorShapeProto to JSON.
         * @function toJSON
         * @memberof onnx.TensorShapeProto
         * @instance
         * @returns {Object.<string,*>} JSON object
         */
        TensorShapeProto.prototype.toJSON = function toJSON() {
            return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
        };

        TensorShapeProto.Dimension = (function() {

            /**
             * Properties of a Dimension.
             * @memberof onnx.TensorShapeProto
             * @interface IDimension
             * @property {number|Long|null} [dimValue] Dimension dimValue
             * @property {string|null} [dimParam] Dimension dimParam
             * @property {string|null} [denotation] Dimension denotation
             */

            /**
             * Constructs a new Dimension.
             * @memberof onnx.TensorShapeProto
             * @classdesc Represents a Dimension.
             * @implements IDimension
             * @constructor
             * @param {onnx.TensorShapeProto.IDimension=} [properties] Properties to set
             */
            function Dimension(properties) {
                if (properties)
                    for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                        if (properties[keys[i]] != null)
                            this[keys[i]] = properties[keys[i]];
            }

            /**
             * Dimension dimValue.
             * @member {number|Long} dimValue
             * @memberof onnx.TensorShapeProto.Dimension
             * @instance
             */
            Dimension.prototype.dimValue = $util.Long ? $util.Long.fromBits(0,0,false) : 0;

            /**
             * Dimension dimParam.
             * @member {string} dimParam
             * @memberof onnx.TensorShapeProto.Dimension
             * @instance
             */
            Dimension.prototype.dimParam = "";

            /**
             * Dimension denotation.
             * @member {string} denotation
             * @memberof onnx.TensorShapeProto.Dimension
             * @instance
             */
            Dimension.prototype.denotation = "";

            // OneOf field names bound to virtual getters and setters
            var $oneOfFields;

            /**
             * Dimension value.
             * @member {"dimValue"|"dimParam"|undefined} value
             * @memberof onnx.TensorShapeProto.Dimension
             * @instance
             */
            Object.defineProperty(Dimension.prototype, "value", {
                get: $util.oneOfGetter($oneOfFields = ["dimValue", "dimParam"]),
                set: $util.oneOfSetter($oneOfFields)
            });

            /**
             * Creates a new Dimension instance using the specified properties.
             * @function create
             * @memberof onnx.TensorShapeProto.Dimension
             * @static
             * @param {onnx.TensorShapeProto.IDimension=} [properties] Properties to set
             * @returns {onnx.TensorShapeProto.Dimension} Dimension instance
             */
            Dimension.create = function create(properties) {
                return new Dimension(properties);
            };

            /**
             * Encodes the specified Dimension message. Does not implicitly {@link onnx.TensorShapeProto.Dimension.verify|verify} messages.
             * @function encode
             * @memberof onnx.TensorShapeProto.Dimension
             * @static
             * @param {onnx.TensorShapeProto.IDimension} message Dimension message or plain object to encode
             * @param {$protobuf.Writer} [writer] Writer to encode to
             * @returns {$protobuf.Writer} Writer
             */
            Dimension.encode = function encode(message, writer) {
                if (!writer)
                    writer = $Writer.create();
                if (message.dimValue != null && message.hasOwnProperty("dimValue"))
                    writer.uint32(/* id 1, wireType 0 =*/8).int64(message.dimValue);
                if (message.dimParam != null && message.hasOwnProperty("dimParam"))
                    writer.uint32(/* id 2, wireType 2 =*/18).string(message.dimParam);
                if (message.denotation != null && message.hasOwnProperty("denotation"))
                    writer.uint32(/* id 3, wireType 2 =*/26).string(message.denotation);
                return writer;
            };

            /**
             * Encodes the specified Dimension message, length delimited. Does not implicitly {@link onnx.TensorShapeProto.Dimension.verify|verify} messages.
             * @function encodeDelimited
             * @memberof onnx.TensorShapeProto.Dimension
             * @static
             * @param {onnx.TensorShapeProto.IDimension} message Dimension message or plain object to encode
             * @param {$protobuf.Writer} [writer] Writer to encode to
             * @returns {$protobuf.Writer} Writer
             */
            Dimension.encodeDelimited = function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
            };

            /**
             * Decodes a Dimension message from the specified reader or buffer.
             * @function decode
             * @memberof onnx.TensorShapeProto.Dimension
             * @static
             * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
             * @param {number} [length] Message length if known beforehand
             * @returns {onnx.TensorShapeProto.Dimension} Dimension
             * @throws {Error} If the payload is not a reader or valid buffer
             * @throws {$protobuf.util.ProtocolError} If required fields are missing
             */
            Dimension.decode = function decode(reader, length) {
                if (!(reader instanceof $Reader))
                    reader = $Reader.create(reader);
                var end = length === undefined ? reader.len : reader.pos + length, message = new $root.onnx.TensorShapeProto.Dimension();
                while (reader.pos < end) {
                    var tag = reader.uint32();
                    switch (tag >>> 3) {
                    case 1:
                        message.dimValue = reader.int64();
                        break;
                    case 2:
                        message.dimParam = reader.string();
                        break;
                    case 3:
                        message.denotation = reader.string();
                        break;
                    default:
                        reader.skipType(tag & 7);
                        break;
                    }
                }
                return message;
            };

            /**
             * Decodes a Dimension message from the specified reader or buffer, length delimited.
             * @function decodeDelimited
             * @memberof onnx.TensorShapeProto.Dimension
             * @static
             * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
             * @returns {onnx.TensorShapeProto.Dimension} Dimension
             * @throws {Error} If the payload is not a reader or valid buffer
             * @throws {$protobuf.util.ProtocolError} If required fields are missing
             */
            Dimension.decodeDelimited = function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                    reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
            };

            /**
             * Verifies a Dimension message.
             * @function verify
             * @memberof onnx.TensorShapeProto.Dimension
             * @static
             * @param {Object.<string,*>} message Plain object to verify
             * @returns {string|null} `null` if valid, otherwise the reason why it is not
             */
            Dimension.verify = function verify(message) {
                if (typeof message !== "object" || message === null)
                    return "object expected";
                var properties = {};
                if (message.dimValue != null && message.hasOwnProperty("dimValue")) {
                    properties.value = 1;
                    if (!$util.isInteger(message.dimValue) && !(message.dimValue && $util.isInteger(message.dimValue.low) && $util.isInteger(message.dimValue.high)))
                        return "dimValue: integer|Long expected";
                }
                if (message.dimParam != null && message.hasOwnProperty("dimParam")) {
                    if (properties.value === 1)
                        return "value: multiple values";
                    properties.value = 1;
                    if (!$util.isString(message.dimParam))
                        return "dimParam: string expected";
                }
                if (message.denotation != null && message.hasOwnProperty("denotation"))
                    if (!$util.isString(message.denotation))
                        return "denotation: string expected";
                return null;
            };

            /**
             * Creates a Dimension message from a plain object. Also converts values to their respective internal types.
             * @function fromObject
             * @memberof onnx.TensorShapeProto.Dimension
             * @static
             * @param {Object.<string,*>} object Plain object
             * @returns {onnx.TensorShapeProto.Dimension} Dimension
             */
            Dimension.fromObject = function fromObject(object) {
                if (object instanceof $root.onnx.TensorShapeProto.Dimension)
                    return object;
                var message = new $root.onnx.TensorShapeProto.Dimension();
                if (object.dimValue != null)
                    if ($util.Long)
                        (message.dimValue = $util.Long.fromValue(object.dimValue)).unsigned = false;
                    else if (typeof object.dimValue === "string")
                        message.dimValue = parseInt(object.dimValue, 10);
                    else if (typeof object.dimValue === "number")
                        message.dimValue = object.dimValue;
                    else if (typeof object.dimValue === "object")
                        message.dimValue = new $util.LongBits(object.dimValue.low >>> 0, object.dimValue.high >>> 0).toNumber();
                if (object.dimParam != null)
                    message.dimParam = String(object.dimParam);
                if (object.denotation != null)
                    message.denotation = String(object.denotation);
                return message;
            };

            /**
             * Creates a plain object from a Dimension message. Also converts values to other types if specified.
             * @function toObject
             * @memberof onnx.TensorShapeProto.Dimension
             * @static
             * @param {onnx.TensorShapeProto.Dimension} message Dimension
             * @param {$protobuf.IConversionOptions} [options] Conversion options
             * @returns {Object.<string,*>} Plain object
             */
            Dimension.toObject = function toObject(message, options) {
                if (!options)
                    options = {};
                var object = {};
                if (options.defaults)
                    object.denotation = "";
                if (message.dimValue != null && message.hasOwnProperty("dimValue")) {
                    if (typeof message.dimValue === "number")
                        object.dimValue = options.longs === String ? String(message.dimValue) : message.dimValue;
                    else
                        object.dimValue = options.longs === String ? $util.Long.prototype.toString.call(message.dimValue) : options.longs === Number ? new $util.LongBits(message.dimValue.low >>> 0, message.dimValue.high >>> 0).toNumber() : message.dimValue;
                    if (options.oneofs)
                        object.value = "dimValue";
                }
                if (message.dimParam != null && message.hasOwnProperty("dimParam")) {
                    object.dimParam = message.dimParam;
                    if (options.oneofs)
                        object.value = "dimParam";
                }
                if (message.denotation != null && message.hasOwnProperty("denotation"))
                    object.denotation = message.denotation;
                return object;
            };

            /**
             * Converts this Dimension to JSON.
             * @function toJSON
             * @memberof onnx.TensorShapeProto.Dimension
             * @instance
             * @returns {Object.<string,*>} JSON object
             */
            Dimension.prototype.toJSON = function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
            };

            return Dimension;
        })();

        return TensorShapeProto;
    })();

    onnx.TypeProto = (function() {

        /**
         * Properties of a TypeProto.
         * @memberof onnx
         * @interface ITypeProto
         * @property {onnx.TypeProto.ITensor|null} [tensorType] TypeProto tensorType
         * @property {string|null} [denotation] TypeProto denotation
         */

        /**
         * Constructs a new TypeProto.
         * @memberof onnx
         * @classdesc Represents a TypeProto.
         * @implements ITypeProto
         * @constructor
         * @param {onnx.ITypeProto=} [properties] Properties to set
         */
        function TypeProto(properties) {
            if (properties)
                for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                        this[keys[i]] = properties[keys[i]];
        }

        /**
         * TypeProto tensorType.
         * @member {onnx.TypeProto.ITensor|null|undefined} tensorType
         * @memberof onnx.TypeProto
         * @instance
         */
        TypeProto.prototype.tensorType = null;

        /**
         * TypeProto denotation.
         * @member {string} denotation
         * @memberof onnx.TypeProto
         * @instance
         */
        TypeProto.prototype.denotation = "";

        // OneOf field names bound to virtual getters and setters
        var $oneOfFields;

        /**
         * TypeProto value.
         * @member {"tensorType"|undefined} value
         * @memberof onnx.TypeProto
         * @instance
         */
        Object.defineProperty(TypeProto.prototype, "value", {
            get: $util.oneOfGetter($oneOfFields = ["tensorType"]),
            set: $util.oneOfSetter($oneOfFields)
        });

        /**
         * Creates a new TypeProto instance using the specified properties.
         * @function create
         * @memberof onnx.TypeProto
         * @static
         * @param {onnx.ITypeProto=} [properties] Properties to set
         * @returns {onnx.TypeProto} TypeProto instance
         */
        TypeProto.create = function create(properties) {
            return new TypeProto(properties);
        };

        /**
         * Encodes the specified TypeProto message. Does not implicitly {@link onnx.TypeProto.verify|verify} messages.
         * @function encode
         * @memberof onnx.TypeProto
         * @static
         * @param {onnx.ITypeProto} message TypeProto message or plain object to encode
         * @param {$protobuf.Writer} [writer] Writer to encode to
         * @returns {$protobuf.Writer} Writer
         */
        TypeProto.encode = function encode(message, writer) {
            if (!writer)
                writer = $Writer.create();
            if (message.tensorType != null && message.hasOwnProperty("tensorType"))
                $root.onnx.TypeProto.Tensor.encode(message.tensorType, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim();
            if (message.denotation != null && message.hasOwnProperty("denotation"))
                writer.uint32(/* id 6, wireType 2 =*/50).string(message.denotation);
            return writer;
        };

        /**
         * Encodes the specified TypeProto message, length delimited. Does not implicitly {@link onnx.TypeProto.verify|verify} messages.
         * @function encodeDelimited
         * @memberof onnx.TypeProto
         * @static
         * @param {onnx.ITypeProto} message TypeProto message or plain object to encode
         * @param {$protobuf.Writer} [writer] Writer to encode to
         * @returns {$protobuf.Writer} Writer
         */
        TypeProto.encodeDelimited = function encodeDelimited(message, writer) {
            return this.encode(message, writer).ldelim();
        };

        /**
         * Decodes a TypeProto message from the specified reader or buffer.
         * @function decode
         * @memberof onnx.TypeProto
         * @static
         * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
         * @param {number} [length] Message length if known beforehand
         * @returns {onnx.TypeProto} TypeProto
         * @throws {Error} If the payload is not a reader or valid buffer
         * @throws {$protobuf.util.ProtocolError} If required fields are missing
         */
        TypeProto.decode = function decode(reader, length) {
            if (!(reader instanceof $Reader))
                reader = $Reader.create(reader);
            var end = length === undefined ? reader.len : reader.pos + length, message = new $root.onnx.TypeProto();
            while (reader.pos < end) {
                var tag = reader.uint32();
                switch (tag >>> 3) {
                case 1:
                    message.tensorType = $root.onnx.TypeProto.Tensor.decode(reader, reader.uint32());
                    break;
                case 6:
                    message.denotation = reader.string();
                    break;
                default:
                    reader.skipType(tag & 7);
                    break;
                }
            }
            return message;
        };

        /**
         * Decodes a TypeProto message from the specified reader or buffer, length delimited.
         * @function decodeDelimited
         * @memberof onnx.TypeProto
         * @static
         * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
         * @returns {onnx.TypeProto} TypeProto
         * @throws {Error} If the payload is not a reader or valid buffer
         * @throws {$protobuf.util.ProtocolError} If required fields are missing
         */
        TypeProto.decodeDelimited = function decodeDelimited(reader) {
            if (!(reader instanceof $Reader))
                reader = new $Reader(reader);
            return this.decode(reader, reader.uint32());
        };

        /**
         * Verifies a TypeProto message.
         * @function verify
         * @memberof onnx.TypeProto
         * @static
         * @param {Object.<string,*>} message Plain object to verify
         * @returns {string|null} `null` if valid, otherwise the reason why it is not
         */
        TypeProto.verify = function verify(message) {
            if (typeof message !== "object" || message === null)
                return "object expected";
            var properties = {};
            if (message.tensorType != null && message.hasOwnProperty("tensorType")) {
                properties.value = 1;
                {
                    var error = $root.onnx.TypeProto.Tensor.verify(message.tensorType);
                    if (error)
                        return "tensorType." + error;
                }
            }
            if (message.denotation != null && message.hasOwnProperty("denotation"))
                if (!$util.isString(message.denotation))
                    return "denotation: string expected";
            return null;
        };

        /**
         * Creates a TypeProto message from a plain object. Also converts values to their respective internal types.
         * @function fromObject
         * @memberof onnx.TypeProto
         * @static
         * @param {Object.<string,*>} object Plain object
         * @returns {onnx.TypeProto} TypeProto
         */
        TypeProto.fromObject = function fromObject(object) {
            if (object instanceof $root.onnx.TypeProto)
                return object;
            var message = new $root.onnx.TypeProto();
            if (object.tensorType != null) {
                if (typeof object.tensorType !== "object")
                    throw TypeError(".onnx.TypeProto.tensorType: object expected");
                message.tensorType = $root.onnx.TypeProto.Tensor.fromObject(object.tensorType);
            }
            if (object.denotation != null)
                message.denotation = String(object.denotation);
            return message;
        };

        /**
         * Creates a plain object from a TypeProto message. Also converts values to other types if specified.
         * @function toObject
         * @memberof onnx.TypeProto
         * @static
         * @param {onnx.TypeProto} message TypeProto
         * @param {$protobuf.IConversionOptions} [options] Conversion options
         * @returns {Object.<string,*>} Plain object
         */
        TypeProto.toObject = function toObject(message, options) {
            if (!options)
                options = {};
            var object = {};
            if (options.defaults)
                object.denotation = "";
            if (message.tensorType != null && message.hasOwnProperty("tensorType")) {
                object.tensorType = $root.onnx.TypeProto.Tensor.toObject(message.tensorType, options);
                if (options.oneofs)
                    object.value = "tensorType";
            }
            if (message.denotation != null && message.hasOwnProperty("denotation"))
                object.denotation = message.denotation;
            return object;
        };

        /**
         * Converts this TypeProto to JSON.
         * @function toJSON
         * @memberof onnx.TypeProto
         * @instance
         * @returns {Object.<string,*>} JSON object
         */
        TypeProto.prototype.toJSON = function toJSON() {
            return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
        };

        TypeProto.Tensor = (function() {

            /**
             * Properties of a Tensor.
             * @memberof onnx.TypeProto
             * @interface ITensor
             * @property {number|null} [elemType] Tensor elemType
             * @property {onnx.ITensorShapeProto|null} [shape] Tensor shape
             */

            /**
             * Constructs a new Tensor.
             * @memberof onnx.TypeProto
             * @classdesc Represents a Tensor.
             * @implements ITensor
             * @constructor
             * @param {onnx.TypeProto.ITensor=} [properties] Properties to set
             */
            function Tensor(properties) {
                if (properties)
                    for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                        if (properties[keys[i]] != null)
                            this[keys[i]] = properties[keys[i]];
            }

            /**
             * Tensor elemType.
             * @member {number} elemType
             * @memberof onnx.TypeProto.Tensor
             * @instance
             */
            Tensor.prototype.elemType = 0;

            /**
             * Tensor shape.
             * @member {onnx.ITensorShapeProto|null|undefined} shape
             * @memberof onnx.TypeProto.Tensor
             * @instance
             */
            Tensor.prototype.shape = null;

            /**
             * Creates a new Tensor instance using the specified properties.
             * @function create
             * @memberof onnx.TypeProto.Tensor
             * @static
             * @param {onnx.TypeProto.ITensor=} [properties] Properties to set
             * @returns {onnx.TypeProto.Tensor} Tensor instance
             */
            Tensor.create = function create(properties) {
                return new Tensor(properties);
            };

            /**
             * Encodes the specified Tensor message. Does not implicitly {@link onnx.TypeProto.Tensor.verify|verify} messages.
             * @function encode
             * @memberof onnx.TypeProto.Tensor
             * @static
             * @param {onnx.TypeProto.ITensor} message Tensor message or plain object to encode
             * @param {$protobuf.Writer} [writer] Writer to encode to
             * @returns {$protobuf.Writer} Writer
             */
            Tensor.encode = function encode(message, writer) {
                if (!writer)
                    writer = $Writer.create();
                if (message.elemType != null && message.hasOwnProperty("elemType"))
                    writer.uint32(/* id 1, wireType 0 =*/8).int32(message.elemType);
                if (message.shape != null && message.hasOwnProperty("shape"))
                    $root.onnx.TensorShapeProto.encode(message.shape, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim();
                return writer;
            };

            /**
             * Encodes the specified Tensor message, length delimited. Does not implicitly {@link onnx.TypeProto.Tensor.verify|verify} messages.
             * @function encodeDelimited
             * @memberof onnx.TypeProto.Tensor
             * @static
             * @param {onnx.TypeProto.ITensor} message Tensor message or plain object to encode
             * @param {$protobuf.Writer} [writer] Writer to encode to
             * @returns {$protobuf.Writer} Writer
             */
            Tensor.encodeDelimited = function encodeDelimited(message, writer) {
                return this.encode(message, writer).ldelim();
            };

            /**
             * Decodes a Tensor message from the specified reader or buffer.
             * @function decode
             * @memberof onnx.TypeProto.Tensor
             * @static
             * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
             * @param {number} [length] Message length if known beforehand
             * @returns {onnx.TypeProto.Tensor} Tensor
             * @throws {Error} If the payload is not a reader or valid buffer
             * @throws {$protobuf.util.ProtocolError} If required fields are missing
             */
            Tensor.decode = function decode(reader, length) {
                if (!(reader instanceof $Reader))
                    reader = $Reader.create(reader);
                var end = length === undefined ? reader.len : reader.pos + length, message = new $root.onnx.TypeProto.Tensor();
                while (reader.pos < end) {
                    var tag = reader.uint32();
                    switch (tag >>> 3) {
                    case 1:
                        message.elemType = reader.int32();
                        break;
                    case 2:
                        message.shape = $root.onnx.TensorShapeProto.decode(reader, reader.uint32());
                        break;
                    default:
                        reader.skipType(tag & 7);
                        break;
                    }
                }
                return message;
            };

            /**
             * Decodes a Tensor message from the specified reader or buffer, length delimited.
             * @function decodeDelimited
             * @memberof onnx.TypeProto.Tensor
             * @static
             * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
             * @returns {onnx.TypeProto.Tensor} Tensor
             * @throws {Error} If the payload is not a reader or valid buffer
             * @throws {$protobuf.util.ProtocolError} If required fields are missing
             */
            Tensor.decodeDelimited = function decodeDelimited(reader) {
                if (!(reader instanceof $Reader))
                    reader = new $Reader(reader);
                return this.decode(reader, reader.uint32());
            };

            /**
             * Verifies a Tensor message.
             * @function verify
             * @memberof onnx.TypeProto.Tensor
             * @static
             * @param {Object.<string,*>} message Plain object to verify
             * @returns {string|null} `null` if valid, otherwise the reason why it is not
             */
            Tensor.verify = function verify(message) {
                if (typeof message !== "object" || message === null)
                    return "object expected";
                if (message.elemType != null && message.hasOwnProperty("elemType"))
                    if (!$util.isInteger(message.elemType))
                        return "elemType: integer expected";
                if (message.shape != null && message.hasOwnProperty("shape")) {
                    var error = $root.onnx.TensorShapeProto.verify(message.shape);
                    if (error)
                        return "shape." + error;
                }
                return null;
            };

            /**
             * Creates a Tensor message from a plain object. Also converts values to their respective internal types.
             * @function fromObject
             * @memberof onnx.TypeProto.Tensor
             * @static
             * @param {Object.<string,*>} object Plain object
             * @returns {onnx.TypeProto.Tensor} Tensor
             */
            Tensor.fromObject = function fromObject(object) {
                if (object instanceof $root.onnx.TypeProto.Tensor)
                    return object;
                var message = new $root.onnx.TypeProto.Tensor();
                if (object.elemType != null)
                    message.elemType = object.elemType | 0;
                if (object.shape != null) {
                    if (typeof object.shape !== "object")
                        throw TypeError(".onnx.TypeProto.Tensor.shape: object expected");
                    message.shape = $root.onnx.TensorShapeProto.fromObject(object.shape);
                }
                return message;
            };

            /**
             * Creates a plain object from a Tensor message. Also converts values to other types if specified.
             * @function toObject
             * @memberof onnx.TypeProto.Tensor
             * @static
             * @param {onnx.TypeProto.Tensor} message Tensor
             * @param {$protobuf.IConversionOptions} [options] Conversion options
             * @returns {Object.<string,*>} Plain object
             */
            Tensor.toObject = function toObject(message, options) {
                if (!options)
                    options = {};
                var object = {};
                if (options.defaults) {
                    object.elemType = 0;
                    object.shape = null;
                }
                if (message.elemType != null && message.hasOwnProperty("elemType"))
                    object.elemType = message.elemType;
                if (message.shape != null && message.hasOwnProperty("shape"))
                    object.shape = $root.onnx.TensorShapeProto.toObject(message.shape, options);
                return object;
            };

            /**
             * Converts this Tensor to JSON.
             * @function toJSON
             * @memberof onnx.TypeProto.Tensor
             * @instance
             * @returns {Object.<string,*>} JSON object
             */
            Tensor.prototype.toJSON = function toJSON() {
                return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
            };

            return Tensor;
        })();

        return TypeProto;
    })();

    onnx.OperatorSetIdProto = (function() {

        /**
         * Properties of an OperatorSetIdProto.
         * @memberof onnx
         * @interface IOperatorSetIdProto
         * @property {string|null} [domain] OperatorSetIdProto domain
         * @property {number|Long|null} [version] OperatorSetIdProto version
         */

        /**
         * Constructs a new OperatorSetIdProto.
         * @memberof onnx
         * @classdesc Represents an OperatorSetIdProto.
         * @implements IOperatorSetIdProto
         * @constructor
         * @param {onnx.IOperatorSetIdProto=} [properties] Properties to set
         */
        function OperatorSetIdProto(properties) {
            if (properties)
                for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
                    if (properties[keys[i]] != null)
                        this[keys[i]] = properties[keys[i]];
        }

        /**
         * OperatorSetIdProto domain.
         * @member {string} domain
         * @memberof onnx.OperatorSetIdProto
         * @instance
         */
        OperatorSetIdProto.prototype.domain = "";

        /**
         * OperatorSetIdProto version.
         * @member {number|Long} version
         * @memberof onnx.OperatorSetIdProto
         * @instance
         */
        OperatorSetIdProto.prototype.version = $util.Long ? $util.Long.fromBits(0,0,false) : 0;

        /**
         * Creates a new OperatorSetIdProto instance using the specified properties.
         * @function create
         * @memberof onnx.OperatorSetIdProto
         * @static
         * @param {onnx.IOperatorSetIdProto=} [properties] Properties to set
         * @returns {onnx.OperatorSetIdProto} OperatorSetIdProto instance
         */
        OperatorSetIdProto.create = function create(properties) {
            return new OperatorSetIdProto(properties);
        };

        /**
         * Encodes the specified OperatorSetIdProto message. Does not implicitly {@link onnx.OperatorSetIdProto.verify|verify} messages.
         * @function encode
         * @memberof onnx.OperatorSetIdProto
         * @static
         * @param {onnx.IOperatorSetIdProto} message OperatorSetIdProto message or plain object to encode
         * @param {$protobuf.Writer} [writer] Writer to encode to
         * @returns {$protobuf.Writer} Writer
         */
        OperatorSetIdProto.encode = function encode(message, writer) {
            if (!writer)
                writer = $Writer.create();
            if (message.domain != null && message.hasOwnProperty("domain"))
                writer.uint32(/* id 1, wireType 2 =*/10).string(message.domain);
            if (message.version != null && message.hasOwnProperty("version"))
                writer.uint32(/* id 2, wireType 0 =*/16).int64(message.version);
            return writer;
        };

        /**
         * Encodes the specified OperatorSetIdProto message, length delimited. Does not implicitly {@link onnx.OperatorSetIdProto.verify|verify} messages.
         * @function encodeDelimited
         * @memberof onnx.OperatorSetIdProto
         * @static
         * @param {onnx.IOperatorSetIdProto} message OperatorSetIdProto message or plain object to encode
         * @param {$protobuf.Writer} [writer] Writer to encode to
         * @returns {$protobuf.Writer} Writer
         */
        OperatorSetIdProto.encodeDelimited = function encodeDelimited(message, writer) {
            return this.encode(message, writer).ldelim();
        };

        /**
         * Decodes an OperatorSetIdProto message from the specified reader or buffer.
         * @function decode
         * @memberof onnx.OperatorSetIdProto
         * @static
         * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
         * @param {number} [length] Message length if known beforehand
         * @returns {onnx.OperatorSetIdProto} OperatorSetIdProto
         * @throws {Error} If the payload is not a reader or valid buffer
         * @throws {$protobuf.util.ProtocolError} If required fields are missing
         */
        OperatorSetIdProto.decode = function decode(reader, length) {
            if (!(reader instanceof $Reader))
                reader = $Reader.create(reader);
            var end = length === undefined ? reader.len : reader.pos + length, message = new $root.onnx.OperatorSetIdProto();
            while (reader.pos < end) {
                var tag = reader.uint32();
                switch (tag >>> 3) {
                case 1:
                    message.domain = reader.string();
                    break;
                case 2:
                    message.version = reader.int64();
                    break;
                default:
                    reader.skipType(tag & 7);
                    break;
                }
            }
            return message;
        };

        /**
         * Decodes an OperatorSetIdProto message from the specified reader or buffer, length delimited.
         * @function decodeDelimited
         * @memberof onnx.OperatorSetIdProto
         * @static
         * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
         * @returns {onnx.OperatorSetIdProto} OperatorSetIdProto
         * @throws {Error} If the payload is not a reader or valid buffer
         * @throws {$protobuf.util.ProtocolError} If required fields are missing
         */
        OperatorSetIdProto.decodeDelimited = function decodeDelimited(reader) {
            if (!(reader instanceof $Reader))
                reader = new $Reader(reader);
            return this.decode(reader, reader.uint32());
        };

        /**
         * Verifies an OperatorSetIdProto message.
         * @function verify
         * @memberof onnx.OperatorSetIdProto
         * @static
         * @param {Object.<string,*>} message Plain object to verify
         * @returns {string|null} `null` if valid, otherwise the reason why it is not
         */
        OperatorSetIdProto.verify = function verify(message) {
            if (typeof message !== "object" || message === null)
                return "object expected";
            if (message.domain != null && message.hasOwnProperty("domain"))
                if (!$util.isString(message.domain))
                    return "domain: string expected";
            if (message.version != null && message.hasOwnProperty("version"))
                if (!$util.isInteger(message.version) && !(message.version && $util.isInteger(message.version.low) && $util.isInteger(message.version.high)))
                    return "version: integer|Long expected";
            return null;
        };

        /**
         * Creates an OperatorSetIdProto message from a plain object. Also converts values to their respective internal types.
         * @function fromObject
         * @memberof onnx.OperatorSetIdProto
         * @static
         * @param {Object.<string,*>} object Plain object
         * @returns {onnx.OperatorSetIdProto} OperatorSetIdProto
         */
        OperatorSetIdProto.fromObject = function fromObject(object) {
            if (object instanceof $root.onnx.OperatorSetIdProto)
                return object;
            var message = new $root.onnx.OperatorSetIdProto();
            if (object.domain != null)
                message.domain = String(object.domain);
            if (object.version != null)
                if ($util.Long)
                    (message.version = $util.Long.fromValue(object.version)).unsigned = false;
                else if (typeof object.version === "string")
                    message.version = parseInt(object.version, 10);
                else if (typeof object.version === "number")
                    message.version = object.version;
                else if (typeof object.version === "object")
                    message.version = new $util.LongBits(object.version.low >>> 0, object.version.high >>> 0).toNumber();
            return message;
        };

        /**
         * Creates a plain object from an OperatorSetIdProto message. Also converts values to other types if specified.
         * @function toObject
         * @memberof onnx.OperatorSetIdProto
         * @static
         * @param {onnx.OperatorSetIdProto} message OperatorSetIdProto
         * @param {$protobuf.IConversionOptions} [options] Conversion options
         * @returns {Object.<string,*>} Plain object
         */
        OperatorSetIdProto.toObject = function toObject(message, options) {
            if (!options)
                options = {};
            var object = {};
            if (options.defaults) {
                object.domain = "";
                if ($util.Long) {
                    var long = new $util.Long(0, 0, false);
                    object.version = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long;
                } else
                    object.version = options.longs === String ? "0" : 0;
            }
            if (message.domain != null && message.hasOwnProperty("domain"))
                object.domain = message.domain;
            if (message.version != null && message.hasOwnProperty("version"))
                if (typeof message.version === "number")
                    object.version = options.longs === String ? String(message.version) : message.version;
                else
                    object.version = options.longs === String ? $util.Long.prototype.toString.call(message.version) : options.longs === Number ? new $util.LongBits(message.version.low >>> 0, message.version.high >>> 0).toNumber() : message.version;
            return object;
        };

        /**
         * Converts this OperatorSetIdProto to JSON.
         * @function toJSON
         * @memberof onnx.OperatorSetIdProto
         * @instance
         * @returns {Object.<string,*>} JSON object
         */
        OperatorSetIdProto.prototype.toJSON = function toJSON() {
            return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
        };

        return OperatorSetIdProto;
    })();

    return onnx;
})();

module.exports = $root;


/***/ }),

/***/ "./node_modules/protobufjs/minimal.js":
/*!********************************************!*\
  !*** ./node_modules/protobufjs/minimal.js ***!
  \********************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";
// minimal library entry point.


module.exports = __webpack_require__(/*! ./src/index-minimal */ "./node_modules/protobufjs/src/index-minimal.js");


/***/ }),

/***/ "./node_modules/protobufjs/src/index-minimal.js":
/*!******************************************************!*\
  !*** ./node_modules/protobufjs/src/index-minimal.js ***!
  \******************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

var protobuf = exports;

/**
 * Build type, one of `"full"`, `"light"` or `"minimal"`.
 * @name build
 * @type {string}
 * @const
 */
protobuf.build = "minimal";

// Serialization
protobuf.Writer       = __webpack_require__(/*! ./writer */ "./node_modules/protobufjs/src/writer.js");
protobuf.BufferWriter = __webpack_require__(/*! ./writer_buffer */ "./node_modules/protobufjs/src/writer_buffer.js");
protobuf.Reader       = __webpack_require__(/*! ./reader */ "./node_modules/protobufjs/src/reader.js");
protobuf.BufferReader = __webpack_require__(/*! ./reader_buffer */ "./node_modules/protobufjs/src/reader_buffer.js");

// Utility
protobuf.util         = __webpack_require__(/*! ./util/minimal */ "./node_modules/protobufjs/src/util/minimal.js");
protobuf.rpc          = __webpack_require__(/*! ./rpc */ "./node_modules/protobufjs/src/rpc.js");
protobuf.roots        = __webpack_require__(/*! ./roots */ "./node_modules/protobufjs/src/roots.js");
protobuf.configure    = configure;

/* istanbul ignore next */
/**
 * Reconfigures the library according to the environment.
 * @returns {undefined}
 */
function configure() {
    protobuf.util._configure();
    protobuf.Writer._configure(protobuf.BufferWriter);
    protobuf.Reader._configure(protobuf.BufferReader);
}

// Set up buffer utility according to the environment
configure();


/***/ }),

/***/ "./node_modules/protobufjs/src/reader.js":
/*!***********************************************!*\
  !*** ./node_modules/protobufjs/src/reader.js ***!
  \***********************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

module.exports = Reader;

var util      = __webpack_require__(/*! ./util/minimal */ "./node_modules/protobufjs/src/util/minimal.js");

var BufferReader; // cyclic

var LongBits  = util.LongBits,
    utf8      = util.utf8;

/* istanbul ignore next */
function indexOutOfRange(reader, writeLength) {
    return RangeError("index out of range: " + reader.pos + " + " + (writeLength || 1) + " > " + reader.len);
}

/**
 * Constructs a new reader instance using the specified buffer.
 * @classdesc Wire format reader using `Uint8Array` if available, otherwise `Array`.
 * @constructor
 * @param {Uint8Array} buffer Buffer to read from
 */
function Reader(buffer) {

    /**
     * Read buffer.
     * @type {Uint8Array}
     */
    this.buf = buffer;

    /**
     * Read buffer position.
     * @type {number}
     */
    this.pos = 0;

    /**
     * Read buffer length.
     * @type {number}
     */
    this.len = buffer.length;
}

var create_array = typeof Uint8Array !== "undefined"
    ? function create_typed_array(buffer) {
        if (buffer instanceof Uint8Array || Array.isArray(buffer))
            return new Reader(buffer);
        throw Error("illegal buffer");
    }
    /* istanbul ignore next */
    : function create_array(buffer) {
        if (Array.isArray(buffer))
            return new Reader(buffer);
        throw Error("illegal buffer");
    };

var create = function create() {
    return util.Buffer
        ? function create_buffer_setup(buffer) {
            return (Reader.create = function create_buffer(buffer) {
                return util.Buffer.isBuffer(buffer)
                    ? new BufferReader(buffer)
                    /* istanbul ignore next */
                    : create_array(buffer);
            })(buffer);
        }
        /* istanbul ignore next */
        : create_array;
};

/**
 * Creates a new reader using the specified buffer.
 * @function
 * @param {Uint8Array|Buffer} buffer Buffer to read from
 * @returns {Reader|BufferReader} A {@link BufferReader} if `buffer` is a Buffer, otherwise a {@link Reader}
 * @throws {Error} If `buffer` is not a valid buffer
 */
Reader.create = create();

Reader.prototype._slice = util.Array.prototype.subarray || /* istanbul ignore next */ util.Array.prototype.slice;

/**
 * Reads a varint as an unsigned 32 bit value.
 * @function
 * @returns {number} Value read
 */
Reader.prototype.uint32 = (function read_uint32_setup() {
    var value = 4294967295; // optimizer type-hint, tends to deopt otherwise (?!)
    return function read_uint32() {
        value = (         this.buf[this.pos] & 127       ) >>> 0; if (this.buf[this.pos++] < 128) return value;
        value = (value | (this.buf[this.pos] & 127) <<  7) >>> 0; if (this.buf[this.pos++] < 128) return value;
        value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) return value;
        value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) return value;
        value = (value | (this.buf[this.pos] &  15) << 28) >>> 0; if (this.buf[this.pos++] < 128) return value;

        /* istanbul ignore if */
        if ((this.pos += 5) > this.len) {
            this.pos = this.len;
            throw indexOutOfRange(this, 10);
        }
        return value;
    };
})();

/**
 * Reads a varint as a signed 32 bit value.
 * @returns {number} Value read
 */
Reader.prototype.int32 = function read_int32() {
    return this.uint32() | 0;
};

/**
 * Reads a zig-zag encoded varint as a signed 32 bit value.
 * @returns {number} Value read
 */
Reader.prototype.sint32 = function read_sint32() {
    var value = this.uint32();
    return value >>> 1 ^ -(value & 1) | 0;
};

/* eslint-disable no-invalid-this */

function readLongVarint() {
    // tends to deopt with local vars for octet etc.
    var bits = new LongBits(0, 0);
    var i = 0;
    if (this.len - this.pos > 4) { // fast route (lo)
        for (; i < 4; ++i) {
            // 1st..4th
            bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;
            if (this.buf[this.pos++] < 128)
                return bits;
        }
        // 5th
        bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0;
        bits.hi = (bits.hi | (this.buf[this.pos] & 127) >>  4) >>> 0;
        if (this.buf[this.pos++] < 128)
            return bits;
        i = 0;
    } else {
        for (; i < 3; ++i) {
            /* istanbul ignore if */
            if (this.pos >= this.len)
                throw indexOutOfRange(this);
            // 1st..3th
            bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;
            if (this.buf[this.pos++] < 128)
                return bits;
        }
        // 4th
        bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0;
        return bits;
    }
    if (this.len - this.pos > 4) { // fast route (hi)
        for (; i < 5; ++i) {
            // 6th..10th
            bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;
            if (this.buf[this.pos++] < 128)
                return bits;
        }
    } else {
        for (; i < 5; ++i) {
            /* istanbul ignore if */
            if (this.pos >= this.len)
                throw indexOutOfRange(this);
            // 6th..10th
            bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;
            if (this.buf[this.pos++] < 128)
                return bits;
        }
    }
    /* istanbul ignore next */
    throw Error("invalid varint encoding");
}

/* eslint-enable no-invalid-this */

/**
 * Reads a varint as a signed 64 bit value.
 * @name Reader#int64
 * @function
 * @returns {Long} Value read
 */

/**
 * Reads a varint as an unsigned 64 bit value.
 * @name Reader#uint64
 * @function
 * @returns {Long} Value read
 */

/**
 * Reads a zig-zag encoded varint as a signed 64 bit value.
 * @name Reader#sint64
 * @function
 * @returns {Long} Value read
 */

/**
 * Reads a varint as a boolean.
 * @returns {boolean} Value read
 */
Reader.prototype.bool = function read_bool() {
    return this.uint32() !== 0;
};

function readFixed32_end(buf, end) { // note that this uses `end`, not `pos`
    return (buf[end - 4]
          | buf[end - 3] << 8
          | buf[end - 2] << 16
          | buf[end - 1] << 24) >>> 0;
}

/**
 * Reads fixed 32 bits as an unsigned 32 bit integer.
 * @returns {number} Value read
 */
Reader.prototype.fixed32 = function read_fixed32() {

    /* istanbul ignore if */
    if (this.pos + 4 > this.len)
        throw indexOutOfRange(this, 4);

    return readFixed32_end(this.buf, this.pos += 4);
};

/**
 * Reads fixed 32 bits as a signed 32 bit integer.
 * @returns {number} Value read
 */
Reader.prototype.sfixed32 = function read_sfixed32() {

    /* istanbul ignore if */
    if (this.pos + 4 > this.len)
        throw indexOutOfRange(this, 4);

    return readFixed32_end(this.buf, this.pos += 4) | 0;
};

/* eslint-disable no-invalid-this */

function readFixed64(/* this: Reader */) {

    /* istanbul ignore if */
    if (this.pos + 8 > this.len)
        throw indexOutOfRange(this, 8);

    return new LongBits(readFixed32_end(this.buf, this.pos += 4), readFixed32_end(this.buf, this.pos += 4));
}

/* eslint-enable no-invalid-this */

/**
 * Reads fixed 64 bits.
 * @name Reader#fixed64
 * @function
 * @returns {Long} Value read
 */

/**
 * Reads zig-zag encoded fixed 64 bits.
 * @name Reader#sfixed64
 * @function
 * @returns {Long} Value read
 */

/**
 * Reads a float (32 bit) as a number.
 * @function
 * @returns {number} Value read
 */
Reader.prototype.float = function read_float() {

    /* istanbul ignore if */
    if (this.pos + 4 > this.len)
        throw indexOutOfRange(this, 4);

    var value = util.float.readFloatLE(this.buf, this.pos);
    this.pos += 4;
    return value;
};

/**
 * Reads a double (64 bit float) as a number.
 * @function
 * @returns {number} Value read
 */
Reader.prototype.double = function read_double() {

    /* istanbul ignore if */
    if (this.pos + 8 > this.len)
        throw indexOutOfRange(this, 4);

    var value = util.float.readDoubleLE(this.buf, this.pos);
    this.pos += 8;
    return value;
};

/**
 * Reads a sequence of bytes preceeded by its length as a varint.
 * @returns {Uint8Array} Value read
 */
Reader.prototype.bytes = function read_bytes() {
    var length = this.uint32(),
        start  = this.pos,
        end    = this.pos + length;

    /* istanbul ignore if */
    if (end > this.len)
        throw indexOutOfRange(this, length);

    this.pos += length;
    if (Array.isArray(this.buf)) // plain array
        return this.buf.slice(start, end);
    return start === end // fix for IE 10/Win8 and others' subarray returning array of size 1
        ? new this.buf.constructor(0)
        : this._slice.call(this.buf, start, end);
};

/**
 * Reads a string preceeded by its byte length as a varint.
 * @returns {string} Value read
 */
Reader.prototype.string = function read_string() {
    var bytes = this.bytes();
    return utf8.read(bytes, 0, bytes.length);
};

/**
 * Skips the specified number of bytes if specified, otherwise skips a varint.
 * @param {number} [length] Length if known, otherwise a varint is assumed
 * @returns {Reader} `this`
 */
Reader.prototype.skip = function skip(length) {
    if (typeof length === "number") {
        /* istanbul ignore if */
        if (this.pos + length > this.len)
            throw indexOutOfRange(this, length);
        this.pos += length;
    } else {
        do {
            /* istanbul ignore if */
            if (this.pos >= this.len)
                throw indexOutOfRange(this);
        } while (this.buf[this.pos++] & 128);
    }
    return this;
};

/**
 * Skips the next element of the specified wire type.
 * @param {number} wireType Wire type received
 * @returns {Reader} `this`
 */
Reader.prototype.skipType = function(wireType) {
    switch (wireType) {
        case 0:
            this.skip();
            break;
        case 1:
            this.skip(8);
            break;
        case 2:
            this.skip(this.uint32());
            break;
        case 3:
            while ((wireType = this.uint32() & 7) !== 4) {
                this.skipType(wireType);
            }
            break;
        case 5:
            this.skip(4);
            break;

        /* istanbul ignore next */
        default:
            throw Error("invalid wire type " + wireType + " at offset " + this.pos);
    }
    return this;
};

Reader._configure = function(BufferReader_) {
    BufferReader = BufferReader_;
    Reader.create = create();
    BufferReader._configure();

    var fn = util.Long ? "toLong" : /* istanbul ignore next */ "toNumber";
    util.merge(Reader.prototype, {

        int64: function read_int64() {
            return readLongVarint.call(this)[fn](false);
        },

        uint64: function read_uint64() {
            return readLongVarint.call(this)[fn](true);
        },

        sint64: function read_sint64() {
            return readLongVarint.call(this).zzDecode()[fn](false);
        },

        fixed64: function read_fixed64() {
            return readFixed64.call(this)[fn](true);
        },

        sfixed64: function read_sfixed64() {
            return readFixed64.call(this)[fn](false);
        }

    });
};


/***/ }),

/***/ "./node_modules/protobufjs/src/reader_buffer.js":
/*!******************************************************!*\
  !*** ./node_modules/protobufjs/src/reader_buffer.js ***!
  \******************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

module.exports = BufferReader;

// extends Reader
var Reader = __webpack_require__(/*! ./reader */ "./node_modules/protobufjs/src/reader.js");
(BufferReader.prototype = Object.create(Reader.prototype)).constructor = BufferReader;

var util = __webpack_require__(/*! ./util/minimal */ "./node_modules/protobufjs/src/util/minimal.js");

/**
 * Constructs a new buffer reader instance.
 * @classdesc Wire format reader using node buffers.
 * @extends Reader
 * @constructor
 * @param {Buffer} buffer Buffer to read from
 */
function BufferReader(buffer) {
    Reader.call(this, buffer);

    /**
     * Read buffer.
     * @name BufferReader#buf
     * @type {Buffer}
     */
}

BufferReader._configure = function () {
    /* istanbul ignore else */
    if (util.Buffer)
        BufferReader.prototype._slice = util.Buffer.prototype.slice;
};


/**
 * @override
 */
BufferReader.prototype.string = function read_string_buffer() {
    var len = this.uint32(); // modifies pos
    return this.buf.utf8Slice
        ? this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + len, this.len))
        : this.buf.toString("utf-8", this.pos, this.pos = Math.min(this.pos + len, this.len));
};

/**
 * Reads a sequence of bytes preceeded by its length as a varint.
 * @name BufferReader#bytes
 * @function
 * @returns {Buffer} Value read
 */

BufferReader._configure();


/***/ }),

/***/ "./node_modules/protobufjs/src/roots.js":
/*!**********************************************!*\
  !*** ./node_modules/protobufjs/src/roots.js ***!
  \**********************************************/
/***/ ((module) => {

"use strict";

module.exports = {};

/**
 * Named roots.
 * This is where pbjs stores generated structures (the option `-r, --root` specifies a name).
 * Can also be used manually to make roots available accross modules.
 * @name roots
 * @type {Object.<string,Root>}
 * @example
 * // pbjs -r myroot -o compiled.js ...
 *
 * // in another module:
 * require("./compiled.js");
 *
 * // in any subsequent module:
 * var root = protobuf.roots["myroot"];
 */


/***/ }),

/***/ "./node_modules/protobufjs/src/rpc.js":
/*!********************************************!*\
  !*** ./node_modules/protobufjs/src/rpc.js ***!
  \********************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";


/**
 * Streaming RPC helpers.
 * @namespace
 */
var rpc = exports;

/**
 * RPC implementation passed to {@link Service#create} performing a service request on network level, i.e. by utilizing http requests or websockets.
 * @typedef RPCImpl
 * @type {function}
 * @param {Method|rpc.ServiceMethod<Message<{}>,Message<{}>>} method Reflected or static method being called
 * @param {Uint8Array} requestData Request data
 * @param {RPCImplCallback} callback Callback function
 * @returns {undefined}
 * @example
 * function rpcImpl(method, requestData, callback) {
 *     if (protobuf.util.lcFirst(method.name) !== "myMethod") // compatible with static code
 *         throw Error("no such method");
 *     asynchronouslyObtainAResponse(requestData, function(err, responseData) {
 *         callback(err, responseData);
 *     });
 * }
 */

/**
 * Node-style callback as used by {@link RPCImpl}.
 * @typedef RPCImplCallback
 * @type {function}
 * @param {Error|null} error Error, if any, otherwise `null`
 * @param {Uint8Array|null} [response] Response data or `null` to signal end of stream, if there hasn't been an error
 * @returns {undefined}
 */

rpc.Service = __webpack_require__(/*! ./rpc/service */ "./node_modules/protobufjs/src/rpc/service.js");


/***/ }),

/***/ "./node_modules/protobufjs/src/rpc/service.js":
/*!****************************************************!*\
  !*** ./node_modules/protobufjs/src/rpc/service.js ***!
  \****************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

module.exports = Service;

var util = __webpack_require__(/*! ../util/minimal */ "./node_modules/protobufjs/src/util/minimal.js");

// Extends EventEmitter
(Service.prototype = Object.create(util.EventEmitter.prototype)).constructor = Service;

/**
 * A service method callback as used by {@link rpc.ServiceMethod|ServiceMethod}.
 *
 * Differs from {@link RPCImplCallback} in that it is an actual callback of a service method which may not return `response = null`.
 * @typedef rpc.ServiceMethodCallback
 * @template TRes extends Message<TRes>
 * @type {function}
 * @param {Error|null} error Error, if any
 * @param {TRes} [response] Response message
 * @returns {undefined}
 */

/**
 * A service method part of a {@link rpc.Service} as created by {@link Service.create}.
 * @typedef rpc.ServiceMethod
 * @template TReq extends Message<TReq>
 * @template TRes extends Message<TRes>
 * @type {function}
 * @param {TReq|Properties<TReq>} request Request message or plain object
 * @param {rpc.ServiceMethodCallback<TRes>} [callback] Node-style callback called with the error, if any, and the response message
 * @returns {Promise<Message<TRes>>} Promise if `callback` has been omitted, otherwise `undefined`
 */

/**
 * Constructs a new RPC service instance.
 * @classdesc An RPC service as returned by {@link Service#create}.
 * @exports rpc.Service
 * @extends util.EventEmitter
 * @constructor
 * @param {RPCImpl} rpcImpl RPC implementation
 * @param {boolean} [requestDelimited=false] Whether requests are length-delimited
 * @param {boolean} [responseDelimited=false] Whether responses are length-delimited
 */
function Service(rpcImpl, requestDelimited, responseDelimited) {

    if (typeof rpcImpl !== "function")
        throw TypeError("rpcImpl must be a function");

    util.EventEmitter.call(this);

    /**
     * RPC implementation. Becomes `null` once the service is ended.
     * @type {RPCImpl|null}
     */
    this.rpcImpl = rpcImpl;

    /**
     * Whether requests are length-delimited.
     * @type {boolean}
     */
    this.requestDelimited = Boolean(requestDelimited);

    /**
     * Whether responses are length-delimited.
     * @type {boolean}
     */
    this.responseDelimited = Boolean(responseDelimited);
}

/**
 * Calls a service method through {@link rpc.Service#rpcImpl|rpcImpl}.
 * @param {Method|rpc.ServiceMethod<TReq,TRes>} method Reflected or static method
 * @param {Constructor<TReq>} requestCtor Request constructor
 * @param {Constructor<TRes>} responseCtor Response constructor
 * @param {TReq|Properties<TReq>} request Request message or plain object
 * @param {rpc.ServiceMethodCallback<TRes>} callback Service callback
 * @returns {undefined}
 * @template TReq extends Message<TReq>
 * @template TRes extends Message<TRes>
 */
Service.prototype.rpcCall = function rpcCall(method, requestCtor, responseCtor, request, callback) {

    if (!request)
        throw TypeError("request must be specified");

    var self = this;
    if (!callback)
        return util.asPromise(rpcCall, self, method, requestCtor, responseCtor, request);

    if (!self.rpcImpl) {
        setTimeout(function() { callback(Error("already ended")); }, 0);
        return undefined;
    }

    try {
        return self.rpcImpl(
            method,
            requestCtor[self.requestDelimited ? "encodeDelimited" : "encode"](request).finish(),
            function rpcCallback(err, response) {

                if (err) {
                    self.emit("error", err, method);
                    return callback(err);
                }

                if (response === null) {
                    self.end(/* endedByRPC */ true);
                    return undefined;
                }

                if (!(response instanceof responseCtor)) {
                    try {
                        response = responseCtor[self.responseDelimited ? "decodeDelimited" : "decode"](response);
                    } catch (err) {
                        self.emit("error", err, method);
                        return callback(err);
                    }
                }

                self.emit("data", response, method);
                return callback(null, response);
            }
        );
    } catch (err) {
        self.emit("error", err, method);
        setTimeout(function() { callback(err); }, 0);
        return undefined;
    }
};

/**
 * Ends this service and emits the `end` event.
 * @param {boolean} [endedByRPC=false] Whether the service has been ended by the RPC implementation.
 * @returns {rpc.Service} `this`
 */
Service.prototype.end = function end(endedByRPC) {
    if (this.rpcImpl) {
        if (!endedByRPC) // signal end to rpcImpl
            this.rpcImpl(null, null, null);
        this.rpcImpl = null;
        this.emit("end").off();
    }
    return this;
};


/***/ }),

/***/ "./node_modules/protobufjs/src/util/longbits.js":
/*!******************************************************!*\
  !*** ./node_modules/protobufjs/src/util/longbits.js ***!
  \******************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

module.exports = LongBits;

var util = __webpack_require__(/*! ../util/minimal */ "./node_modules/protobufjs/src/util/minimal.js");

/**
 * Constructs new long bits.
 * @classdesc Helper class for working with the low and high bits of a 64 bit value.
 * @memberof util
 * @constructor
 * @param {number} lo Low 32 bits, unsigned
 * @param {number} hi High 32 bits, unsigned
 */
function LongBits(lo, hi) {

    // note that the casts below are theoretically unnecessary as of today, but older statically
    // generated converter code might still call the ctor with signed 32bits. kept for compat.

    /**
     * Low bits.
     * @type {number}
     */
    this.lo = lo >>> 0;

    /**
     * High bits.
     * @type {number}
     */
    this.hi = hi >>> 0;
}

/**
 * Zero bits.
 * @memberof util.LongBits
 * @type {util.LongBits}
 */
var zero = LongBits.zero = new LongBits(0, 0);

zero.toNumber = function() { return 0; };
zero.zzEncode = zero.zzDecode = function() { return this; };
zero.length = function() { return 1; };

/**
 * Zero hash.
 * @memberof util.LongBits
 * @type {string}
 */
var zeroHash = LongBits.zeroHash = "\0\0\0\0\0\0\0\0";

/**
 * Constructs new long bits from the specified number.
 * @param {number} value Value
 * @returns {util.LongBits} Instance
 */
LongBits.fromNumber = function fromNumber(value) {
    if (value === 0)
        return zero;
    var sign = value < 0;
    if (sign)
        value = -value;
    var lo = value >>> 0,
        hi = (value - lo) / 4294967296 >>> 0;
    if (sign) {
        hi = ~hi >>> 0;
        lo = ~lo >>> 0;
        if (++lo > 4294967295) {
            lo = 0;
            if (++hi > 4294967295)
                hi = 0;
        }
    }
    return new LongBits(lo, hi);
};

/**
 * Constructs new long bits from a number, long or string.
 * @param {Long|number|string} value Value
 * @returns {util.LongBits} Instance
 */
LongBits.from = function from(value) {
    if (typeof value === "number")
        return LongBits.fromNumber(value);
    if (util.isString(value)) {
        /* istanbul ignore else */
        if (util.Long)
            value = util.Long.fromString(value);
        else
            return LongBits.fromNumber(parseInt(value, 10));
    }
    return value.low || value.high ? new LongBits(value.low >>> 0, value.high >>> 0) : zero;
};

/**
 * Converts this long bits to a possibly unsafe JavaScript number.
 * @param {boolean} [unsigned=false] Whether unsigned or not
 * @returns {number} Possibly unsafe number
 */
LongBits.prototype.toNumber = function toNumber(unsigned) {
    if (!unsigned && this.hi >>> 31) {
        var lo = ~this.lo + 1 >>> 0,
            hi = ~this.hi     >>> 0;
        if (!lo)
            hi = hi + 1 >>> 0;
        return -(lo + hi * 4294967296);
    }
    return this.lo + this.hi * 4294967296;
};

/**
 * Converts this long bits to a long.
 * @param {boolean} [unsigned=false] Whether unsigned or not
 * @returns {Long} Long
 */
LongBits.prototype.toLong = function toLong(unsigned) {
    return util.Long
        ? new util.Long(this.lo | 0, this.hi | 0, Boolean(unsigned))
        /* istanbul ignore next */
        : { low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned) };
};

var charCodeAt = String.prototype.charCodeAt;

/**
 * Constructs new long bits from the specified 8 characters long hash.
 * @param {string} hash Hash
 * @returns {util.LongBits} Bits
 */
LongBits.fromHash = function fromHash(hash) {
    if (hash === zeroHash)
        return zero;
    return new LongBits(
        ( charCodeAt.call(hash, 0)
        | charCodeAt.call(hash, 1) << 8
        | charCodeAt.call(hash, 2) << 16
        | charCodeAt.call(hash, 3) << 24) >>> 0
    ,
        ( charCodeAt.call(hash, 4)
        | charCodeAt.call(hash, 5) << 8
        | charCodeAt.call(hash, 6) << 16
        | charCodeAt.call(hash, 7) << 24) >>> 0
    );
};

/**
 * Converts this long bits to a 8 characters long hash.
 * @returns {string} Hash
 */
LongBits.prototype.toHash = function toHash() {
    return String.fromCharCode(
        this.lo        & 255,
        this.lo >>> 8  & 255,
        this.lo >>> 16 & 255,
        this.lo >>> 24      ,
        this.hi        & 255,
        this.hi >>> 8  & 255,
        this.hi >>> 16 & 255,
        this.hi >>> 24
    );
};

/**
 * Zig-zag encodes this long bits.
 * @returns {util.LongBits} `this`
 */
LongBits.prototype.zzEncode = function zzEncode() {
    var mask =   this.hi >> 31;
    this.hi  = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0;
    this.lo  = ( this.lo << 1                   ^ mask) >>> 0;
    return this;
};

/**
 * Zig-zag decodes this long bits.
 * @returns {util.LongBits} `this`
 */
LongBits.prototype.zzDecode = function zzDecode() {
    var mask = -(this.lo & 1);
    this.lo  = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0;
    this.hi  = ( this.hi >>> 1                  ^ mask) >>> 0;
    return this;
};

/**
 * Calculates the length of this longbits when encoded as a varint.
 * @returns {number} Length
 */
LongBits.prototype.length = function length() {
    var part0 =  this.lo,
        part1 = (this.lo >>> 28 | this.hi << 4) >>> 0,
        part2 =  this.hi >>> 24;
    return part2 === 0
         ? part1 === 0
           ? part0 < 16384
             ? part0 < 128 ? 1 : 2
             : part0 < 2097152 ? 3 : 4
           : part1 < 16384
             ? part1 < 128 ? 5 : 6
             : part1 < 2097152 ? 7 : 8
         : part2 < 128 ? 9 : 10;
};


/***/ }),

/***/ "./node_modules/protobufjs/src/util/minimal.js":
/*!*****************************************************!*\
  !*** ./node_modules/protobufjs/src/util/minimal.js ***!
  \*****************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var util = exports;

// used to return a Promise where callback is omitted
util.asPromise = __webpack_require__(/*! @protobufjs/aspromise */ "./node_modules/@protobufjs/aspromise/index.js");

// converts to / from base64 encoded strings
util.base64 = __webpack_require__(/*! @protobufjs/base64 */ "./node_modules/@protobufjs/base64/index.js");

// base class of rpc.Service
util.EventEmitter = __webpack_require__(/*! @protobufjs/eventemitter */ "./node_modules/@protobufjs/eventemitter/index.js");

// float handling accross browsers
util.float = __webpack_require__(/*! @protobufjs/float */ "./node_modules/@protobufjs/float/index.js");

// requires modules optionally and hides the call from bundlers
util.inquire = __webpack_require__(/*! @protobufjs/inquire */ "./node_modules/@protobufjs/inquire/index.js");

// converts to / from utf8 encoded strings
util.utf8 = __webpack_require__(/*! @protobufjs/utf8 */ "./node_modules/@protobufjs/utf8/index.js");

// provides a node-like buffer pool in the browser
util.pool = __webpack_require__(/*! @protobufjs/pool */ "./node_modules/@protobufjs/pool/index.js");

// utility to work with the low and high bits of a 64 bit value
util.LongBits = __webpack_require__(/*! ./longbits */ "./node_modules/protobufjs/src/util/longbits.js");

/**
 * Whether running within node or not.
 * @memberof util
 * @type {boolean}
 */
util.isNode = Boolean(typeof __webpack_require__.g !== "undefined"
                   && __webpack_require__.g
                   && __webpack_require__.g.process
                   && __webpack_require__.g.process.versions
                   && __webpack_require__.g.process.versions.node);

/**
 * Global object reference.
 * @memberof util
 * @type {Object}
 */
util.global = util.isNode && __webpack_require__.g
           || typeof window !== "undefined" && window
           || typeof self   !== "undefined" && self
           || this; // eslint-disable-line no-invalid-this

/**
 * An immuable empty array.
 * @memberof util
 * @type {Array.<*>}
 * @const
 */
util.emptyArray = Object.freeze ? Object.freeze([]) : /* istanbul ignore next */ []; // used on prototypes

/**
 * An immutable empty object.
 * @type {Object}
 * @const
 */
util.emptyObject = Object.freeze ? Object.freeze({}) : /* istanbul ignore next */ {}; // used on prototypes

/**
 * Tests if the specified value is an integer.
 * @function
 * @param {*} value Value to test
 * @returns {boolean} `true` if the value is an integer
 */
util.isInteger = Number.isInteger || /* istanbul ignore next */ function isInteger(value) {
    return typeof value === "number" && isFinite(value) && Math.floor(value) === value;
};

/**
 * Tests if the specified value is a string.
 * @param {*} value Value to test
 * @returns {boolean} `true` if the value is a string
 */
util.isString = function isString(value) {
    return typeof value === "string" || value instanceof String;
};

/**
 * Tests if the specified value is a non-null object.
 * @param {*} value Value to test
 * @returns {boolean} `true` if the value is a non-null object
 */
util.isObject = function isObject(value) {
    return value && typeof value === "object";
};

/**
 * Checks if a property on a message is considered to be present.
 * This is an alias of {@link util.isSet}.
 * @function
 * @param {Object} obj Plain object or message instance
 * @param {string} prop Property name
 * @returns {boolean} `true` if considered to be present, otherwise `false`
 */
util.isset =

/**
 * Checks if a property on a message is considered to be present.
 * @param {Object} obj Plain object or message instance
 * @param {string} prop Property name
 * @returns {boolean} `true` if considered to be present, otherwise `false`
 */
util.isSet = function isSet(obj, prop) {
    var value = obj[prop];
    if (value != null && obj.hasOwnProperty(prop)) // eslint-disable-line eqeqeq, no-prototype-builtins
        return typeof value !== "object" || (Array.isArray(value) ? value.length : Object.keys(value).length) > 0;
    return false;
};

/**
 * Any compatible Buffer instance.
 * This is a minimal stand-alone definition of a Buffer instance. The actual type is that exported by node's typings.
 * @interface Buffer
 * @extends Uint8Array
 */

/**
 * Node's Buffer class if available.
 * @type {Constructor<Buffer>}
 */
util.Buffer = (function() {
    try {
        var Buffer = util.inquire("buffer").Buffer;
        // refuse to use non-node buffers if not explicitly assigned (perf reasons):
        return Buffer.prototype.utf8Write ? Buffer : /* istanbul ignore next */ null;
    } catch (e) {
        /* istanbul ignore next */
        return null;
    }
})();

// Internal alias of or polyfull for Buffer.from.
util._Buffer_from = null;

// Internal alias of or polyfill for Buffer.allocUnsafe.
util._Buffer_allocUnsafe = null;

/**
 * Creates a new buffer of whatever type supported by the environment.
 * @param {number|number[]} [sizeOrArray=0] Buffer size or number array
 * @returns {Uint8Array|Buffer} Buffer
 */
util.newBuffer = function newBuffer(sizeOrArray) {
    /* istanbul ignore next */
    return typeof sizeOrArray === "number"
        ? util.Buffer
            ? util._Buffer_allocUnsafe(sizeOrArray)
            : new util.Array(sizeOrArray)
        : util.Buffer
            ? util._Buffer_from(sizeOrArray)
            : typeof Uint8Array === "undefined"
                ? sizeOrArray
                : new Uint8Array(sizeOrArray);
};

/**
 * Array implementation used in the browser. `Uint8Array` if supported, otherwise `Array`.
 * @type {Constructor<Uint8Array>}
 */
util.Array = typeof Uint8Array !== "undefined" ? Uint8Array /* istanbul ignore next */ : Array;

/**
 * Any compatible Long instance.
 * This is a minimal stand-alone definition of a Long instance. The actual type is that exported by long.js.
 * @interface Long
 * @property {number} low Low bits
 * @property {number} high High bits
 * @property {boolean} unsigned Whether unsigned or not
 */

/**
 * Long.js's Long class if available.
 * @type {Constructor<Long>}
 */
util.Long = /* istanbul ignore next */ util.global.dcodeIO && /* istanbul ignore next */ util.global.dcodeIO.Long
         || /* istanbul ignore next */ util.global.Long
         || util.inquire("long");

/**
 * Regular expression used to verify 2 bit (`bool`) map keys.
 * @type {RegExp}
 * @const
 */
util.key2Re = /^true|false|0|1$/;

/**
 * Regular expression used to verify 32 bit (`int32` etc.) map keys.
 * @type {RegExp}
 * @const
 */
util.key32Re = /^-?(?:0|[1-9][0-9]*)$/;

/**
 * Regular expression used to verify 64 bit (`int64` etc.) map keys.
 * @type {RegExp}
 * @const
 */
util.key64Re = /^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;

/**
 * Converts a number or long to an 8 characters long hash string.
 * @param {Long|number} value Value to convert
 * @returns {string} Hash
 */
util.longToHash = function longToHash(value) {
    return value
        ? util.LongBits.from(value).toHash()
        : util.LongBits.zeroHash;
};

/**
 * Converts an 8 characters long hash string to a long or number.
 * @param {string} hash Hash
 * @param {boolean} [unsigned=false] Whether unsigned or not
 * @returns {Long|number} Original value
 */
util.longFromHash = function longFromHash(hash, unsigned) {
    var bits = util.LongBits.fromHash(hash);
    if (util.Long)
        return util.Long.fromBits(bits.lo, bits.hi, unsigned);
    return bits.toNumber(Boolean(unsigned));
};

/**
 * Merges the properties of the source object into the destination object.
 * @memberof util
 * @param {Object.<string,*>} dst Destination object
 * @param {Object.<string,*>} src Source object
 * @param {boolean} [ifNotSet=false] Merges only if the key is not already set
 * @returns {Object.<string,*>} Destination object
 */
function merge(dst, src, ifNotSet) { // used by converters
    for (var keys = Object.keys(src), i = 0; i < keys.length; ++i)
        if (dst[keys[i]] === undefined || !ifNotSet)
            dst[keys[i]] = src[keys[i]];
    return dst;
}

util.merge = merge;

/**
 * Converts the first character of a string to lower case.
 * @param {string} str String to convert
 * @returns {string} Converted string
 */
util.lcFirst = function lcFirst(str) {
    return str.charAt(0).toLowerCase() + str.substring(1);
};

/**
 * Creates a custom error constructor.
 * @memberof util
 * @param {string} name Error name
 * @returns {Constructor<Error>} Custom error constructor
 */
function newError(name) {

    function CustomError(message, properties) {

        if (!(this instanceof CustomError))
            return new CustomError(message, properties);

        // Error.call(this, message);
        // ^ just returns a new error instance because the ctor can be called as a function

        Object.defineProperty(this, "message", { get: function() { return message; } });

        /* istanbul ignore next */
        if (Error.captureStackTrace) // node
            Error.captureStackTrace(this, CustomError);
        else
            Object.defineProperty(this, "stack", { value: new Error().stack || "" });

        if (properties)
            merge(this, properties);
    }

    (CustomError.prototype = Object.create(Error.prototype)).constructor = CustomError;

    Object.defineProperty(CustomError.prototype, "name", { get: function() { return name; } });

    CustomError.prototype.toString = function toString() {
        return this.name + ": " + this.message;
    };

    return CustomError;
}

util.newError = newError;

/**
 * Constructs a new protocol error.
 * @classdesc Error subclass indicating a protocol specifc error.
 * @memberof util
 * @extends Error
 * @template T extends Message<T>
 * @constructor
 * @param {string} message Error message
 * @param {Object.<string,*>} [properties] Additional properties
 * @example
 * try {
 *     MyMessage.decode(someBuffer); // throws if required fields are missing
 * } catch (e) {
 *     if (e instanceof ProtocolError && e.instance)
 *         console.log("decoded so far: " + JSON.stringify(e.instance));
 * }
 */
util.ProtocolError = newError("ProtocolError");

/**
 * So far decoded message instance.
 * @name util.ProtocolError#instance
 * @type {Message<T>}
 */

/**
 * A OneOf getter as returned by {@link util.oneOfGetter}.
 * @typedef OneOfGetter
 * @type {function}
 * @returns {string|undefined} Set field name, if any
 */

/**
 * Builds a getter for a oneof's present field name.
 * @param {string[]} fieldNames Field names
 * @returns {OneOfGetter} Unbound getter
 */
util.oneOfGetter = function getOneOf(fieldNames) {
    var fieldMap = {};
    for (var i = 0; i < fieldNames.length; ++i)
        fieldMap[fieldNames[i]] = 1;

    /**
     * @returns {string|undefined} Set field name, if any
     * @this Object
     * @ignore
     */
    return function() { // eslint-disable-line consistent-return
        for (var keys = Object.keys(this), i = keys.length - 1; i > -1; --i)
            if (fieldMap[keys[i]] === 1 && this[keys[i]] !== undefined && this[keys[i]] !== null)
                return keys[i];
    };
};

/**
 * A OneOf setter as returned by {@link util.oneOfSetter}.
 * @typedef OneOfSetter
 * @type {function}
 * @param {string|undefined} value Field name
 * @returns {undefined}
 */

/**
 * Builds a setter for a oneof's present field name.
 * @param {string[]} fieldNames Field names
 * @returns {OneOfSetter} Unbound setter
 */
util.oneOfSetter = function setOneOf(fieldNames) {

    /**
     * @param {string} name Field name
     * @returns {undefined}
     * @this Object
     * @ignore
     */
    return function(name) {
        for (var i = 0; i < fieldNames.length; ++i)
            if (fieldNames[i] !== name)
                delete this[fieldNames[i]];
    };
};

/**
 * Default conversion options used for {@link Message#toJSON} implementations.
 *
 * These options are close to proto3's JSON mapping with the exception that internal types like Any are handled just like messages. More precisely:
 *
 * - Longs become strings
 * - Enums become string keys
 * - Bytes become base64 encoded strings
 * - (Sub-)Messages become plain objects
 * - Maps become plain objects with all string keys
 * - Repeated fields become arrays
 * - NaN and Infinity for float and double fields become strings
 *
 * @type {IConversionOptions}
 * @see https://developers.google.com/protocol-buffers/docs/proto3?hl=en#json
 */
util.toJSONOptions = {
    longs: String,
    enums: String,
    bytes: String,
    json: true
};

// Sets up buffer utility according to the environment (called in index-minimal)
util._configure = function() {
    var Buffer = util.Buffer;
    /* istanbul ignore if */
    if (!Buffer) {
        util._Buffer_from = util._Buffer_allocUnsafe = null;
        return;
    }
    // because node 4.x buffers are incompatible & immutable
    // see: https://github.com/dcodeIO/protobuf.js/pull/665
    util._Buffer_from = Buffer.from !== Uint8Array.from && Buffer.from ||
        /* istanbul ignore next */
        function Buffer_from(value, encoding) {
            return new Buffer(value, encoding);
        };
    util._Buffer_allocUnsafe = Buffer.allocUnsafe ||
        /* istanbul ignore next */
        function Buffer_allocUnsafe(size) {
            return new Buffer(size);
        };
};


/***/ }),

/***/ "./node_modules/protobufjs/src/writer.js":
/*!***********************************************!*\
  !*** ./node_modules/protobufjs/src/writer.js ***!
  \***********************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

module.exports = Writer;

var util      = __webpack_require__(/*! ./util/minimal */ "./node_modules/protobufjs/src/util/minimal.js");

var BufferWriter; // cyclic

var LongBits  = util.LongBits,
    base64    = util.base64,
    utf8      = util.utf8;

/**
 * Constructs a new writer operation instance.
 * @classdesc Scheduled writer operation.
 * @constructor
 * @param {function(*, Uint8Array, number)} fn Function to call
 * @param {number} len Value byte length
 * @param {*} val Value to write
 * @ignore
 */
function Op(fn, len, val) {

    /**
     * Function to call.
     * @type {function(Uint8Array, number, *)}
     */
    this.fn = fn;

    /**
     * Value byte length.
     * @type {number}
     */
    this.len = len;

    /**
     * Next operation.
     * @type {Writer.Op|undefined}
     */
    this.next = undefined;

    /**
     * Value to write.
     * @type {*}
     */
    this.val = val; // type varies
}

/* istanbul ignore next */
function noop() {} // eslint-disable-line no-empty-function

/**
 * Constructs a new writer state instance.
 * @classdesc Copied writer state.
 * @memberof Writer
 * @constructor
 * @param {Writer} writer Writer to copy state from
 * @ignore
 */
function State(writer) {

    /**
     * Current head.
     * @type {Writer.Op}
     */
    this.head = writer.head;

    /**
     * Current tail.
     * @type {Writer.Op}
     */
    this.tail = writer.tail;

    /**
     * Current buffer length.
     * @type {number}
     */
    this.len = writer.len;

    /**
     * Next state.
     * @type {State|null}
     */
    this.next = writer.states;
}

/**
 * Constructs a new writer instance.
 * @classdesc Wire format writer using `Uint8Array` if available, otherwise `Array`.
 * @constructor
 */
function Writer() {

    /**
     * Current length.
     * @type {number}
     */
    this.len = 0;

    /**
     * Operations head.
     * @type {Object}
     */
    this.head = new Op(noop, 0, 0);

    /**
     * Operations tail
     * @type {Object}
     */
    this.tail = this.head;

    /**
     * Linked forked states.
     * @type {Object|null}
     */
    this.states = null;

    // When a value is written, the writer calculates its byte length and puts it into a linked
    // list of operations to perform when finish() is called. This both allows us to allocate
    // buffers of the exact required size and reduces the amount of work we have to do compared
    // to first calculating over objects and then encoding over objects. In our case, the encoding
    // part is just a linked list walk calling operations with already prepared values.
}

var create = function create() {
    return util.Buffer
        ? function create_buffer_setup() {
            return (Writer.create = function create_buffer() {
                return new BufferWriter();
            })();
        }
        /* istanbul ignore next */
        : function create_array() {
            return new Writer();
        };
};

/**
 * Creates a new writer.
 * @function
 * @returns {BufferWriter|Writer} A {@link BufferWriter} when Buffers are supported, otherwise a {@link Writer}
 */
Writer.create = create();

/**
 * Allocates a buffer of the specified size.
 * @param {number} size Buffer size
 * @returns {Uint8Array} Buffer
 */
Writer.alloc = function alloc(size) {
    return new util.Array(size);
};

// Use Uint8Array buffer pool in the browser, just like node does with buffers
/* istanbul ignore else */
if (util.Array !== Array)
    Writer.alloc = util.pool(Writer.alloc, util.Array.prototype.subarray);

/**
 * Pushes a new operation to the queue.
 * @param {function(Uint8Array, number, *)} fn Function to call
 * @param {number} len Value byte length
 * @param {number} val Value to write
 * @returns {Writer} `this`
 * @private
 */
Writer.prototype._push = function push(fn, len, val) {
    this.tail = this.tail.next = new Op(fn, len, val);
    this.len += len;
    return this;
};

function writeByte(val, buf, pos) {
    buf[pos] = val & 255;
}

function writeVarint32(val, buf, pos) {
    while (val > 127) {
        buf[pos++] = val & 127 | 128;
        val >>>= 7;
    }
    buf[pos] = val;
}

/**
 * Constructs a new varint writer operation instance.
 * @classdesc Scheduled varint writer operation.
 * @extends Op
 * @constructor
 * @param {number} len Value byte length
 * @param {number} val Value to write
 * @ignore
 */
function VarintOp(len, val) {
    this.len = len;
    this.next = undefined;
    this.val = val;
}

VarintOp.prototype = Object.create(Op.prototype);
VarintOp.prototype.fn = writeVarint32;

/**
 * Writes an unsigned 32 bit value as a varint.
 * @param {number} value Value to write
 * @returns {Writer} `this`
 */
Writer.prototype.uint32 = function write_uint32(value) {
    // here, the call to this.push has been inlined and a varint specific Op subclass is used.
    // uint32 is by far the most frequently used operation and benefits significantly from this.
    this.len += (this.tail = this.tail.next = new VarintOp(
        (value = value >>> 0)
                < 128       ? 1
        : value < 16384     ? 2
        : value < 2097152   ? 3
        : value < 268435456 ? 4
        :                     5,
    value)).len;
    return this;
};

/**
 * Writes a signed 32 bit value as a varint.
 * @function
 * @param {number} value Value to write
 * @returns {Writer} `this`
 */
Writer.prototype.int32 = function write_int32(value) {
    return value < 0
        ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec
        : this.uint32(value);
};

/**
 * Writes a 32 bit value as a varint, zig-zag encoded.
 * @param {number} value Value to write
 * @returns {Writer} `this`
 */
Writer.prototype.sint32 = function write_sint32(value) {
    return this.uint32((value << 1 ^ value >> 31) >>> 0);
};

function writeVarint64(val, buf, pos) {
    while (val.hi) {
        buf[pos++] = val.lo & 127 | 128;
        val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0;
        val.hi >>>= 7;
    }
    while (val.lo > 127) {
        buf[pos++] = val.lo & 127 | 128;
        val.lo = val.lo >>> 7;
    }
    buf[pos++] = val.lo;
}

/**
 * Writes an unsigned 64 bit value as a varint.
 * @param {Long|number|string} value Value to write
 * @returns {Writer} `this`
 * @throws {TypeError} If `value` is a string and no long library is present.
 */
Writer.prototype.uint64 = function write_uint64(value) {
    var bits = LongBits.from(value);
    return this._push(writeVarint64, bits.length(), bits);
};

/**
 * Writes a signed 64 bit value as a varint.
 * @function
 * @param {Long|number|string} value Value to write
 * @returns {Writer} `this`
 * @throws {TypeError} If `value` is a string and no long library is present.
 */
Writer.prototype.int64 = Writer.prototype.uint64;

/**
 * Writes a signed 64 bit value as a varint, zig-zag encoded.
 * @param {Long|number|string} value Value to write
 * @returns {Writer} `this`
 * @throws {TypeError} If `value` is a string and no long library is present.
 */
Writer.prototype.sint64 = function write_sint64(value) {
    var bits = LongBits.from(value).zzEncode();
    return this._push(writeVarint64, bits.length(), bits);
};

/**
 * Writes a boolish value as a varint.
 * @param {boolean} value Value to write
 * @returns {Writer} `this`
 */
Writer.prototype.bool = function write_bool(value) {
    return this._push(writeByte, 1, value ? 1 : 0);
};

function writeFixed32(val, buf, pos) {
    buf[pos    ] =  val         & 255;
    buf[pos + 1] =  val >>> 8   & 255;
    buf[pos + 2] =  val >>> 16  & 255;
    buf[pos + 3] =  val >>> 24;
}

/**
 * Writes an unsigned 32 bit value as fixed 32 bits.
 * @param {number} value Value to write
 * @returns {Writer} `this`
 */
Writer.prototype.fixed32 = function write_fixed32(value) {
    return this._push(writeFixed32, 4, value >>> 0);
};

/**
 * Writes a signed 32 bit value as fixed 32 bits.
 * @function
 * @param {number} value Value to write
 * @returns {Writer} `this`
 */
Writer.prototype.sfixed32 = Writer.prototype.fixed32;

/**
 * Writes an unsigned 64 bit value as fixed 64 bits.
 * @param {Long|number|string} value Value to write
 * @returns {Writer} `this`
 * @throws {TypeError} If `value` is a string and no long library is present.
 */
Writer.prototype.fixed64 = function write_fixed64(value) {
    var bits = LongBits.from(value);
    return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi);
};

/**
 * Writes a signed 64 bit value as fixed 64 bits.
 * @function
 * @param {Long|number|string} value Value to write
 * @returns {Writer} `this`
 * @throws {TypeError} If `value` is a string and no long library is present.
 */
Writer.prototype.sfixed64 = Writer.prototype.fixed64;

/**
 * Writes a float (32 bit).
 * @function
 * @param {number} value Value to write
 * @returns {Writer} `this`
 */
Writer.prototype.float = function write_float(value) {
    return this._push(util.float.writeFloatLE, 4, value);
};

/**
 * Writes a double (64 bit float).
 * @function
 * @param {number} value Value to write
 * @returns {Writer} `this`
 */
Writer.prototype.double = function write_double(value) {
    return this._push(util.float.writeDoubleLE, 8, value);
};

var writeBytes = util.Array.prototype.set
    ? function writeBytes_set(val, buf, pos) {
        buf.set(val, pos); // also works for plain array values
    }
    /* istanbul ignore next */
    : function writeBytes_for(val, buf, pos) {
        for (var i = 0; i < val.length; ++i)
            buf[pos + i] = val[i];
    };

/**
 * Writes a sequence of bytes.
 * @param {Uint8Array|string} value Buffer or base64 encoded string to write
 * @returns {Writer} `this`
 */
Writer.prototype.bytes = function write_bytes(value) {
    var len = value.length >>> 0;
    if (!len)
        return this._push(writeByte, 1, 0);
    if (util.isString(value)) {
        var buf = Writer.alloc(len = base64.length(value));
        base64.decode(value, buf, 0);
        value = buf;
    }
    return this.uint32(len)._push(writeBytes, len, value);
};

/**
 * Writes a string.
 * @param {string} value Value to write
 * @returns {Writer} `this`
 */
Writer.prototype.string = function write_string(value) {
    var len = utf8.length(value);
    return len
        ? this.uint32(len)._push(utf8.write, len, value)
        : this._push(writeByte, 1, 0);
};

/**
 * Forks this writer's state by pushing it to a stack.
 * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.
 * @returns {Writer} `this`
 */
Writer.prototype.fork = function fork() {
    this.states = new State(this);
    this.head = this.tail = new Op(noop, 0, 0);
    this.len = 0;
    return this;
};

/**
 * Resets this instance to the last state.
 * @returns {Writer} `this`
 */
Writer.prototype.reset = function reset() {
    if (this.states) {
        this.head   = this.states.head;
        this.tail   = this.states.tail;
        this.len    = this.states.len;
        this.states = this.states.next;
    } else {
        this.head = this.tail = new Op(noop, 0, 0);
        this.len  = 0;
    }
    return this;
};

/**
 * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.
 * @returns {Writer} `this`
 */
Writer.prototype.ldelim = function ldelim() {
    var head = this.head,
        tail = this.tail,
        len  = this.len;
    this.reset().uint32(len);
    if (len) {
        this.tail.next = head.next; // skip noop
        this.tail = tail;
        this.len += len;
    }
    return this;
};

/**
 * Finishes the write operation.
 * @returns {Uint8Array} Finished buffer
 */
Writer.prototype.finish = function finish() {
    var head = this.head.next, // skip noop
        buf  = this.constructor.alloc(this.len),
        pos  = 0;
    while (head) {
        head.fn(head.val, buf, pos);
        pos += head.len;
        head = head.next;
    }
    // this.head = this.tail = null;
    return buf;
};

Writer._configure = function(BufferWriter_) {
    BufferWriter = BufferWriter_;
    Writer.create = create();
    BufferWriter._configure();
};


/***/ }),

/***/ "./node_modules/protobufjs/src/writer_buffer.js":
/*!******************************************************!*\
  !*** ./node_modules/protobufjs/src/writer_buffer.js ***!
  \******************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

module.exports = BufferWriter;

// extends Writer
var Writer = __webpack_require__(/*! ./writer */ "./node_modules/protobufjs/src/writer.js");
(BufferWriter.prototype = Object.create(Writer.prototype)).constructor = BufferWriter;

var util = __webpack_require__(/*! ./util/minimal */ "./node_modules/protobufjs/src/util/minimal.js");

/**
 * Constructs a new buffer writer instance.
 * @classdesc Wire format writer using node buffers.
 * @extends Writer
 * @constructor
 */
function BufferWriter() {
    Writer.call(this);
}

BufferWriter._configure = function () {
    /**
     * Allocates a buffer of the specified size.
     * @function
     * @param {number} size Buffer size
     * @returns {Buffer} Buffer
     */
    BufferWriter.alloc = util._Buffer_allocUnsafe;

    BufferWriter.writeBytesBuffer = util.Buffer && util.Buffer.prototype instanceof Uint8Array && util.Buffer.prototype.set.name === "set"
        ? function writeBytesBuffer_set(val, buf, pos) {
          buf.set(val, pos); // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited)
          // also works for plain array values
        }
        /* istanbul ignore next */
        : function writeBytesBuffer_copy(val, buf, pos) {
          if (val.copy) // Buffer values
            val.copy(buf, pos, 0, val.length);
          else for (var i = 0; i < val.length;) // plain array values
            buf[pos++] = val[i++];
        };
};


/**
 * @override
 */
BufferWriter.prototype.bytes = function write_bytes_buffer(value) {
    if (util.isString(value))
        value = util._Buffer_from(value, "base64");
    var len = value.length >>> 0;
    this.uint32(len);
    if (len)
        this._push(BufferWriter.writeBytesBuffer, len, value);
    return this;
};

function writeStringBuffer(val, buf, pos) {
    if (val.length < 40) // plain js is faster for short strings (probably due to redundant assertions)
        util.utf8.write(val, buf, pos);
    else if (buf.utf8Write)
        buf.utf8Write(val, pos);
    else
        buf.write(val, pos);
}

/**
 * @override
 */
BufferWriter.prototype.string = function write_string_buffer(value) {
    var len = util.Buffer.byteLength(value);
    this.uint32(len);
    if (len)
        this._push(writeStringBuffer, len, value);
    return this;
};


/**
 * Finishes the write operation.
 * @name BufferWriter#finish
 * @function
 * @returns {Buffer} Finished buffer
 */

BufferWriter._configure();


/***/ }),

/***/ "./lib/backend-onnxjs.ts":
/*!*******************************!*\
  !*** ./lib/backend-onnxjs.ts ***!
  \*******************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.onnxjsBackend = void 0;
const session_1 = __webpack_require__(/*! ./onnxjs/session */ "./lib/onnxjs/session.ts");
const session_handler_1 = __webpack_require__(/*! ./onnxjs/session-handler */ "./lib/onnxjs/session-handler.ts");
class OnnxjsBackend {
    // eslint-disable-next-line @typescript-eslint/no-empty-function
    async init() { }
    async createSessionHandler(pathOrBuffer, options) {
        // NOTE: Session.Config(from onnx.js) is not compatible with InferenceSession.SessionOptions(from
        // onnxruntime-common).
        //       In future we should remove Session.Config and use InferenceSession.SessionOptions.
        //       Currently we allow this to happen to make test runner work.
        const session = new session_1.Session(options);
        // typescript cannot merge method override correctly (so far in 4.2.3). need if-else to call the method.
        if (typeof pathOrBuffer === 'string') {
            await session.loadModel(pathOrBuffer);
        }
        else {
            await session.loadModel(pathOrBuffer);
        }
        return new session_handler_1.OnnxjsSessionHandler(session);
    }
}
exports.onnxjsBackend = new OnnxjsBackend();


/***/ }),

/***/ "./lib/backend-wasm.ts":
/*!*****************************!*\
  !*** ./lib/backend-wasm.ts ***!
  \*****************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.wasmBackend = exports.initializeFlags = void 0;
const onnxruntime_common_1 = __webpack_require__(/*! onnxruntime-common */ "../common/dist/lib/index.js");
const os_1 = __webpack_require__(/*! os */ "?0757");
const proxy_wrapper_1 = __webpack_require__(/*! ./wasm/proxy-wrapper */ "./lib/wasm/proxy-wrapper.ts");
const session_handler_1 = __webpack_require__(/*! ./wasm/session-handler */ "./lib/wasm/session-handler.ts");
/**
 * This function initializes all flags for WebAssembly.
 *
 * Those flags are accessible from `ort.env.wasm`. Users are allow to set those flags before the first inference session
 * being created, to override default value.
 */
const initializeFlags = () => {
    if (typeof onnxruntime_common_1.env.wasm.initTimeout !== 'number' || onnxruntime_common_1.env.wasm.initTimeout < 0) {
        onnxruntime_common_1.env.wasm.initTimeout = 0;
    }
    if (typeof onnxruntime_common_1.env.wasm.simd !== 'boolean') {
        onnxruntime_common_1.env.wasm.simd = true;
    }
    if (typeof onnxruntime_common_1.env.wasm.proxy !== 'boolean') {
        onnxruntime_common_1.env.wasm.proxy = false;
    }
    if (typeof onnxruntime_common_1.env.wasm.numThreads !== 'number' || !Number.isInteger(onnxruntime_common_1.env.wasm.numThreads) || onnxruntime_common_1.env.wasm.numThreads <= 0) {
        const numCpuLogicalCores = typeof navigator === 'undefined' ? (0, os_1.cpus)().length : navigator.hardwareConcurrency;
        onnxruntime_common_1.env.wasm.numThreads = Math.min(4, Math.ceil((numCpuLogicalCores || 1) / 2));
    }
};
exports.initializeFlags = initializeFlags;
class OnnxruntimeWebAssemblyBackend {
    async init() {
        // populate wasm flags
        (0, exports.initializeFlags)();
        // init wasm
        await (0, proxy_wrapper_1.initWasm)();
    }
    async createSessionHandler(pathOrBuffer, options) {
        const handler = new session_handler_1.OnnxruntimeWebAssemblySessionHandler();
        await handler.loadModel(pathOrBuffer, options);
        return Promise.resolve(handler);
    }
}
exports.wasmBackend = new OnnxruntimeWebAssemblyBackend();


/***/ }),

/***/ "./lib/index.ts":
/*!**********************!*\
  !*** ./lib/index.ts ***!
  \**********************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
/* eslint-disable @typescript-eslint/no-var-requires, @typescript-eslint/no-require-imports */
// We use "require" instead of "import" here because import statement must be put in top level. Our current code does
// not allow terser to tree-shaking code as expected because some codes are treated as having side effects.
// So we import code inside the if-clause to allow terser remove the code safely.
__exportStar(__webpack_require__(/*! onnxruntime-common */ "../common/dist/lib/index.js"), exports);
const onnxruntime_common_1 = __webpack_require__(/*! onnxruntime-common */ "../common/dist/lib/index.js");
if (true) {
    const onnxjsBackend = (__webpack_require__(/*! ./backend-onnxjs */ "./lib/backend-onnxjs.ts").onnxjsBackend);
    (0, onnxruntime_common_1.registerBackend)('webgl', onnxjsBackend, -10);
}
if (true) {
    const wasmBackend = (__webpack_require__(/*! ./backend-wasm */ "./lib/backend-wasm.ts").wasmBackend);
    (0, onnxruntime_common_1.registerBackend)('cpu', wasmBackend, 10);
    (0, onnxruntime_common_1.registerBackend)('wasm', wasmBackend, 10);
    (0, onnxruntime_common_1.registerBackend)('xnnpack', wasmBackend, 9);
}


/***/ }),

/***/ "./lib/onnxjs/attribute-with-cache-key.ts":
/*!************************************************!*\
  !*** ./lib/onnxjs/attribute-with-cache-key.ts ***!
  \************************************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.createAttributeWithCacheKey = void 0;
class AttributeWithCacheKeyImpl {
    constructor(attribute) {
        Object.assign(this, attribute);
    }
    get cacheKey() {
        if (!this._cacheKey) {
            this._cacheKey =
                Object.getOwnPropertyNames(this).sort().map(name => `${this[name]}`).join(';');
        }
        return this._cacheKey;
    }
}
const createAttributeWithCacheKey = (attribute) => new AttributeWithCacheKeyImpl(attribute);
exports.createAttributeWithCacheKey = createAttributeWithCacheKey;


/***/ }),

/***/ "./lib/onnxjs/attribute.ts":
/*!*********************************!*\
  !*** ./lib/onnxjs/attribute.ts ***!
  \*********************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Attribute = void 0;
const onnx_proto_1 = __webpack_require__(/*! onnx-proto */ "./node_modules/onnx-proto/dist/onnx.js");
const ort_generated_1 = __webpack_require__(/*! ./ort-schema/ort-generated */ "./lib/onnxjs/ort-schema/ort-generated.ts");
const tensor_1 = __webpack_require__(/*! ./tensor */ "./lib/onnxjs/tensor.ts");
const util_1 = __webpack_require__(/*! ./util */ "./lib/onnxjs/util.ts");
var ortFbs = ort_generated_1.onnxruntime.experimental.fbs;
class Attribute {
    constructor(attributes) {
        this._attributes = new Map();
        if (attributes !== null && attributes !== undefined) {
            for (const attr of attributes) {
                if (attr instanceof onnx_proto_1.onnx.AttributeProto) {
                    this._attributes.set(attr.name, [Attribute.getValue(attr), Attribute.getType(attr)]);
                }
                else if (attr instanceof ortFbs.Attribute) {
                    this._attributes.set(attr.name(), [Attribute.getValue(attr), Attribute.getType(attr)]);
                }
            }
            if (this._attributes.size < attributes.length) {
                throw new Error('duplicated attribute names');
            }
        }
    }
    set(key, type, value) {
        this._attributes.set(key, [value, type]);
    }
    delete(key) {
        this._attributes.delete(key);
    }
    getFloat(key, defaultValue) {
        return this.get(key, 'float', defaultValue);
    }
    getInt(key, defaultValue) {
        return this.get(key, 'int', defaultValue);
    }
    getString(key, defaultValue) {
        return this.get(key, 'string', defaultValue);
    }
    getTensor(key, defaultValue) {
        return this.get(key, 'tensor', defaultValue);
    }
    getFloats(key, defaultValue) {
        return this.get(key, 'floats', defaultValue);
    }
    getInts(key, defaultValue) {
        return this.get(key, 'ints', defaultValue);
    }
    getStrings(key, defaultValue) {
        return this.get(key, 'strings', defaultValue);
    }
    getTensors(key, defaultValue) {
        return this.get(key, 'tensors', defaultValue);
    }
    get(key, type, defaultValue) {
        const valueAndType = this._attributes.get(key);
        if (valueAndType === undefined) {
            if (defaultValue !== undefined) {
                return defaultValue;
            }
            throw new Error(`required attribute not found: ${key}`);
        }
        if (valueAndType[1] !== type) {
            throw new Error(`type mismatch: expected ${type} but got ${valueAndType[1]}`);
        }
        return valueAndType[0];
    }
    static getType(attr) {
        const type = attr instanceof onnx_proto_1.onnx.AttributeProto ? (attr).type : attr.type();
        switch (type) {
            case onnx_proto_1.onnx.AttributeProto.AttributeType.FLOAT:
                return 'float';
            case onnx_proto_1.onnx.AttributeProto.AttributeType.INT:
                return 'int';
            case onnx_proto_1.onnx.AttributeProto.AttributeType.STRING:
                return 'string';
            case onnx_proto_1.onnx.AttributeProto.AttributeType.TENSOR:
                return 'tensor';
            case onnx_proto_1.onnx.AttributeProto.AttributeType.FLOATS:
                return 'floats';
            case onnx_proto_1.onnx.AttributeProto.AttributeType.INTS:
                return 'ints';
            case onnx_proto_1.onnx.AttributeProto.AttributeType.STRINGS:
                return 'strings';
            case onnx_proto_1.onnx.AttributeProto.AttributeType.TENSORS:
                return 'tensors';
            default:
                throw new Error(`attribute type is not supported yet: ${onnx_proto_1.onnx.AttributeProto.AttributeType[type]}`);
        }
    }
    static getValue(attr) {
        const attrType = attr instanceof onnx_proto_1.onnx.AttributeProto ? attr.type : attr.type();
        if (attrType === onnx_proto_1.onnx.AttributeProto.AttributeType.GRAPH || attrType === onnx_proto_1.onnx.AttributeProto.AttributeType.GRAPHS) {
            throw new Error('graph attribute is not supported yet');
        }
        const value = this.getValueNoCheck(attr);
        // cast LONG to number
        if (attrType === onnx_proto_1.onnx.AttributeProto.AttributeType.INT && util_1.LongUtil.isLong(value)) {
            return util_1.LongUtil.longToNumber(value);
        }
        // cast LONG[] to number[]
        if (attrType === onnx_proto_1.onnx.AttributeProto.AttributeType.INTS) {
            const arr = value;
            const numberValue = new Array(arr.length);
            for (let i = 0; i < arr.length; i++) {
                const maybeLong = arr[i];
                numberValue[i] = util_1.LongUtil.longToNumber(maybeLong);
            }
            return numberValue;
        }
        // cast onnx.TensorProto to onnxjs.Tensor
        if (attrType === onnx_proto_1.onnx.AttributeProto.AttributeType.TENSOR) {
            return attr instanceof onnx_proto_1.onnx.AttributeProto ? tensor_1.Tensor.fromProto(value) :
                tensor_1.Tensor.fromOrtTensor(value);
        }
        // cast onnx.TensorProto[] to onnxjs.Tensor[]
        if (attrType === onnx_proto_1.onnx.AttributeProto.AttributeType.TENSORS) {
            if (attr instanceof onnx_proto_1.onnx.AttributeProto) {
                const tensorProtos = value;
                return tensorProtos.map(value => tensor_1.Tensor.fromProto(value));
            }
            else if (attr instanceof ortFbs.Attribute) {
                const tensorProtos = value;
                return tensorProtos.map(value => tensor_1.Tensor.fromOrtTensor(value));
            }
        }
        // cast Uint8Array to string
        if (attrType === onnx_proto_1.onnx.AttributeProto.AttributeType.STRING) {
            // string in onnx attribute is of uint8array type, so we need to convert it to string below. While in ort format,
            // string attributes are returned as string, so no conversion is needed.
            if (attr instanceof onnx_proto_1.onnx.AttributeProto) {
                const utf8String = value;
                return (0, util_1.decodeUtf8String)(utf8String);
            }
        }
        // cast Uint8Array[] to string[]
        if (attrType === onnx_proto_1.onnx.AttributeProto.AttributeType.STRINGS) {
            // strings in onnx attribute is returned as uint8array[], so we need to convert it to string[] below. While in ort
            // format strings attributes are returned as string[], so no conversion is needed.
            if (attr instanceof onnx_proto_1.onnx.AttributeProto) {
                const utf8Strings = value;
                return utf8Strings.map(util_1.decodeUtf8String);
            }
        }
        return value;
    }
    static getValueNoCheck(attr) {
        return attr instanceof (onnx_proto_1.onnx.AttributeProto) ? this.getValueNoCheckFromOnnxFormat(attr) :
            this.getValueNoCheckFromOrtFormat(attr);
    }
    static getValueNoCheckFromOnnxFormat(attr) {
        switch (attr.type) {
            case onnx_proto_1.onnx.AttributeProto.AttributeType.FLOAT:
                return attr.f;
            case onnx_proto_1.onnx.AttributeProto.AttributeType.INT:
                return attr.i;
            case onnx_proto_1.onnx.AttributeProto.AttributeType.STRING:
                return attr.s;
            case onnx_proto_1.onnx.AttributeProto.AttributeType.TENSOR:
                return attr.t;
            case onnx_proto_1.onnx.AttributeProto.AttributeType.GRAPH:
                return attr.g;
            case onnx_proto_1.onnx.AttributeProto.AttributeType.FLOATS:
                return attr.floats;
            case onnx_proto_1.onnx.AttributeProto.AttributeType.INTS:
                return attr.ints;
            case onnx_proto_1.onnx.AttributeProto.AttributeType.STRINGS:
                return attr.strings;
            case onnx_proto_1.onnx.AttributeProto.AttributeType.TENSORS:
                return attr.tensors;
            case onnx_proto_1.onnx.AttributeProto.AttributeType.GRAPHS:
                return attr.graphs;
            default:
                throw new Error(`unsupported attribute type: ${onnx_proto_1.onnx.AttributeProto.AttributeType[attr.type]}`);
        }
    }
    static getValueNoCheckFromOrtFormat(attr) {
        switch (attr.type()) {
            case ortFbs.AttributeType.FLOAT:
                return attr.f();
            case ortFbs.AttributeType.INT:
                return attr.i();
            case ortFbs.AttributeType.STRING:
                return attr.s();
            case ortFbs.AttributeType.TENSOR:
                return attr.t();
            case ortFbs.AttributeType.GRAPH:
                return attr.g();
            case ortFbs.AttributeType.FLOATS:
                return attr.floatsArray();
            case ortFbs.AttributeType.INTS: {
                const ints = [];
                for (let i = 0; i < attr.intsLength(); i++) {
                    ints.push(attr.ints(i));
                }
                return ints;
            }
            case ortFbs.AttributeType.STRINGS: {
                const strings = [];
                for (let i = 0; i < attr.stringsLength(); i++) {
                    strings.push(attr.strings(i));
                }
                return strings;
            }
            case ortFbs.AttributeType.TENSORS: {
                const tensors = [];
                for (let i = 0; i < attr.tensorsLength(); i++) {
                    tensors.push(attr.tensors(i));
                }
                return tensors;
            }
            // case ortFbs.AttributeType.GRAPHS:
            // TODO: Subgraph not supported yet.
            // const graphs = [];
            // for (let i = 0; i < attr.graphsLength(); i++) {
            //   graphs.push(attr.graphs(i)!);
            // }
            // return graphs;
            default:
                throw new Error(`unsupported attribute type: ${ortFbs.AttributeType[attr.type()]}`);
        }
    }
}
exports.Attribute = Attribute;


/***/ }),

/***/ "./lib/onnxjs/backend.ts":
/*!*******************************!*\
  !*** ./lib/onnxjs/backend.ts ***!
  \*******************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.resolveBackend = exports.backend = void 0;
const backend_webgl_1 = __webpack_require__(/*! ./backends/backend-webgl */ "./lib/onnxjs/backends/backend-webgl.ts");
// caches all initialized backend instances
const backendsCache = new Map();
exports.backend = {
    webgl: new backend_webgl_1.WebGLBackend(),
};
/**
 * Resolve a reference to the backend. If a hint is specified, the corresponding
 * backend will be used.
 */
async function resolveBackend(hint) {
    if (!hint) {
        return resolveBackend(['webgl']);
    }
    else {
        const hints = typeof hint === 'string' ? [hint] : hint;
        for (const backendHint of hints) {
            const cache = backendsCache.get(backendHint);
            if (cache) {
                return cache;
            }
            const backend = await tryLoadBackend(backendHint);
            if (backend) {
                return backend;
            }
        }
    }
    throw new Error('no available backend to use');
}
exports.resolveBackend = resolveBackend;
async function tryLoadBackend(backendHint) {
    const backendObj = exports.backend;
    if (typeof backendObj[backendHint] !== 'undefined' && isBackend(backendObj[backendHint])) {
        const backend = backendObj[backendHint];
        let init = backend.initialize();
        if (typeof init === 'object' && 'then' in init) {
            init = await init;
        }
        if (init) {
            backendsCache.set(backendHint, backend);
            return backend;
        }
    }
    return undefined;
}
function isBackend(obj) {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const o = obj;
    // check if an object is a Backend instance
    if ('initialize' in o && typeof o.initialize === 'function' && // initialize()
        'createSessionHandler' in o && typeof o.createSessionHandler === 'function' && // createSessionHandler()
        'dispose' in o && typeof o.dispose === 'function' // dispose()
    ) {
        return true;
    }
    return false;
}


/***/ }),

/***/ "./lib/onnxjs/backends/backend-webgl.ts":
/*!**********************************************!*\
  !*** ./lib/onnxjs/backends/backend-webgl.ts ***!
  \**********************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.WebGLBackend = void 0;
const onnxruntime_common_1 = __webpack_require__(/*! onnxruntime-common */ "../common/dist/lib/index.js");
const instrument_1 = __webpack_require__(/*! ../instrument */ "./lib/onnxjs/instrument.ts");
const session_handler_1 = __webpack_require__(/*! ./webgl/session-handler */ "./lib/onnxjs/backends/webgl/session-handler.ts");
const webgl_context_factory_1 = __webpack_require__(/*! ./webgl/webgl-context-factory */ "./lib/onnxjs/backends/webgl/webgl-context-factory.ts");
/**
 * WebGLBackend is the entry point for all WebGL opeartions
 * When it starts it created the WebGLRenderingContext
 * and other main framework components such as Program and Texture Managers
 */
class WebGLBackend {
    get contextId() {
        return onnxruntime_common_1.env.webgl.contextId;
    }
    set contextId(value) {
        onnxruntime_common_1.env.webgl.contextId = value;
    }
    get matmulMaxBatchSize() {
        return onnxruntime_common_1.env.webgl.matmulMaxBatchSize;
    }
    set matmulMaxBatchSize(value) {
        onnxruntime_common_1.env.webgl.matmulMaxBatchSize = value;
    }
    get textureCacheMode() {
        return onnxruntime_common_1.env.webgl.textureCacheMode;
    }
    set textureCacheMode(value) {
        onnxruntime_common_1.env.webgl.textureCacheMode = value;
    }
    get pack() {
        return onnxruntime_common_1.env.webgl.pack;
    }
    set pack(value) {
        onnxruntime_common_1.env.webgl.pack = value;
    }
    get async() {
        return onnxruntime_common_1.env.webgl.async;
    }
    set async(value) {
        onnxruntime_common_1.env.webgl.async = value;
    }
    initialize() {
        try {
            this.glContext = (0, webgl_context_factory_1.createWebGLContext)(this.contextId);
            if (typeof this.matmulMaxBatchSize !== 'number') {
                this.matmulMaxBatchSize = 16;
            }
            if (typeof this.textureCacheMode !== 'string') {
                this.textureCacheMode = 'full';
            }
            if (typeof this.pack !== 'boolean') {
                this.pack = false;
            }
            if (typeof this.async !== 'boolean') {
                this.async = false;
            }
            instrument_1.Logger.setWithEnv(onnxruntime_common_1.env);
            instrument_1.Logger.verbose('WebGLBackend', `Created WebGLContext: ${typeof this.glContext} with matmulMaxBatchSize: ${this.matmulMaxBatchSize}; textureCacheMode: ${this.textureCacheMode}; pack: ${this.pack}; async: ${this.async}.`);
            return true;
        }
        catch (e) {
            instrument_1.Logger.warning('WebGLBackend', `Unable to initialize WebGLBackend. ${e}`);
            return false;
        }
    }
    createSessionHandler(context) {
        return new session_handler_1.WebGLSessionHandler(this, context);
    }
    dispose() {
        this.glContext.dispose();
    }
}
exports.WebGLBackend = WebGLBackend;


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/glsl-coordinate-lib.ts":
/*!**********************************************************!*\
  !*** ./lib/onnxjs/backends/webgl/glsl-coordinate-lib.ts ***!
  \**********************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.CoordsGlslLib = void 0;
const util_1 = __webpack_require__(/*! ../../util */ "./lib/onnxjs/util.ts");
const glsl_definitions_1 = __webpack_require__(/*! ./glsl-definitions */ "./lib/onnxjs/backends/webgl/glsl-definitions.ts");
const glsl_source_1 = __webpack_require__(/*! ./glsl-source */ "./lib/onnxjs/backends/webgl/glsl-source.ts");
const texture_layout_strategy_1 = __webpack_require__(/*! ./texture-layout-strategy */ "./lib/onnxjs/backends/webgl/texture-layout-strategy.ts");
const utils_1 = __webpack_require__(/*! ./utils */ "./lib/onnxjs/backends/webgl/utils.ts");
/**
 * GLSL Library responsible for data types and routines for manipulating
 * coordinates and mapping to/from tensor indices
 */
class CoordsGlslLib extends glsl_definitions_1.GlslLib {
    constructor(context) {
        super(context);
    }
    getFunctions() {
        return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, this.offsetToCoords()), this.coordsToOffset()), this.toVec()), this.valueFrom()), this.getCommonUtilFuncs()), this.getInputsSamplingSnippets()), this.getOutputSamplingSnippet());
    }
    getCustomTypes() {
        return {};
    }
    /**
     * Produces a function that can map from
     * 2D normalzied coordinates (s,t) to a flat offset
     */
    offsetToCoords() {
        const funcName = 'offsetToCoords';
        return {
            offsetToCoords: new glsl_definitions_1.GlslLibRoutine(`
      vec2 ${funcName}(int offset, int width, int height) {
        int t = offset / width;
        int s = offset - t*width;
        vec2 coords = (vec2(s,t) + vec2(0.5,0.5)) / vec2(width, height);
        return coords;
      }
      `)
        };
    }
    /**
     * Produces a function that can map from
     * 2D normalzied coordinates (s,t) to a flat offset
     */
    coordsToOffset() {
        const funcName = 'coordsToOffset';
        return {
            coordsToOffset: new glsl_definitions_1.GlslLibRoutine(`
      int ${funcName}(vec2 coords, int width, int height) {
        float s = coords.s * float(width);
        float t = coords.t * float(height);
        int offset = int(t) * width + int(s);
        return offset;
      }
      `)
        };
    }
    /**
     * Generates code for output sampler.
     */
    getOutputSamplingSnippet() {
        const outputLayout = this.context.outputTextureLayout;
        if (outputLayout.isPacked) {
            return this.getPackedOutputSamplingSnippet(outputLayout);
        }
        else {
            return this.getUnpackedOutputSamplingSnippet(outputLayout);
        }
    }
    /**
     * Generates code for packed output sampler.
     */
    getPackedOutputSamplingSnippet(outputLayout) {
        const outShape = outputLayout.unpackedShape;
        const outTexShape = [outputLayout.width, outputLayout.height];
        const result = {};
        const funcName = 'getOutputCoords';
        switch (outShape.length) {
            case 0:
                result[funcName] = this.getOutputScalarCoords();
                break;
            case 1:
                result[funcName] = this.getOutputPacked1DCoords(outShape, outTexShape);
                break;
            case 2:
                result[funcName] = this.getOutputPacked2DCoords(outShape, outTexShape);
                break;
            case 3:
                result[funcName] =
                    this.getOutputPacked3DCoords(outShape, outTexShape);
                break;
            default:
                result[funcName] = this.getOutputPackedNDCoords(outShape, outTexShape);
        }
        const glsl = (0, glsl_source_1.getGlsl)(this.context.glContext.version);
        // TODO we need this to properly return a packed vec4 from kernels.
        // Replace all '{glsl.output} = result' with 'setOutput(result)' in all kernels.
        const floatTextureSetRGBASource = `
      void setOutput(vec4 val) {
        ${glsl.output} = val;
      }
    `;
        const floatTextureSetRGBAFuncName = 'floatTextureSetRGBA';
        result[floatTextureSetRGBAFuncName] = new glsl_definitions_1.GlslLibRoutine(floatTextureSetRGBASource);
        return result;
    }
    /**
     * Generates code for unpacked output sampler.
     */
    getUnpackedOutputSamplingSnippet(outputLayout) {
        const outShape = outputLayout.unpackedShape;
        const outTexShape = [outputLayout.width, outputLayout.height];
        const result = {};
        const funcName = 'getOutputCoords';
        switch (outShape.length) {
            case 0:
                result[funcName] = this.getOutputScalarCoords();
                break;
            case 1:
                result[funcName] = this.getOutputUnpacked1DCoords(outShape, outTexShape);
                break;
            case 2:
                result[funcName] =
                    this.getOutputUnpacked2DCoords(outShape, outTexShape);
                break;
            case 3:
                result[funcName] =
                    this.getOutputUnpacked3DCoords(outShape, outTexShape);
                break;
            case 4:
                result[funcName] = this.getOutputUnpacked4DCoords(outShape, outTexShape);
                break;
            case 5:
                result[funcName] = this.getOutputUnpacked5DCoords(outShape, outTexShape);
                break;
            case 6:
                result[funcName] = this.getOutputUnpacked6DCoords(outShape, outTexShape);
                break;
            default:
                throw new Error(`Unsupported output dimensionality: ${outShape.length}`);
        }
        const glsl = (0, glsl_source_1.getGlsl)(this.context.glContext.version);
        // TODO we need this to properly return a packed vec4 from kernels.
        // Replace all '{glsl.output} = result' with 'setOutput(result)' in all kernels.
        const floatTextureSetRSource = `
        void setOutput(float val) {
          ${glsl.output} = vec4(val, 0, 0, 0);
        }
    `;
        const floatTextureSetRFuncName = 'floatTextureSetR';
        result[floatTextureSetRFuncName] = new glsl_definitions_1.GlslLibRoutine(floatTextureSetRSource);
        return result;
    }
    /**
     * Scalar output coordinates.
     */
    getOutputScalarCoords() {
        return new glsl_definitions_1.GlslLibRoutine(`
      int getOutputCoords() {
        return 0;
      }
    `);
    }
    /**
     * 1D packed output coordinates.
     */
    getOutputPacked1DCoords(shape, texShape) {
        const packedTexShape = texShape;
        let source = '';
        if (packedTexShape[0] === 1) {
            source = `
          int getOutputCoords() {
            return 2 * int(TexCoords.y * ${packedTexShape[1]}.0);
          }
        `;
            return new glsl_definitions_1.GlslLibRoutine(source);
        }
        if (packedTexShape[1] === 1) {
            source = `
          int getOutputCoords() {
            return 2 * int(TexCoords.x * ${packedTexShape[0]}.0);
          }
        `;
            return new glsl_definitions_1.GlslLibRoutine(source);
        }
        source = `
        int getOutputCoords() {
          ivec2 resTexRC = ivec2(TexCoords.xy *
                                 vec2(${packedTexShape[0]}, ${packedTexShape[1]}));
          return 2 * (resTexRC.y * ${packedTexShape[0]} + resTexRC.x);
        }
      `;
        return new glsl_definitions_1.GlslLibRoutine(source);
    }
    /**
     * 2D packed output coordinates.
     */
    getOutputPacked2DCoords(shape, texShape) {
        let source = '';
        if (util_1.ArrayUtil.arraysEqual(shape, texShape)) {
            source = `
        ivec2 getOutputCoords() {
          return 2 * ivec2(TexCoords.xy * vec2(${texShape[0]}, ${texShape[1]}));
        }
      `;
            return new glsl_definitions_1.GlslLibRoutine(source);
        }
        const packedTexShape = texShape;
        // texels needed to accommodate a logical row
        const texelsInLogicalRow = Math.ceil(shape[1] / 2);
        /**
         * getOutputCoords
         *
         * resTexRC: The rows and columns of the texels. If you move over one
         * texel to the right in the packed texture, you are moving over one column
         * (not two).
         *
         * index: The texel index
         */
        source = `
        ivec2 getOutputCoords() {
          ivec2 resTexRC = ivec2(TexCoords.xy *
                                vec2(${packedTexShape[0]}, ${packedTexShape[1]}));

          int index = resTexRC.y * ${packedTexShape[0]} + resTexRC.x;

          // reverse r and c order for packed texture
          int r = imod(index, ${texelsInLogicalRow}) * 2;
          int c = 2 * (index / ${texelsInLogicalRow});

          return ivec2(r, c);
        }
      `;
        return new glsl_definitions_1.GlslLibRoutine(source);
    }
    /**
     * 3D packed output coordinates.
     */
    getOutputPacked3DCoords(shape, texShape) {
        const packedTexShape = [texShape[0], texShape[1]];
        const texelsInLogicalRow = Math.ceil(shape[2] / 2);
        const texelsInBatch = texelsInLogicalRow * Math.ceil(shape[1] / 2);
        const source = `
        ivec3 getOutputCoords() {
          ivec2 resTexRC = ivec2(TexCoords.xy *
                                vec2(${packedTexShape[0]}, ${packedTexShape[1]}));
          int index = resTexRC.y * ${packedTexShape[0]} + resTexRC.x;

          int b = index / ${texelsInBatch};
          index -= b * ${texelsInBatch};

          // reverse r and c order for packed texture
          int r = imod(index, ${texelsInLogicalRow}) * 2;
          int c = 2 * (index / ${texelsInLogicalRow});

          return ivec3(b, r, c);
        }
      `;
        return new glsl_definitions_1.GlslLibRoutine(source);
    }
    /**
     * ND packed output coordinates.
     */
    getOutputPackedNDCoords(shape, texShape) {
        const packedTexShape = [texShape[0], texShape[1]];
        const texelsInLogicalRow = Math.ceil(shape[shape.length - 1] / 2);
        const texelsInBatch = texelsInLogicalRow * Math.ceil(shape[shape.length - 2] / 2);
        let texelsInBatchN = texelsInBatch;
        let batches = '';
        let coords = 'b, r, c';
        for (let b = 2; b < shape.length - 1; b++) {
            texelsInBatchN *= shape[shape.length - b - 1];
            batches = `
      int b${b} = index / ${texelsInBatchN};
      index -= b${b} * ${texelsInBatchN};
    ` + batches;
            coords = `b${b}, ` + coords;
        }
        const source = `
      ivec${shape.length} getOutputCoords() {
        ivec2 resTexRC = ivec2(TexCoords.xy *
                              vec2(${packedTexShape[0]}, ${packedTexShape[1]}));
        int index = resTexRC.y * ${packedTexShape[0]} + resTexRC.x;

        ${batches}

        int b = index / ${texelsInBatch};
        index -= b * ${texelsInBatch};

        // reverse r and c order for packed texture
        int r = imod(index, ${texelsInLogicalRow}) * 2;
        int c = 2 * (index / ${texelsInLogicalRow});

        return ivec${shape.length}(${coords});
      }
    `;
        return new glsl_definitions_1.GlslLibRoutine(source);
    }
    /**
     * Unpacked 1D output coordinates.
     */
    getOutputUnpacked1DCoords(shape, texShape) {
        const source = `
        int getOutputCoords() {
          ivec2 resTexRC = ivec2(TexCoords.xy *
                                vec2(${texShape[0]}, ${texShape[1]}));
          return resTexRC.y * ${texShape[0]} + resTexRC.x;
        }
      `;
        return new glsl_definitions_1.GlslLibRoutine(source);
    }
    /**
     * Unpacked 2D output coordinates.
     */
    getOutputUnpacked2DCoords(shape, texShape) {
        const source = `
        ivec2 getOutputCoords() {
          ivec2 resTexRC = ivec2(TexCoords.xy *
                                vec2(${texShape[0]}, ${texShape[1]}));
          int index = resTexRC.y * ${texShape[0]} + resTexRC.x;
          int r = index / ${shape[1]};
          int c = index - r * ${shape[1]};
          return ivec2(r, c);
        }
      `;
        return new glsl_definitions_1.GlslLibRoutine(source);
    }
    /**
     * Unpacked 3D output coordinates.
     */
    getOutputUnpacked3DCoords(shape, texShape) {
        let source = '';
        const rank = shape.length;
        let strides = null;
        if (rank < 2) {
            strides = [];
        }
        strides = new Array(rank - 1);
        strides[rank - 2] = shape[rank - 1];
        for (let i = rank - 3; i >= 0; --i) {
            strides[i] = strides[i + 1] * shape[i + 1];
        }
        const coordsToCompute = ['r', 'c', 'd'];
        const coordsFromIndexSnippet = strides
            .map((stride, i) => {
            const line1 = `int ${coordsToCompute[i]} = index / ${stride}`;
            const line2 = i === strides.length - 1 ?
                `int ${coordsToCompute[i + 1]} = index - ${coordsToCompute[i]} * ${stride}` :
                `index -= ${coordsToCompute[i]} * ${stride}`;
            return `${line1}; ${line2};`;
        })
            .join('');
        source = `
        ivec3 getOutputCoords() {
          ivec2 resTexRC = ivec2(TexCoords.xy *
                                vec2(${texShape[0]}, ${texShape[1]}));
          int index = resTexRC.y * ${texShape[0]} + resTexRC.x;
          ${coordsFromIndexSnippet}
          return ivec3(r, c, d);
        }
      `;
        return new glsl_definitions_1.GlslLibRoutine(source);
    }
    /**
     * Unpacked 4D output coordinates.
     */
    getOutputUnpacked4DCoords(shape, texShape) {
        let source = '';
        const rank = shape.length;
        let strides = null;
        if (rank < 2) {
            strides = [];
        }
        strides = new Array(rank - 1);
        strides[rank - 2] = shape[rank - 1];
        for (let i = rank - 3; i >= 0; --i) {
            strides[i] = strides[i + 1] * shape[i + 1];
        }
        const coordsToCompute = ['r', 'c', 'd', 'd2'];
        const coordsFromIndexSnippet = strides
            .map((stride, i) => {
            const line1 = `int ${coordsToCompute[i]} = index / ${stride}`;
            const line2 = i === strides.length - 1 ?
                `int ${coordsToCompute[i + 1]} = index - ${coordsToCompute[i]} * ${stride}` :
                `index -= ${coordsToCompute[i]} * ${stride}`;
            return `${line1}; ${line2};`;
        })
            .join('');
        source = `
      ivec4 getOutputCoords() {
          ivec2 resTexRC = ivec2(TexCoords.xy *
                                vec2(${texShape[0]}, ${texShape[1]}));
          int index = resTexRC.y * ${texShape[0]} + resTexRC.x;
          ${coordsFromIndexSnippet}
          return ivec4(r, c, d, d2);
        }
      `;
        return new glsl_definitions_1.GlslLibRoutine(source);
    }
    /**
     * Unpacked 5D output coordinates.
     */
    getOutputUnpacked5DCoords(shape, texShape) {
        let source = '';
        const rank = shape.length;
        let strides = null;
        if (rank < 2) {
            strides = [];
        }
        strides = new Array(rank - 1);
        strides[rank - 2] = shape[rank - 1];
        for (let i = rank - 3; i >= 0; --i) {
            strides[i] = strides[i + 1] * shape[i + 1];
        }
        const coordsToCompute = ['r', 'c', 'd', 'd2', 'd3'];
        const coordsFromIndexSnippet = strides
            .map((stride, i) => {
            const line1 = `int ${coordsToCompute[i]} = index / ${stride}`;
            const line2 = i === strides.length - 1 ?
                `int ${coordsToCompute[i + 1]} = index - ${coordsToCompute[i]} * ${stride}` :
                `index -= ${coordsToCompute[i]} * ${stride}`;
            return `${line1}; ${line2};`;
        })
            .join('');
        source = `
      ivec5 getOutputCoords() {
          ivec2 resTexRC = ivec2(TexCoords.xy *
                                vec2(${texShape[0]}, ${texShape[1]}));
          int index = resTexRC.y * ${texShape[0]} + resTexRC.x;
          ${coordsFromIndexSnippet}
          return ivec5(r, c, d, d2, d3);
        }
      `;
        return new glsl_definitions_1.GlslLibRoutine(source);
    }
    /**
     * Unpacked 6D output coordinates.
     */
    getOutputUnpacked6DCoords(shape, texShape) {
        let source = '';
        const rank = shape.length;
        let strides = null;
        if (rank < 2) {
            strides = [];
        }
        strides = new Array(rank - 1);
        strides[rank - 2] = shape[rank - 1];
        for (let i = rank - 3; i >= 0; --i) {
            strides[i] = strides[i + 1] * shape[i + 1];
        }
        const coordsToCompute = ['r', 'c', 'd', 'd2', 'd3', 'd4'];
        const coordsFromIndexSnippet = strides
            .map((stride, i) => {
            const line1 = `int ${coordsToCompute[i]} = index / ${stride}`;
            const line2 = i === strides.length - 1 ?
                `int ${coordsToCompute[i + 1]} = index - ${coordsToCompute[i]} * ${stride}` :
                `index -= ${coordsToCompute[i]} * ${stride}`;
            return `${line1}; ${line2};`;
        })
            .join('');
        source = `
     ivec6 getOutputCoords() {
         ivec2 resTexRC = ivec2(TexCoords.xy *
                               vec2(${texShape[0]}, ${texShape[1]}));
         int index = resTexRC.y * ${texShape[0]} + resTexRC.x;
         ${coordsFromIndexSnippet}
         return ivec6(r, c, d, d2, d3, d4);
       }
     `;
        return new glsl_definitions_1.GlslLibRoutine(source);
    }
    /**
     * Generates code for common UV coords computation utility functions.
     */
    getCommonUtilFuncs() {
        const result = {};
        let funcName = 'uvFromFlat';
        result[funcName] = new glsl_definitions_1.GlslLibRoutine(`
    vec2 uvFromFlat(int texNumR, int texNumC, int index) {
      int texC = index / texNumR;
      int texR = index - texC * texNumR;
      // TODO: swap texR, texC order in following function so row is corresponding to u and column is corresponding to
      //       v.
      return (vec2(texR, texC) + halfCR) / vec2(texNumR, texNumC);
    }
    `);
        funcName = 'packedUVfrom1D';
        result[funcName] = new glsl_definitions_1.GlslLibRoutine(`
      vec2 packedUVfrom1D(int texNumR, int texNumC, int index) {
        int texelIndex = index / 2;
        int texR = texelIndex / texNumC;
        int texC = texelIndex - texR * texNumC;
        return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
      }
      `);
        funcName = 'packedUVfrom2D';
        result[funcName] = new glsl_definitions_1.GlslLibRoutine(`
      vec2 packedUVfrom2D(int texNumR, int texNumC, int texelsInLogicalRow, int row, int col) {
        int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2);
        int texR = texelIndex / texNumC;
        int texC = texelIndex - texR * texNumC;
        return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
      }
      `);
        funcName = 'packedUVfrom3D';
        result[funcName] = new glsl_definitions_1.GlslLibRoutine(`
      vec2 packedUVfrom3D(int texNumR, int texNumC,
          int texelsInBatch, int texelsInLogicalRow, int b,
          int row, int col) {
        int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2);
        int texR = index / texNumC;
        int texC = index - texR * texNumC;
        return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
      }
      `);
        funcName = 'sampleTexture';
        const glsl = (0, glsl_source_1.getGlsl)(this.context.glContext.version);
        result[funcName] = new glsl_definitions_1.GlslLibRoutine(`
        float sampleTexture(sampler2D textureSampler, vec2 uv) {
            return ${glsl.texture2D}(textureSampler, uv).r;
        }`);
        return result;
    }
    /**
     * Constructing snippets for inputs
     */
    getInputsSamplingSnippets() {
        const result = {};
        const outputLayout = this.context.outputTextureLayout;
        this.context.programInfo.inputNames.forEach((samplerName, i) => {
            const inputLayout = this.context.inputTextureLayouts[i];
            const funcName = (0, utils_1.generateShaderFuncNameFromInputSamplerName)(samplerName);
            if (inputLayout.isPacked) {
                result[funcName] = this.getPackedSamplerFromInput(funcName, samplerName, inputLayout);
            }
            else {
                result[funcName] = this.getUnpackedSamplerFromInput(funcName, samplerName, inputLayout);
            }
            const outCoordFuncName = (0, utils_1.generateShaderFuncNameFromInputSamplerNameAtOutCoords)(samplerName);
            if (inputLayout.unpackedShape.length <= outputLayout.unpackedShape.length) {
                if (inputLayout.isPacked) {
                    result[outCoordFuncName] =
                        this.getPackedSamplerAtOutputCoords(outCoordFuncName, inputLayout, outputLayout, samplerName);
                }
                else {
                    result[outCoordFuncName] =
                        this.getUnpackedSamplerAtOutputCoords(outCoordFuncName, inputLayout, outputLayout, samplerName);
                }
            }
        });
        return result;
    }
    /**
     * Constructing snippets for output coordinates of samplers
     */
    getPackedSamplerAtOutputCoords(funcName, inputLayout, outputLayout, name) {
        const inShape = inputLayout.unpackedShape;
        const outShape = outputLayout.unpackedShape;
        const texName = name;
        const texFuncSnippet = (0, utils_1.generateShaderFuncNameFromInputSamplerName)(texName);
        const inRank = inShape.length;
        const outRank = outShape.length;
        const broadcastDims = util_1.BroadcastUtil.getBroadcastDims(inShape, outShape);
        const type = (0, utils_1.getCoordsDataType)(outRank);
        const rankDiff = outRank - inRank;
        let coordsSnippet;
        const fields = (0, utils_1.getGlChannels)();
        if (inRank === 0) {
            coordsSnippet = '';
        }
        else if (outRank < 2 && broadcastDims.length >= 1) {
            coordsSnippet = 'coords = 0;';
        }
        else {
            coordsSnippet = broadcastDims.map(d => `coords.${fields[d + rankDiff]} = 0;`).join('\n');
        }
        let unpackedCoordsSnippet = '';
        if (outRank < 2 && inRank > 0) {
            unpackedCoordsSnippet = 'coords';
        }
        else {
            unpackedCoordsSnippet = inShape.map((s, i) => `coords.${fields[i + rankDiff]}`).join(', ');
        }
        let output = 'return outputValue;';
        const inSize = util_1.ShapeUtil.size(inShape);
        const isInputScalar = inSize === 1;
        const outSize = util_1.ShapeUtil.size(outShape);
        const isOutputScalar = outSize === 1;
        if (inRank === 1 && !isInputScalar && !isOutputScalar) {
            output = `
        return vec4(outputValue.xy, outputValue.xy);
      `;
        }
        else if (isInputScalar && !isOutputScalar) {
            if (outRank === 1) {
                output = `
          return vec4(outputValue.x, outputValue.x, 0., 0.);
        `;
            }
            else {
                output = `
          return vec4(outputValue.x);
        `;
            }
        }
        else if (broadcastDims.length) {
            const rows = inRank - 2;
            const cols = inRank - 1;
            if (broadcastDims.indexOf(rows) > -1 && broadcastDims.indexOf(cols) > -1) {
                output = 'return vec4(outputValue.x);';
            }
            else if (broadcastDims.indexOf(rows) > -1) {
                output = 'return vec4(outputValue.x, outputValue.y, ' +
                    'outputValue.x, outputValue.y);';
            }
            else if (broadcastDims.indexOf(cols) > -1) {
                output = 'return vec4(outputValue.xx, outputValue.zz);';
            }
        }
        const swapLastDimsSnippet = `
        int lastDim = coords.${fields[outRank - 1]};
        coords.${fields[outRank - 1]} = coords.${fields[outRank - 2]};
        coords.${fields[outRank - 2]} = lastDim;
      `;
        const source = `
      vec4 ${funcName}() {
        ${type} coords = getOutputCoords();
        ${swapLastDimsSnippet}
        ${coordsSnippet}
        vec4 outputValue = ${texFuncSnippet}(${unpackedCoordsSnippet});
        ${output}
      }
    `;
        return new glsl_definitions_1.GlslLibRoutine(source, ['coordinates.getOutputCoords']);
    }
    /**
     * Constructing snippets for unpacked output coordinates of samplers
     */
    getUnpackedSamplerAtOutputCoords(funcName, inputLayout, outputLayout, name) {
        const outTexShape = [outputLayout.width, outputLayout.height];
        const inTexShape = [inputLayout.width, inputLayout.height];
        const inRank = inputLayout.unpackedShape.length;
        const outRank = outputLayout.unpackedShape.length;
        const inShape = inputLayout.unpackedShape;
        const outShape = outputLayout.unpackedShape;
        const texFuncSnippet = (0, utils_1.generateShaderFuncNameFromInputSamplerName)(name);
        if (inRank === outRank && util_1.ArrayUtil.arraysEqual(inTexShape, outTexShape)) {
            const source = `
          float ${funcName}() {
            return sampleTexture(${name}, TexCoords);
          }
        `;
            return new glsl_definitions_1.GlslLibRoutine(source, ['coordinates.sampleTexture']);
        }
        const type = (0, utils_1.getCoordsDataType)(outRank);
        const broadcastDims = util_1.BroadcastUtil.getBroadcastDims(inShape, outShape);
        const rankDiff = outRank - inRank;
        let coordsSnippet;
        const fields = (0, utils_1.getGlChannels)();
        if (inRank === 0) {
            coordsSnippet = '';
        }
        else if (outRank < 2 && broadcastDims.length >= 1) {
            coordsSnippet = 'coords = 0;';
        }
        else {
            coordsSnippet = broadcastDims.map(d => `coords.${fields[d + rankDiff]} = 0;`).join('\n');
        }
        let unpackedCoordsSnippet = '';
        if (outRank < 2 && inRank > 0) {
            unpackedCoordsSnippet = 'coords';
        }
        else {
            unpackedCoordsSnippet = inputLayout.unpackedShape.map((s, i) => `coords.${fields[i + rankDiff]}`).join(', ');
        }
        const source = `
        float ${funcName}() {
          ${type} coords = getOutputCoords();
          ${coordsSnippet}
          return ${texFuncSnippet}(${unpackedCoordsSnippet});
        }
      `;
        return new glsl_definitions_1.GlslLibRoutine(source, ['coordinates.getOutputCoords']);
    }
    /**
     * Constructing snippets for packed operations.
     */
    getPackedSamplerFromInput(funcName, name, inputLayout) {
        switch (inputLayout.unpackedShape.length) {
            case 0:
                return this.getPackedSamplerScalar(funcName, name);
            case 1:
                return this.getPackedSampler1D(funcName, name, inputLayout);
            case 2:
                return this.getPackedSampler2D(funcName, name, inputLayout);
            case 3:
                return this.getPackedSampler3D(funcName, name, inputLayout);
            default:
                return this.getPackedSamplerND(funcName, name, inputLayout);
        }
    }
    /**
     * Constructing snippets for unpacked operations.
     */
    getUnpackedSamplerFromInput(funcName, name, inputLayout) {
        const shape = inputLayout.unpackedShape;
        switch (shape.length) {
            case 0:
                return this.getUnpackedSamplerScalar(funcName, name, inputLayout);
            case 1:
                return this.getUnpackedSampler1D(funcName, name, inputLayout);
            case 2:
                return this.getUnpackedSampler2D(funcName, name, inputLayout);
            case 3:
                return this.getUnpackedSampler3D(funcName, name, inputLayout);
            case 4:
                return this.getUnpackedSampler4D(funcName, name, inputLayout);
            case 5:
                return this.getUnpackedSampler5D(funcName, name, inputLayout);
            case 6:
                return this.getUnpackedSampler6D(funcName, name, inputLayout);
            default:
                // TODO support more dimensionalities
                throw new Error(`Unsupported dimension ${shape.length}-D`);
        }
    }
    /**
     * Packed scalar snippet.
     */
    getPackedSamplerScalar(funcName, name) {
        const glsl = (0, glsl_source_1.getGlsl)(this.context.glContext.version);
        const source = `
          vec4 ${funcName}() {
            return ${glsl.texture2D}(${name}, halfCR);
          }
        `;
        return new glsl_definitions_1.GlslLibRoutine(source);
    }
    /**
     * Packed 1D snippet.
     */
    getPackedSampler1D(funcName, name, inputLayout) {
        const texShape = [inputLayout.width, inputLayout.height];
        const packedTexShape = [texShape[1], texShape[0]];
        const glsl = (0, glsl_source_1.getGlsl)(this.context.glContext.version);
        const packedSampler = `vec4 ${funcName}(int index) {
      vec2 uv = packedUVfrom1D(
      ${packedTexShape[0]}, ${packedTexShape[1]}, index);
      return ${glsl.texture2D}(${name}, uv);
    }`;
        const source = packedSampler;
        return new glsl_definitions_1.GlslLibRoutine(source, ['coordinates.packedUVfrom1D']);
    }
    /**
     * Packed 2D snippet.
     */
    getPackedSampler2D(funcName, name, inputLayout) {
        const shape = inputLayout.unpackedShape;
        const texShape = [inputLayout.width, inputLayout.height];
        const glsl = (0, glsl_source_1.getGlsl)(this.context.glContext.version);
        const texNumR = texShape[0];
        const texNumC = texShape[1];
        if (texShape != null && util_1.ArrayUtil.arraysEqual(shape, texShape)) {
            const packedSampler = `vec4 ${funcName}(int row, int col) {
        vec2 uv = (vec2(col, row) + halfCR) / vec2(${texNumC}.0, ${texNumR}.0);
        return ${glsl.texture2D}(${name}, uv);
      }`;
            return new glsl_definitions_1.GlslLibRoutine(packedSampler);
        }
        const packedTexShape = texShape;
        const valuesPerRow = Math.ceil(shape[1] / 2);
        const packedSampler = `vec4 ${funcName}(int row, int col) {
      vec2 uv = packedUVfrom2D(${packedTexShape[1]}, ${packedTexShape[0]}, ${valuesPerRow}, row, col);
      return ${glsl.texture2D}(${name}, uv);
    }`;
        const source = packedSampler;
        return new glsl_definitions_1.GlslLibRoutine(source, ['coordinates.packedUVfrom2D']);
    }
    /**
     * Packed 3D snippet.
     */
    getPackedSampler3D(funcName, name, inputLayout) {
        const shape = inputLayout.unpackedShape;
        const texShape = [inputLayout.width, inputLayout.height];
        const packedTexShape = [texShape[0], texShape[1]];
        const glsl = (0, glsl_source_1.getGlsl)(this.context.glContext.version);
        if (shape[0] === 1) {
            const squeezedShape = shape.slice(1);
            const keptDims = [1, 2];
            const newInputShape = (0, utils_1.squeezeInputShape)(shape, squeezedShape);
            const params = ['b', 'row', 'col'];
            // Deep copy of input texture layout.
            const newInputLayout = JSON.parse(JSON.stringify(inputLayout));
            newInputLayout.unpackedShape = newInputShape;
            const samplerRoutine = this.getPackedSamplerFromInput(funcName, name, newInputLayout);
            const packedSampler = `${samplerRoutine.routineBody}
      vec4 ${funcName}(int b, int row, int col) {
        return ${funcName}(${(0, utils_1.getSqueezedParams)(params, keptDims)});
      } `;
            const source = packedSampler;
            return new glsl_definitions_1.GlslLibRoutine(source, samplerRoutine.dependencies);
        }
        const texNumR = packedTexShape[0];
        const texNumC = packedTexShape[1];
        const valuesPerRow = Math.ceil(shape[2] / 2);
        const texelsInBatch = valuesPerRow * Math.ceil(shape[1] / 2);
        const packedSampler = `vec4 ${funcName}(int b, int row, int col) {
      vec2 uv = packedUVfrom3D(
        ${texNumC}, ${texNumR}, ${texelsInBatch}, ${valuesPerRow}, b, row, col);
      return ${glsl.texture2D}(${name}, uv);}`;
        const source = packedSampler;
        return new glsl_definitions_1.GlslLibRoutine(source, ['coordinates.packedUVfrom3D']);
    }
    /*
     * Packed ND snippet.
     */
    getPackedSamplerND(funcName, name, inputLayout) {
        const shape = inputLayout.unpackedShape;
        const rank = shape.length;
        const texShape = [inputLayout.width, inputLayout.height];
        const glsl = (0, glsl_source_1.getGlsl)(this.context.glContext.version);
        const packedTexShape = [texShape[0], texShape[1]];
        const texNumR = packedTexShape[1];
        const texNumC = packedTexShape[0];
        const valuesPerRow = Math.ceil(shape[rank - 1] / 2);
        let texelsInBatch = valuesPerRow * Math.ceil(shape[rank - 2] / 2);
        let params = 'int b, int row, int col';
        let index = `b * ${texelsInBatch} + (row / 2) * ${valuesPerRow} + (col / 2)`;
        for (let b = 2; b < rank - 1; b++) {
            params = `int b${b}, ` + params;
            texelsInBatch *= shape[rank - b - 1];
            index = `b${b} * ${texelsInBatch} + ` + index;
        }
        const packedSampler = `vec4 ${funcName}(${params}) {
      int index = ${index};
      int texR = index / ${texNumC};
      int texC = index - texR * ${texNumC};
      vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${texNumC}, ${texNumR});
      return ${glsl.texture2D}(${name}, uv);
    }`;
        const source = packedSampler;
        return new glsl_definitions_1.GlslLibRoutine(source);
    }
    /**
     * Unpacked scalar snippet.
     */
    getUnpackedSamplerScalar(funcName, name, inputLayout) {
        const [texNumR, texNumC] = [inputLayout.width, inputLayout.height];
        if (texNumR === 1 && texNumC === 1) {
            const source = `
          float ${funcName}() {
            return sampleTexture(${name}, halfCR);
          }
        `;
            return new glsl_definitions_1.GlslLibRoutine(source, ['coordinates.sampleTexture']);
        }
        const source = `
        float ${funcName}() {
          int offset_${name} = coordsToOffset(TexCoords, ${texNumR}, ${texNumC});
          vec2 uv = uvFromFlat(${texNumR}, ${texNumC}, offset_${name});
          return sampleTexture(${name}, uv);
        }
      `;
        return new glsl_definitions_1.GlslLibRoutine(source, ['coordinates.uvFromFlat', 'coordinates.sampleTexture', 'coordinates.coordsToOffset']);
    }
    /**
     * Unpacked 1D snippet.
     */
    getUnpackedSampler1D(funcName, name, inputLayout) {
        const tNumR = inputLayout.width;
        const tNumC = inputLayout.height;
        if (tNumC === 1 && tNumR === 1) {
            const source = `
        float ${funcName}(int index) {
          return sampleTexture(${name}, halfCR);
        }
      `;
            return new glsl_definitions_1.GlslLibRoutine(source, ['coordinates.sampleTexture']);
        }
        if (tNumC === 1) {
            const source = `
          float ${funcName}(int index) {
            vec2 uv = vec2((float(index) + 0.5) / ${tNumR}.0, 0.5);
            return sampleTexture(${name}, uv);
          }
        `;
            return new glsl_definitions_1.GlslLibRoutine(source, ['coordinates.sampleTexture']);
        }
        if (tNumR === 1) {
            const source = `
          float ${funcName}(int index) {
            vec2 uv = vec2(0.5, (float(index) + 0.5) / ${tNumC}.0);
            return sampleTexture(${name}, uv);
          }
        `;
            return new glsl_definitions_1.GlslLibRoutine(source, ['coordinates.sampleTexture']);
        }
        const source = `
        float ${funcName}(int index) {
          vec2 uv = uvFromFlat(${tNumR}, ${tNumC}, index);
          return sampleTexture(${name}, uv);
        }
      `;
        return new glsl_definitions_1.GlslLibRoutine(source, ['coordinates.uvFromFlat', 'coordinates.sampleTexture']);
    }
    /**
     * Unpacked 2D snippet.
     */
    getUnpackedSampler2D(funcName, name, inputLayout) {
        const shape = inputLayout.unpackedShape;
        // TODO: modify row/col order for other dimensions.
        const texShape = [inputLayout.height, inputLayout.width];
        if (texShape != null && util_1.ArrayUtil.arraysEqual(shape, texShape)) {
            const texNumR = texShape[1];
            const texNumC = texShape[0];
            const source = `
          float ${funcName}(int row, int col) {
            vec2 uv = (vec2(row, col) + halfCR) / vec2(${texNumR}.0, ${texNumC}.0);
            return sampleTexture(${name}, uv);
          }
        `;
            return new glsl_definitions_1.GlslLibRoutine(source, ['coordinates.sampleTexture']);
        }
        const { newShape, keptDims } = (0, texture_layout_strategy_1.squeezeShape)(shape);
        const squeezedShape = newShape;
        if (squeezedShape.length < shape.length) {
            const newInputShape = (0, utils_1.squeezeInputShape)(shape, squeezedShape);
            // Deep copy of input texture layout.
            const newInputLayout = JSON.parse(JSON.stringify(inputLayout));
            newInputLayout.unpackedShape = newInputShape;
            const params = ['col', 'row'];
            const source = `
          ${this.getUnpackedSamplerFromInput(funcName, name, newInputLayout).routineBody}
          float ${funcName}(int row, int col) {
            return ${funcName}(${(0, utils_1.getSqueezedParams)(params, keptDims)});
          }
        `;
            return new glsl_definitions_1.GlslLibRoutine(source, ['coordinates.sampleTexture']);
        }
        const texNumR = texShape[1];
        const texNumC = texShape[0];
        if (texNumC === 1) {
            const source = `
          float ${funcName}(int row, int col) {
            int offset_${name} = coordsToOffset(TexCoords, ${texNumR}, ${texNumC});
            float index = dot(vec3(row, col, offset_${name}), vec3(${shape[1]}, 1, 1));
            vec2 uv = vec2(0.5, (index + 0.5) / ${texNumR}.0);
            return sampleTexture(${name}, uv);
          }
        `;
            return new glsl_definitions_1.GlslLibRoutine(source, ['coordinates.sampleTexture', 'coordinates.coordsToOffset']);
        }
        if (texNumR === 1) {
            const source = `
          float ${funcName}(int row, int col) {
            int offset_${name} = coordsToOffset(TexCoords, ${texNumR}, ${texNumC});
            float index = dot(vec3(row, col, offset_${name}), vec3(${shape[1]}, 1, 1));
            vec2 uv = vec2((index + 0.5) / ${texNumC}.0, 0.5);
            return sampleTexture(${name}, uv);
          }
        `;
            return new glsl_definitions_1.GlslLibRoutine(source, ['coordinates.sampleTexture', 'coordinates.coordsToOffset']);
        }
        const source = `
        float ${funcName}(int row, int col) {
          int index = col * ${shape[1]} + row;
          vec2 uv = uvFromFlat(${texNumR}, ${texNumC}, index);
          return sampleTexture(${name}, uv);
        }
      `;
        return new glsl_definitions_1.GlslLibRoutine(source, ['coordinates.uvFromFlat', 'coordinates.sampleTexture', 'coordinates.coordsToOffset']);
    }
    /**
     * Unpacked 3D snippet.
     */
    getUnpackedSampler3D(funcName, name, inputLayout) {
        const shape = inputLayout.unpackedShape;
        const stride0 = shape[1] * shape[2];
        const stride1 = shape[2];
        const { newShape, keptDims } = (0, texture_layout_strategy_1.squeezeShape)(shape);
        const squeezedShape = newShape;
        if (squeezedShape.length < shape.length) {
            const newInputShape = (0, utils_1.squeezeInputShape)(shape, squeezedShape);
            const params = ['batch', 'col', 'row'];
            // Deep copy of input texture layout.
            const newInputLayout = JSON.parse(JSON.stringify(inputLayout));
            newInputLayout.unpackedShape = newInputShape;
            const routine = this.getUnpackedSamplerFromInput(funcName, name, newInputLayout);
            // TODO: revisit the logic here to make it simpler
            const revDims = keptDims.reverse();
            const source = `
          ${routine.routineBody}
          float ${funcName}(int batch, int row, int col) {
            return ${funcName}(${(0, utils_1.getSqueezedParams)(params, revDims)});
          }
        `;
            return new glsl_definitions_1.GlslLibRoutine(source, routine.dependencies);
        }
        const texNumR = inputLayout.width;
        const texNumC = inputLayout.height;
        const source = `
          float ${funcName}(int depth, int row, int col) {
            // Explicitly use integer operations as dot() only works on floats.
            int index = depth * ${stride0} + col * ${stride1} + row;
            vec2 uv = uvFromFlat(${texNumR}, ${texNumC}, index);
            return sampleTexture(${name}, uv);
          }
      `;
        return new glsl_definitions_1.GlslLibRoutine(source, ['coordinates.uvFromFlat', 'coordinates.sampleTexture', 'coordinates.coordsToOffset']);
    }
    /**
     * Unpacked 4D snippet.
     */
    getUnpackedSampler4D(funcName, name, inputLayout) {
        const shape = inputLayout.unpackedShape;
        const stride2 = shape[3];
        const stride1 = shape[2] * stride2;
        const stride0 = shape[1] * stride1;
        //
        // TODO: re-enable this shortcut once the index calculation bug is fixed.
        //
        // const {newShape, keptDims} = squeezeShape(shape as number[]);
        // if (newShape.length < shape.length) {
        //   const newInputShape = squeezeInputShape(shape, newShape);
        //   const params = ['row', 'col', 'depth', 'depth2'];
        //   // Deep copy of input texture layout.
        //   const newInputLayout: TextureLayout = JSON.parse(JSON.stringify(inputLayout));
        //   newInputLayout.unpackedShape = newInputShape;
        //   const source = `
        //       ${this.getUnpackedSamplerFromInput(funcName, name, newInputLayout).routineBody}
        //       float ${funcName}(int row, int col, int depth, int depth2) {
        //         return ${funcName}(${getSqueezedParams(params, keptDims)});
        //       }
        //     `;
        //   return new GlslLibRoutine(
        //       source, ['coordinates.uvFromFlat', 'coordinates.sampleTexture', 'coordinates.coordsToOffset']);
        // }
        const texNumR = inputLayout.width;
        const texNumC = inputLayout.height;
        const source = `
        float ${funcName}(int row, int col, int depth, int depth2) {
          int index = row * ${stride0} + col * ${stride1} +
              depth2 * ${stride2} + depth;
          vec2 uv = uvFromFlat(${texNumR}, ${texNumC}, index);
          return sampleTexture(${name}, uv);
        }
      `;
        return new glsl_definitions_1.GlslLibRoutine(source, ['coordinates.uvFromFlat', 'coordinates.sampleTexture']);
    }
    /**
     * Unpacked 5D snippet.
     */
    getUnpackedSampler5D(funcName, name, inputLayout) {
        const shape = inputLayout.unpackedShape;
        const stride3 = shape[4];
        const stride2 = shape[3] * stride3;
        const stride1 = shape[2] * stride2;
        const stride0 = shape[1] * stride1;
        const { newShape, keptDims } = (0, texture_layout_strategy_1.squeezeShape)(shape);
        if (newShape.length < shape.length) {
            const newInputShape = (0, utils_1.squeezeInputShape)(shape, newShape);
            const params = ['row', 'col', 'depth', 'depth2', 'depth3'];
            // Deep copy of input texture layout.
            const newInputLayout = JSON.parse(JSON.stringify(inputLayout));
            newInputLayout.unpackedShape = newInputShape;
            const source = `
          ${this.getUnpackedSamplerFromInput(funcName, name, newInputLayout).routineBody}
          float ${funcName}(int row, int col, int depth, int depth2, int depth3) {
            return ${funcName}(${(0, utils_1.getSqueezedParams)(params, keptDims)});
          }
        `;
            return new glsl_definitions_1.GlslLibRoutine(source, ['coordinates.sampleTexture', 'coordinates.uvFromFlat']);
        }
        const texNumR = inputLayout.width;
        const texNumC = inputLayout.height;
        const source = `
        float ${funcName}(int row, int col, int depth, int depth2, int depth3) {
          int index = row * ${stride0} + col * ${stride1} + depth * ${stride2} +
          depth3 * ${stride3} + depth2;
          vec2 uv = uvFromFlat(${texNumR}, ${texNumC}, index);
          return sampleTexture(${name}, uv);
        }
      `;
        return new glsl_definitions_1.GlslLibRoutine(source, ['coordinates.sampleTexture', 'coordinates.uvFromFlat']);
    }
    /**
     * Unpacked 6D snippet.
     */
    getUnpackedSampler6D(funcName, name, inputLayout) {
        const shape = inputLayout.unpackedShape;
        const stride4 = shape[5];
        const stride3 = shape[4] * stride4;
        const stride2 = shape[3] * stride3;
        const stride1 = shape[2] * stride2;
        const stride0 = shape[1] * stride1;
        const { newShape, keptDims } = (0, texture_layout_strategy_1.squeezeShape)(shape);
        if (newShape.length < shape.length) {
            const newInputShape = (0, utils_1.squeezeInputShape)(shape, newShape);
            const params = ['row', 'col', 'depth', 'depth2', 'depth3', 'depth4'];
            // Deep copy of input texture layout.
            const newInputLayout = JSON.parse(JSON.stringify(inputLayout));
            newInputLayout.unpackedShape = newInputShape;
            const source = `
            ${this.getUnpackedSamplerFromInput(funcName, name, newInputLayout).routineBody}
            float ${funcName}(int row, int col, int depth,
              int depth2, int depth3, int depth4) {
              return ${funcName}(${(0, utils_1.getSqueezedParams)(params, keptDims)});
            }
          `;
            return new glsl_definitions_1.GlslLibRoutine(source, ['coordinates.sampleTexture', 'coordinates.uvFromFlat']);
        }
        const texNumR = inputLayout.width;
        const texNumC = inputLayout.height;
        const source = `
          float ${funcName}(int row, int col, int depth,
            int depth2, int depth3, int depth4) {
            int index = row * ${stride0} + col * ${stride1} + depth * ${stride2} +
            depth2 * ${stride3} + depth3 * ${stride4} + depth4;
            vec2 uv = uvFromFlat(${texNumR}, ${texNumC}, index);
            return sampleTexture(${name}, uv);
          }
        `;
        return new glsl_definitions_1.GlslLibRoutine(source, ['coordinates.uvFromFlat', 'coordinates.sampleTexture', 'coordinates.coordsToOffset']);
    }
    /**
     * This is the main function to map from the given texture coordiantes (s,t)
     * to logical indices for the output
     * There will only be one single variation of this
     * Also see coordsToOffset and offsetToIndices for input-specific versions
     */
    toVec() {
        const output = this.context.outputTextureLayout;
        const rank = output.shape.length;
        const strides = output.strides;
        const xScale = output.width;
        const yScale = output.height;
        const stridesBlock = [];
        for (let i = 0; i < rank - 1; ++i) {
            stridesBlock.push(`
        c[${i}] = offset / ${strides[i]};`);
            stridesBlock.push(`
        offset -= c[${i}] * ${strides[i]};`);
        }
        stridesBlock.push(`
        c[${rank - 1}] = offset;`);
        const body = `
      void toVec(vec2 texCoords, out int c[${rank}]) {
        int offset = coordsToOffset(texCoords, ${xScale}, ${yScale});
        ${stridesBlock.join('')}
      }
      void toVec(int offset, out int c[${rank}]) {
        ${stridesBlock.join('')}
      }
    `;
        return { toVec: new glsl_definitions_1.GlslLibRoutine(body, ['coordinates.coordsToOffset']) };
    }
    /**
     * These are value getter functions generated for each input
     * Each function is hardwired to the name and dimensions of the input
     * An '_T' variation is also produced which accesses values as if the
     * input was transposed
     */
    valueFrom() {
        const result = {};
        this.context.programInfo.inputNames.forEach((name, i) => {
            const layout = this.context.inputTextureLayouts[i];
            const shape = layout.unpackedShape.length > 0 ? layout.unpackedShape : layout.shape;
            const rank = shape.length;
            let funcName = `_${name}`;
            result[funcName] = new glsl_definitions_1.GlslLibRoutine(this.getValueFromSingle(name, rank, layout.width, layout.height, false), [`shapeUtils.indicesToOffset${funcName}`, 'coordinates.offsetToCoords', 'fragcolor.getColorAsFloat']);
            funcName = funcName + '_T';
            result[funcName] = new glsl_definitions_1.GlslLibRoutine(this.getValueFromSingle(name, rank, layout.width, layout.height, true), [`shapeUtils.indicesToOffset${funcName}`, 'coordinates.offsetToCoords', 'fragcolor.getColorAsFloat']);
        });
        return result;
    }
    /**
     * Produces one value getter function for the name and rank given
     * If a transpose is set proper offsetToCoords mapping will be used
     * @param name name of the function
     * @param rank rank of the input
     * @param transpose whether or not should generate a transpose variation
     */
    getValueFromSingle(varName, rank, width, height, transpose) {
        let name = `_${varName}`;
        if (transpose) {
            name = name + '_T';
        }
        const glsl = (0, glsl_source_1.getGlsl)(this.context.glContext.version);
        return `
        float ${name}(int m[${rank}]) {
          int offset = indicesToOffset${name}(m);
          vec2 coords = offsetToCoords(offset, ${width}, ${height});
          float value = getColorAsFloat(${glsl.texture2D}(${varName}, coords));
          return value;
        }
        `;
    }
    /**
     * Produces a packed value getter function for the name and rank given
     * If a transpose is set proper offsetToCoords mapping will be used
     * @param name name of the function
     * @param rank rank of the input
     * @param transpose whether or not should generate a transpose variation
     */
    getPackedValueFrom(varName, rank, width, height, transpose) {
        let name = `_${varName}_Pack`;
        if (transpose) {
            name = name + '_T';
        }
        const glsl = (0, glsl_source_1.getGlsl)(this.context.glContext.version);
        return `
        vec4 ${name}(int m[${rank}]) {
          int offset = indicesToOffset_${varName}(m);
          vec2 coords = offsetToCoords(offset, ${width}, ${height});
          return ${glsl.texture2D}(${varName}, coords);
        }
        `;
    }
}
exports.CoordsGlslLib = CoordsGlslLib;


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/glsl-definitions.ts":
/*!*******************************************************!*\
  !*** ./lib/onnxjs/backends/webgl/glsl-definitions.ts ***!
  \*******************************************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.TopologicalSortGlslRoutines = exports.GlslLibRoutineNode = exports.GlslLibRoutine = exports.GlslLib = exports.GlslContext = exports.FunctionType = void 0;
/* eslint-disable @typescript-eslint/naming-convention */
var FunctionType;
(function (FunctionType) {
    FunctionType[FunctionType["ValueBased"] = 0] = "ValueBased";
    FunctionType[FunctionType["Positional"] = 1] = "Positional";
})(FunctionType = exports.FunctionType || (exports.FunctionType = {}));
class GlslContext {
    constructor(glContext, programInfo, inputTextureLayouts, outputTextureLayout) {
        this.glContext = glContext;
        this.programInfo = programInfo;
        this.inputTextureLayouts = inputTextureLayouts;
        this.outputTextureLayout = outputTextureLayout;
    }
}
exports.GlslContext = GlslContext;
class GlslLib {
    constructor(context) {
        this.context = context;
    }
}
exports.GlslLib = GlslLib;
// abstraction to represent a GLSL library routine and it's dependencies
class GlslLibRoutine {
    constructor(routineBody, dependencies) {
        this.routineBody = routineBody;
        this.dependencies = dependencies;
    }
}
exports.GlslLibRoutine = GlslLibRoutine;
// abstraction to represent a GLSL library routine and it's dependencies AS GRAPH Nodes
// this level of abstraction is used to topologically sort routines before fragment shade inclusion
class GlslLibRoutineNode {
    constructor(name, routineBody, dependencies) {
        this.name = name;
        if (dependencies) {
            this.dependencies = dependencies;
        }
        else {
            this.dependencies = [];
        }
        if (routineBody) {
            this.routineBody = routineBody;
        }
    }
    addDependency(node) {
        if (node) {
            this.dependencies.push(node);
        }
    }
}
exports.GlslLibRoutineNode = GlslLibRoutineNode;
// topologically sort GLSL library routines (graph nodes abstraction) before shader script inclusion
class TopologicalSortGlslRoutines {
    static returnOrderedNodes(nodes) {
        if (!nodes || nodes.length === 0) {
            return [];
        }
        if (nodes.length === 1) {
            return nodes;
        }
        const cycleCheck = new Set();
        const alreadyTraversed = new Set();
        const result = new Array();
        this.createOrderedNodes(nodes, cycleCheck, alreadyTraversed, result);
        return result;
    }
    static createOrderedNodes(graphNodes, cycleCheck, alreadyTraversed, result) {
        for (let i = 0; i < graphNodes.length; ++i) {
            this.dfsTraverse(graphNodes[i], cycleCheck, alreadyTraversed, result);
        }
    }
    static dfsTraverse(root, cycleCheck, alreadyTraversed, result) {
        // if this root has already been traversed return
        if (!root || alreadyTraversed.has(root.name)) {
            return;
        }
        // cyclic dependency has been detected
        if (cycleCheck.has(root.name)) {
            throw new Error('Cyclic dependency detected. Can\'t topologically sort routines needed for shader.');
        }
        // hold this node to detect cycles if any
        cycleCheck.add(root.name);
        // traverse children in a dfs fashion
        const dependencies = root.dependencies;
        if (dependencies && dependencies.length > 0) {
            for (let i = 0; i < dependencies.length; ++i) {
                this.dfsTraverse(dependencies[i], cycleCheck, alreadyTraversed, result);
            }
        }
        // add to result holder
        result.push(root);
        // mark this node as traversed so that we don't traverse from this again
        alreadyTraversed.add(root.name);
        // release the hold
        cycleCheck.delete(root.name);
    }
}
exports.TopologicalSortGlslRoutines = TopologicalSortGlslRoutines;


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/glsl-encoding-lib.ts":
/*!********************************************************!*\
  !*** ./lib/onnxjs/backends/webgl/glsl-encoding-lib.ts ***!
  \********************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.EncodingGlslLib = void 0;
const glsl_definitions_1 = __webpack_require__(/*! ./glsl-definitions */ "./lib/onnxjs/backends/webgl/glsl-definitions.ts");
/**
 * This GLSL library handles routines converting
 * float32 to/from Unsigned byte or float 16
 */
class EncodingGlslLib extends glsl_definitions_1.GlslLib {
    constructor(context) {
        super(context);
    }
    getFunctions() {
        return Object.assign(Object.assign({}, this.encodeFloat32()), this.decodeFloat32());
    }
    getCustomTypes() {
        return {};
    }
    encodeFloat32() {
        return {
            encode: new glsl_definitions_1.GlslLibRoutine(`highp vec4 encode(highp float f) {
        return vec4(f, 0.0, 0.0, 0.0);
      }
        `)
        };
    }
    decodeFloat32() {
        return {
            decode: new glsl_definitions_1.GlslLibRoutine(`highp float decode(highp vec4 rgba) {
        return rgba.r;
      }
        `)
        };
    }
    /**
     * returns the routine to encode encode a 32bit float to a vec4 (of unsigned bytes)
     * @credit: https://stackoverflow.com/questions/7059962/how-do-i-convert-a-vec4-rgba-value-to-a-float
     */
    encodeUint8() {
        const endianness = EncodingGlslLib.isLittleEndian() ? 'rgba.rgba=rgba.abgr;' : '';
        return {
            encode: new glsl_definitions_1.GlslLibRoutine(`
      highp vec4 encode(highp float f) {
        highp float F = abs(f);
        highp float Sign = step(0.0,-f);
        highp float Exponent = floor(log2(F));
        highp float Mantissa = (exp2(- Exponent) * F);
        Exponent = floor(log2(F) + 127.0) + floor(log2(Mantissa));
        highp vec4 rgba;
        rgba[0] = 128.0 * Sign  + floor(Exponent*exp2(-1.0));
        rgba[1] = 128.0 * mod(Exponent,2.0) + mod(floor(Mantissa*128.0),128.0);
        rgba[2] = floor(mod(floor(Mantissa*exp2(23.0 -8.0)),exp2(8.0)));
        rgba[3] = floor(exp2(23.0)*mod(Mantissa,exp2(-15.0)));
        ${endianness}
        rgba = rgba / 255.0; // values need to be normalized to [0,1]
        return rgba;
    }
        `)
        };
    }
    /**
     * returns the routine to encode a vec4 of unsigned bytes to float32
     * @credit: https://stackoverflow.com/questions/7059962/how-do-i-convert-a-vec4-rgba-value-to-a-float
     */
    decodeUint8() {
        const endianness = EncodingGlslLib.isLittleEndian() ? 'rgba.rgba=rgba.abgr;' : '';
        return {
            decode: new glsl_definitions_1.GlslLibRoutine(`
        highp float decode(highp vec4 rgba) {
          rgba = rgba * 255.0; // values need to be de-normalized from [0,1] to [0,255]
          ${endianness}
          highp float Sign = 1.0 - step(128.0,rgba[0])*2.0;
          highp float Exponent = 2.0 * mod(rgba[0],128.0) + step(128.0,rgba[1]) - 127.0;
          highp float Mantissa = mod(rgba[1],128.0)*65536.0 + rgba[2]*256.0 +rgba[3] + float(0x800000);
          highp float Result =  Sign * exp2(Exponent) * (Mantissa * exp2(-23.0 ));
          return Result;
      }
        `)
        };
    }
    /**
     * Determines if the machine is little endian or not
     * @credit: https://gist.github.com/TooTallNate/4750953
     */
    static isLittleEndian() {
        const b = new ArrayBuffer(4);
        const a = new Uint32Array(b);
        const c = new Uint8Array(b);
        a[0] = 0xdeadbeef;
        if (c[0] === 0xef) {
            return true;
        }
        if (c[0] === 0xde) {
            return false;
        }
        throw new Error('unknown endianness');
    }
}
exports.EncodingGlslLib = EncodingGlslLib;


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/glsl-fragcolor-lib.ts":
/*!*********************************************************!*\
  !*** ./lib/onnxjs/backends/webgl/glsl-fragcolor-lib.ts ***!
  \*********************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.FragColorGlslLib = void 0;
const glsl_definitions_1 = __webpack_require__(/*! ./glsl-definitions */ "./lib/onnxjs/backends/webgl/glsl-definitions.ts");
const glsl_source_1 = __webpack_require__(/*! ./glsl-source */ "./lib/onnxjs/backends/webgl/glsl-source.ts");
/**
 * This GLSL library handles routines around reading a texlet and writing to it
 * Reading and writing could be more than just dealing with one channel
 * It may require encoding/decoding to/from 4 channels into one
 */
class FragColorGlslLib extends glsl_definitions_1.GlslLib {
    constructor(context) {
        super(context);
    }
    getFunctions() {
        return Object.assign(Object.assign({}, this.setFragColor()), this.getColorAsFloat());
    }
    getCustomTypes() {
        return {};
    }
    setFragColor() {
        const glsl = (0, glsl_source_1.getGlsl)(this.context.glContext.version);
        return {
            setFragColor: new glsl_definitions_1.GlslLibRoutine(`
        void setFragColor(float value) {
            ${glsl.output} = encode(value);
        }
        `, ['encoding.encode'])
        };
    }
    getColorAsFloat() {
        return {
            getColorAsFloat: new glsl_definitions_1.GlslLibRoutine(`
        float getColorAsFloat(vec4 color) {
            return decode(color);
        }
        `, ['encoding.decode'])
        };
    }
}
exports.FragColorGlslLib = FragColorGlslLib;


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/glsl-function-inliner.ts":
/*!************************************************************!*\
  !*** ./lib/onnxjs/backends/webgl/glsl-function-inliner.ts ***!
  \************************************************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.replaceInlines = void 0;
const INLINE_FUNC_DEF_REGEX = /@inline[\s\n\r]+(\w+)[\s\n\r]+([0-9a-zA-Z_]+)\s*\(([^)]*)\)\s*{(([^}]|[\n\r])*)}/gm;
const FUNC_CALL_REGEX = '(\\w+)?\\s+([_0-9a-zA-Z]+)\\s+=\\s+__FUNC__\\((.*)\\)\\s*;';
/**
 * GLSL preprocessor responsible for resolving @inline directives
 */
function replaceInlines(script) {
    const inlineDefs = {};
    let match;
    while ((match = INLINE_FUNC_DEF_REGEX.exec(script)) !== null) {
        const params = match[3]
            .split(',')
            .map(s => {
            const tokens = s.trim().split(' ');
            if (tokens && tokens.length === 2) {
                return { type: tokens[0], name: tokens[1] };
            }
            return null;
        })
            .filter(v => v !== null);
        inlineDefs[match[2]] = { params, body: match[4] };
    }
    for (const name in inlineDefs) {
        const regexString = FUNC_CALL_REGEX.replace('__FUNC__', name);
        const regex = new RegExp(regexString, 'gm');
        while ((match = regex.exec(script)) !== null) {
            const type = match[1];
            const variable = match[2];
            const params = match[3].split(',');
            const declLine = (type) ? `${type} ${variable};` : '';
            let newBody = inlineDefs[name].body;
            let paramRedecLine = '';
            inlineDefs[name].params.forEach((v, i) => {
                if (v) {
                    paramRedecLine += `${v.type} ${v.name} = ${params[i]};\n`;
                }
            });
            newBody = `${paramRedecLine}\n ${newBody}`;
            newBody = newBody.replace('return', `${variable} = `);
            const replacement = `
      ${declLine}
      {
        ${newBody}
      }
      `;
            script = script.replace(match[0], replacement);
        }
    }
    script = script.replace(INLINE_FUNC_DEF_REGEX, '');
    return script;
}
exports.replaceInlines = replaceInlines;


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/glsl-preprocessor.ts":
/*!********************************************************!*\
  !*** ./lib/onnxjs/backends/webgl/glsl-preprocessor.ts ***!
  \********************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.GlslPreprocessor = void 0;
const glsl_definitions_1 = __webpack_require__(/*! ./glsl-definitions */ "./lib/onnxjs/backends/webgl/glsl-definitions.ts");
const glsl_function_inliner_1 = __webpack_require__(/*! ./glsl-function-inliner */ "./lib/onnxjs/backends/webgl/glsl-function-inliner.ts");
const glsl_registered_libs_1 = __webpack_require__(/*! ./glsl-registered-libs */ "./lib/onnxjs/backends/webgl/glsl-registered-libs.ts");
const glsl_source_1 = __webpack_require__(/*! ./glsl-source */ "./lib/onnxjs/backends/webgl/glsl-source.ts");
/**
 * Preprocessor for the additions to the GLSL language
 * It deals with:
 *  @include directives
 *  @inline
 *  Loop unrolling (not implemented)
 *  Macro resolution (not implemented)
 */
class GlslPreprocessor {
    constructor(glContext, programInfo, inputTextureLayouts, outputTextureLayout) {
        this.libs = {};
        this.glslLibRoutineDependencyGraph = {};
        this.context = new glsl_definitions_1.GlslContext(glContext, programInfo, inputTextureLayouts, outputTextureLayout);
        // construct GlslLibs
        Object.keys(glsl_registered_libs_1.glslRegistry).forEach((name) => {
            const lib = new glsl_registered_libs_1.glslRegistry[name](this.context);
            this.libs[name] = lib;
        });
        // construct GlslRoutineDependencyGraph
        const map = this.glslLibRoutineDependencyGraph;
        for (const libName in this.libs) {
            const lib = this.libs[libName];
            const routinesInLib = lib.getFunctions();
            for (const routine in routinesInLib) {
                const key = libName + '.' + routine;
                let currentNode;
                if (map[key]) {
                    currentNode = map[key];
                    currentNode.routineBody = routinesInLib[routine].routineBody;
                }
                else {
                    currentNode = new glsl_definitions_1.GlslLibRoutineNode(key, routinesInLib[routine].routineBody);
                    map[key] = currentNode;
                }
                const dependencies = routinesInLib[routine].dependencies;
                if (dependencies) {
                    for (let i = 0; i < dependencies.length; ++i) {
                        if (!map[dependencies[i]]) {
                            const node = new glsl_definitions_1.GlslLibRoutineNode(dependencies[i]);
                            map[dependencies[i]] = node;
                            currentNode.addDependency(node);
                        }
                        else {
                            currentNode.addDependency(map[dependencies[i]]);
                        }
                    }
                }
            }
        }
    }
    preprocess() {
        const programInfo = this.context.programInfo;
        let source = programInfo.shaderSource;
        // append main() function
        if (!this.context.programInfo.hasMain) {
            source = `${source}
      ${(0, glsl_source_1.getDefaultFragShaderMain)(this.context.glContext.version, this.context.outputTextureLayout.shape.length)}`;
        }
        // replace inlines
        source = (0, glsl_function_inliner_1.replaceInlines)(source);
        // concat final source string
        return `${(0, glsl_source_1.getFragShaderPreamble)(this.context.glContext.version)}
    ${this.getUniforms(programInfo.inputNames, programInfo.variables)}
    ${this.getImports(source)}
    ${source}`;
    }
    getImports(script) {
        const routinesIncluded = this.selectGlslLibRoutinesToBeIncluded(script);
        if (routinesIncluded.length === 0) {
            return '';
        }
        let routines = '';
        for (let i = 0; i < routinesIncluded.length; ++i) {
            if (routinesIncluded[i].routineBody) {
                routines += routinesIncluded[i].routineBody + '\n';
            }
            else {
                throw new Error(`Missing body for the Glsl Library routine: ${routinesIncluded[i].name}`);
            }
        }
        return routines;
    }
    selectGlslLibRoutinesToBeIncluded(script) {
        const nodes = [];
        Object.keys(this.glslLibRoutineDependencyGraph).forEach(classAndRoutine => {
            const routine = classAndRoutine.split('.')[1];
            if (script.indexOf(routine) !== -1) {
                nodes.push(this.glslLibRoutineDependencyGraph[classAndRoutine]);
            }
        });
        return glsl_definitions_1.TopologicalSortGlslRoutines.returnOrderedNodes(nodes);
    }
    getUniforms(samplers, variables) {
        const uniformLines = [];
        if (samplers) {
            for (const sampler of samplers) {
                uniformLines.push(`uniform sampler2D ${sampler};`);
            }
        }
        if (variables) {
            for (const variable of variables) {
                uniformLines.push(`uniform ${variable.type} ${variable.name}${variable.arrayLength ? `[${variable.arrayLength}]` : ''};`);
            }
        }
        return uniformLines.join('\n');
    }
}
exports.GlslPreprocessor = GlslPreprocessor;


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/glsl-registered-libs.ts":
/*!***********************************************************!*\
  !*** ./lib/onnxjs/backends/webgl/glsl-registered-libs.ts ***!
  \***********************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.glslRegistry = void 0;
const glsl_coordinate_lib_1 = __webpack_require__(/*! ./glsl-coordinate-lib */ "./lib/onnxjs/backends/webgl/glsl-coordinate-lib.ts");
const glsl_encoding_lib_1 = __webpack_require__(/*! ./glsl-encoding-lib */ "./lib/onnxjs/backends/webgl/glsl-encoding-lib.ts");
const glsl_fragcolor_lib_1 = __webpack_require__(/*! ./glsl-fragcolor-lib */ "./lib/onnxjs/backends/webgl/glsl-fragcolor-lib.ts");
const glsl_shape_utils_lib_1 = __webpack_require__(/*! ./glsl-shape-utils-lib */ "./lib/onnxjs/backends/webgl/glsl-shape-utils-lib.ts");
const glsl_vec_lib_1 = __webpack_require__(/*! ./glsl-vec-lib */ "./lib/onnxjs/backends/webgl/glsl-vec-lib.ts");
exports.glslRegistry = {
    'encoding': glsl_encoding_lib_1.EncodingGlslLib,
    'fragcolor': glsl_fragcolor_lib_1.FragColorGlslLib,
    'vec': glsl_vec_lib_1.VecGlslLib,
    'shapeUtils': glsl_shape_utils_lib_1.ShapeUtilsGlslLib,
    'coordinates': glsl_coordinate_lib_1.CoordsGlslLib,
    //  'arrays': ArrayGlslSLib
};


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/glsl-shape-utils-lib.ts":
/*!***********************************************************!*\
  !*** ./lib/onnxjs/backends/webgl/glsl-shape-utils-lib.ts ***!
  \***********************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ShapeUtilsGlslLib = void 0;
const glsl_definitions_1 = __webpack_require__(/*! ./glsl-definitions */ "./lib/onnxjs/backends/webgl/glsl-definitions.ts");
/**
 * GLSL Library responsible for data types and routines for manipulating
 * coordinates and mapping to/from tensor indices
 */
class ShapeUtilsGlslLib extends glsl_definitions_1.GlslLib {
    constructor(context) {
        super(context);
    }
    getFunctions() {
        return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, this.bcastIndex()), this.bcastMatmulIndex()), this.offsetToIndices()), this.indicesToOffset()), this.incrementIndices());
    }
    getCustomTypes() {
        return {};
    }
    bcastIndex() {
        const outputRank = this.context.outputTextureLayout.shape.length;
        const result = {};
        this.context.programInfo.inputNames.forEach((name, i) => {
            const shape = this.context.inputTextureLayouts[i].unpackedShape;
            if (shape.length <= outputRank) {
                const rank = shape.length;
                const dimOffset = outputRank - rank;
                const funcName = `bcastIndices_${name}`;
                let block = '';
                for (let i = 0; i < rank; ++i) {
                    block += `
          realIndices[${i}] = int( mod(float(bcastedIndices[${dimOffset + i}]), ${shape[i]}.0) );
          `;
                }
                const body = `
        void ${funcName} (int bcastedIndices[${outputRank}], out int realIndices[${rank}]) {
          ${block}
        }
        `;
                result[funcName] = new glsl_definitions_1.GlslLibRoutine(body);
            }
        });
        return result;
    }
    bcastMatmulIndex() {
        const outputRank = this.context.outputTextureLayout.shape.length;
        const result = {};
        this.context.programInfo.inputNames.forEach((name, i) => {
            const shape = this.context.inputTextureLayouts[i].shape;
            if (!(shape.length < 2 || shape.length > outputRank)) {
                const rank = shape.length;
                const dimOffset = outputRank - rank;
                const funcName = `bcastMatmulIndices_${name}`;
                let block = '';
                for (let i = 0; i < rank - 2; ++i) {
                    block += `
          realIndices[${i}] = int( mod(float(bcastedIndices[${dimOffset + i}]), ${shape[i]}.0) );
          `;
                }
                const body = `
        void ${funcName}(int bcastedIndices[${outputRank}], out int realIndices[${rank}]) {
          ${block}
          realIndices[${rank - 1}] = bcastedIndices[${outputRank - 1}];
          realIndices[${rank - 2}] = bcastedIndices[${outputRank - 2}];
        }
        `;
                result[funcName] = new glsl_definitions_1.GlslLibRoutine(body);
            }
        });
        return result;
    }
    indicesToOffset() {
        const result = {};
        this.context.programInfo.inputNames.forEach((name, i) => {
            const shape = this.context.inputTextureLayouts[i].shape;
            const strides = this.context.inputTextureLayouts[i].strides;
            const rank = shape.length;
            let funcName = `indicesToOffset_${name}`;
            result[funcName] = new glsl_definitions_1.GlslLibRoutine(ShapeUtilsGlslLib.indexToOffsetSingle(funcName, rank, strides));
            funcName = `indicesToOffset_${name}_T`;
            result[funcName] =
                new glsl_definitions_1.GlslLibRoutine(ShapeUtilsGlslLib.indexToOffsetSingle(funcName, rank, strides.slice().reverse()));
        });
        return result;
    }
    static indexToOffsetSingle(name, rank, strides) {
        let block = '';
        for (let i = rank - 1; i >= 0; --i) {
            block += `
        offset += indices[${i}] * ${strides[i]};
        `;
        }
        return `
      int ${name}(int indices[${rank}]) {
        int offset = 0;
        ${block}
        return offset;
      }
      `;
    }
    offsetToIndices() {
        const result = {};
        this.context.programInfo.inputNames.forEach((name, i) => {
            const shape = this.context.inputTextureLayouts[i].shape;
            const strides = this.context.inputTextureLayouts[i].strides;
            const rank = shape.length;
            let funcName = `offsetToIndices_${name}`;
            result[funcName] = new glsl_definitions_1.GlslLibRoutine(ShapeUtilsGlslLib.offsetToIndicesSingle(funcName, rank, strides));
            funcName = `offsetToIndices_${name}_T`;
            result[funcName] =
                new glsl_definitions_1.GlslLibRoutine(ShapeUtilsGlslLib.offsetToIndicesSingle(funcName, rank, strides.slice().reverse()));
        });
        return result;
    }
    static offsetToIndicesSingle(name, rank, strides) {
        const stridesBlock = [];
        for (let i = 0; i < rank - 1; ++i) {
            stridesBlock.push(`
      indices[${i}] = offset / ${strides[i]};`);
            stridesBlock.push(`
        offset -= indices[${i}] * ${strides[i]};`);
        }
        stridesBlock.push(`
      indices[${rank - 1}] = offset;`);
        return `
      void ${name}(int offset, out int indices[${rank}]) {
        ${stridesBlock.join('')}
      }
      `;
    }
    incrementIndices() {
        const result = {};
        this.context.programInfo.inputNames.forEach((name, i) => {
            const shape = this.context.inputTextureLayouts[i].shape;
            const rank = shape.length;
            const funcName = `incrementIndices_${name}`;
            let shapeInit = '';
            for (let i = 0; i < rank; ++i) {
                shapeInit += `
        shape[${i}] = ${shape[i]};`;
            }
            const body = `
        void ${funcName}(int axis, out int indices[${rank}]) {
          int shape[${rank}];
          ${shapeInit};
          for(int i = ${rank} -1 ; i >= 0; --i) {
            if(i > axis) continue;
            indices[i] += 1;
            if(indices[i] < shape[i]) {
              break;
            }
            indices[i] = 0;
          }
        }
        `;
            result[funcName] = new glsl_definitions_1.GlslLibRoutine(body);
        });
        return result;
    }
}
exports.ShapeUtilsGlslLib = ShapeUtilsGlslLib;


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/glsl-source.ts":
/*!**************************************************!*\
  !*** ./lib/onnxjs/backends/webgl/glsl-source.ts ***!
  \**************************************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getDefaultFragShaderMain = exports.getFragShaderPreamble = exports.getVertexShaderSource = exports.getGlsl = void 0;
const GLSL_ES_2_0 = {
    version: '',
    attribute: 'attribute',
    varyingVertex: 'varying',
    varyingFrag: 'varying',
    texture2D: 'texture2D',
    output: 'gl_FragColor',
    outputDeclaration: '',
};
const GLSL_ES_3_0 = {
    version: '#version 300 es',
    attribute: 'in',
    varyingVertex: 'out',
    varyingFrag: 'in',
    texture2D: 'texture',
    output: 'outputColor',
    outputDeclaration: 'out vec4 outputColor;',
};
function getGlsl(version) {
    return version === 1 ? GLSL_ES_2_0 : GLSL_ES_3_0;
}
exports.getGlsl = getGlsl;
function getVertexShaderSource(version) {
    const glsl = getGlsl(version);
    return `${glsl.version}
      precision highp float;
      ${glsl.attribute} vec3 position;
      ${glsl.attribute} vec2 textureCoord;

      ${glsl.varyingVertex} vec2 TexCoords;

      void main()
      {
          gl_Position = vec4(position, 1.0);
          TexCoords = textureCoord;
      }`;
}
exports.getVertexShaderSource = getVertexShaderSource;
function getFragShaderPreamble(version) {
    const glsl = getGlsl(version);
    return `${glsl.version}
    precision highp float;
    precision highp int;
    precision highp sampler2D;
    ${glsl.varyingFrag} vec2 TexCoords;
    ${glsl.outputDeclaration}
    const vec2 halfCR = vec2(0.5, 0.5);

    // Custom vector types to handle higher dimenalities.
    struct ivec5
    {
      int x;
      int y;
      int z;
      int w;
      int u;
    };

    struct ivec6
    {
      int x;
      int y;
      int z;
      int w;
      int u;
      int v;
    };

    int imod(int x, int y) {
      return x - y * (x / y);
    }

    `;
}
exports.getFragShaderPreamble = getFragShaderPreamble;
function getDefaultFragShaderMain(version, outputShapeLength) {
    const glsl = getGlsl(version);
    return `
  void main() {
    int indices[${outputShapeLength}];
    toVec(TexCoords, indices);
    vec4 result = vec4(process(indices));
    ${glsl.output} = result;
  }
  `;
}
exports.getDefaultFragShaderMain = getDefaultFragShaderMain;


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/glsl-vec-lib.ts":
/*!***************************************************!*\
  !*** ./lib/onnxjs/backends/webgl/glsl-vec-lib.ts ***!
  \***************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.VecGlslLib = void 0;
const glsl_definitions_1 = __webpack_require__(/*! ./glsl-definitions */ "./lib/onnxjs/backends/webgl/glsl-definitions.ts");
/**
 * GLSL Library responsible for vec routines
 * Vec is an varible length int array. The length is fixed at the time of
 * generating the library functions from the dimensions of the output.
 */
class VecGlslLib extends glsl_definitions_1.GlslLib {
    constructor(context) {
        super(context);
    }
    getCustomTypes() {
        return {};
    }
    getFunctions() {
        return Object.assign(Object.assign(Object.assign(Object.assign({}, this.binaryVecFunctions()), this.copyVec()), this.setVecItem()), this.getVecItem());
    }
    binaryVecFunctions() {
        const outputLayout = this.context.outputTextureLayout;
        const rank = outputLayout.shape.length;
        const nameOp = { add: '+=', sub: '-=', mul: '*=', div: '/=' };
        const result = {};
        for (const name in nameOp) {
            const fname = `${name}Vec`;
            let assignmentBlock = '';
            for (let i = 0; i < rank; ++i) {
                assignmentBlock += `
          dest[${i}] ${nameOp[name]} src[${i}];
          `;
            }
            const body = `
        void ${fname}(int src[${rank}], out int dest[${rank}]) {
          ${assignmentBlock}
        }
        `;
            result[fname] = new glsl_definitions_1.GlslLibRoutine(body);
        }
        return result;
    }
    copyVec() {
        const outputLayout = this.context.outputTextureLayout;
        const rank = outputLayout.shape.length;
        let assignmentBlock = '';
        for (let i = 0; i < rank; ++i) {
            assignmentBlock += `
        dest[${i}] = src[${i}];
        `;
        }
        const body = `
      void copyVec(int src[${rank}], out int dest[${rank}]) {
        ${assignmentBlock}
      }
      `;
        return { copyVec: new glsl_definitions_1.GlslLibRoutine(body) };
    }
    setVecItem() {
        const outputLayout = this.context.outputTextureLayout;
        const rank = outputLayout.shape.length;
        let block = `
        if(index < 0)
            index =${rank} + index;
        if (index == 0)
            m[0] = value;
        `;
        for (let i = 1; i < rank - 1; ++i) {
            block += `
        else if (index == ${i})
            m[${i}] = value;
            `;
        }
        block += `
        else
            m[${rank - 1}] = value;
        `;
        const body = `
      void setVecItem(out int m[${rank}], int index, int value) {
        ${block}
      }
        `;
        return { setVecItem: new glsl_definitions_1.GlslLibRoutine(body) };
    }
    getVecItem() {
        const outputLayout = this.context.outputTextureLayout;
        const rank = outputLayout.shape.length;
        let block = `
        if(index < 0)
            index = ${rank} + index;
        if (index == 0)
            return m[0];
      `;
        for (let i = 1; i < rank - 1; ++i) {
            block += `
        else if (index == ${i})
            return m[${i}];
      `;
        }
        block += `
        else
            return m[${rank - 1}];
        `;
        const body = `
      int getVecItem(int m[${rank}], int index) {
        ${block}
      }
    `;
        return { getVecItem: new glsl_definitions_1.GlslLibRoutine(body) };
    }
}
exports.VecGlslLib = VecGlslLib;


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/inference-handler.ts":
/*!********************************************************!*\
  !*** ./lib/onnxjs/backends/webgl/inference-handler.ts ***!
  \********************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.WebGLInferenceHandler = void 0;
const instrument_1 = __webpack_require__(/*! ../../instrument */ "./lib/onnxjs/instrument.ts");
const tensor_1 = __webpack_require__(/*! ../../tensor */ "./lib/onnxjs/tensor.ts");
const util_1 = __webpack_require__(/*! ../../util */ "./lib/onnxjs/util.ts");
const pack_1 = __webpack_require__(/*! ./ops/pack */ "./lib/onnxjs/backends/webgl/ops/pack.ts");
const reshape_packed_1 = __webpack_require__(/*! ./ops/reshape-packed */ "./lib/onnxjs/backends/webgl/ops/reshape-packed.ts");
const uint8_encode_1 = __webpack_require__(/*! ./ops/uint8-encode */ "./lib/onnxjs/backends/webgl/ops/uint8-encode.ts");
const unpack_1 = __webpack_require__(/*! ./ops/unpack */ "./lib/onnxjs/backends/webgl/ops/unpack.ts");
const texture_layout_1 = __webpack_require__(/*! ./texture-layout */ "./lib/onnxjs/backends/webgl/texture-layout.ts");
const types_1 = __webpack_require__(/*! ./types */ "./lib/onnxjs/backends/webgl/types.ts");
const getProgramInfoUniqueKey = (programInfo, inputTextureDatas) => {
    const inputs = inputTextureDatas.map(texture => `${texture.unpackedShape.join(',')};${texture.width}x${texture.height}`)
        .join('_');
    let key = programInfo.name;
    if (programInfo.cacheHint) {
        key += '[' + programInfo.cacheHint + ']';
    }
    key += ':' + inputs;
    return key;
};
class WebGLInferenceHandler {
    constructor(session) {
        this.session = session;
        this.packedTextureDataCache = new Map();
        this.unpackedTextureDataCache = new Map();
    }
    /**
     * @returns [width, height]
     */
    calculateTextureWidthAndHeight(shape, textureType) {
        return (0, texture_layout_1.calculateTextureWidthAndHeight)(this.session.layoutStrategy, shape, textureType);
    }
    executeProgram(program, inputs) {
        if (inputs.length < program.inputNames.length) {
            throw new Error(`Input size mustn't be less than ${program.inputNames.length}.`);
        }
        if (program.inputNames.length !== program.inputTypes.length) {
            throw new Error('input names size does not match input types');
        }
        // create texture info for input
        const inputTextureDatas = [];
        for (let i = 0; i < program.inputNames.length; ++i) {
            inputTextureDatas[i] = this.getOrCreateTextureData(inputs[i], program.inputTypes[i]);
        }
        const key = getProgramInfoUniqueKey(program, inputTextureDatas);
        let artifact = this.session.programManager.getArtifact(key);
        const programInfo = artifact ?
            artifact.programInfo :
            (typeof program.get === 'function' ? program.get() :
                program);
        // create texture info for output
        const outputTextureLayout = (0, texture_layout_1.createTextureLayoutFromTextureType)(this.session.layoutStrategy, programInfo.output.dims, programInfo.output.textureType);
        const outputTextureData = this.createTextureData(outputTextureLayout, programInfo.output.type);
        if (!artifact) {
            artifact = this.session.programManager.build(programInfo, inputTextureDatas, outputTextureData);
            this.session.programManager.setArtifact(key, artifact);
        }
        this.runProgram(artifact, inputTextureDatas, outputTextureData);
        return outputTextureData;
    }
    run(program, inputs) {
        const outputTextureData = this.executeProgram(program, inputs);
        return outputTextureData.tensor;
    }
    runProgram(artifact, inputs, output) {
        // input should match
        for (let i = 0; i < inputs.length; ++i) {
            if (!!inputs[i].isPacked !== (artifact.programInfo.inputTypes[i] === types_1.TextureType.packed)) {
                throw new Error(`input[${i}] property packed inconsistent`);
            }
        }
        // output should match
        if (!!output.isPacked !== (artifact.programInfo.output.textureType === types_1.TextureType.packed)) {
            throw new Error('output property packed inconsistent');
        }
        this.session.programManager.run(artifact, inputs, output);
    }
    /**
     * Create a TextureData object from a tensor.
     * Usage = Encoder.Usage.UploadOnly.
     * If a related texture data is found in cache, returns it;
     * Otherwise:
     *   Creates a new texture layout if not provided;
     *   Creates WebGLTexture with the layout;
     *   Upload tensor data to the texture;
     *   Creates a texture data object associated with the given tensor.
     * @param tensor the tensor with data to upload
     */
    getOrCreateTextureData(tensor, textureType) {
        let td = this.getTextureData(tensor.dataId, textureType === types_1.TextureType.packed);
        if (!td) {
            // check if we have texture data in different type
            td = this.getTextureData(tensor.dataId, textureType !== types_1.TextureType.packed);
            if (td) {
                if (textureType === types_1.TextureType.packed) {
                    return this.pack(td);
                }
                else {
                    return this.unpack(td);
                }
            }
        }
        if (!td) {
            const layout = (0, texture_layout_1.createTextureLayoutFromTextureType)(this.session.layoutStrategy, tensor.dims, textureType);
            if (textureType === types_1.TextureType.packedLastDimension) {
                const group = 1;
                const channels = 4;
                const shape = tensor.dims;
                if (shape.length === 4) {
                    // pre-processing for kernel data of Conv.
                    //
                    // TODO: currently this is a hacking to overwrite Conv's weight. The correct way to do this should be:
                    // 1. implement texture based const-folding
                    // 2. create a WebGL program "preprocessConvWeight" to do the same work as below
                    // 3. run the program before dotProduct.
                    //
                    const adjustedKernelShape = [shape[0], Math.ceil((shape[1] * shape[2] * shape[3]) / channels)];
                    const adjustedLayout = (0, texture_layout_1.createTextureLayoutFromTextureType)(this.session.layoutStrategy, adjustedKernelShape, textureType);
                    let buffer = tensor.numberData;
                    if (shape[1] * shape[2] * shape[3] % channels !== 0) {
                        const numFeatureMaps = shape[0];
                        const oldRowSize = shape[1] * shape[2] * shape[3];
                        const newRowSize = Math.ceil(oldRowSize * group / channels) * channels;
                        const newSize = numFeatureMaps * newRowSize;
                        buffer = new Float32Array(newSize);
                        for (let f = 0; f < numFeatureMaps; ++f) {
                            const oldOffset = f * oldRowSize;
                            const newOffset = f * newRowSize + f % group * oldRowSize;
                            buffer.set(tensor.numberData.subarray(oldOffset, oldOffset + oldRowSize), newOffset);
                        }
                    }
                    return this.createTextureData(adjustedLayout, tensor.type, buffer, tensor, 1 /* Encoder.Usage.UploadOnly */);
                }
            }
            if (textureType === types_1.TextureType.packed) {
                const unpackedTextureLayout = (0, texture_layout_1.createTextureLayoutFromShape)(this.session.layoutStrategy, tensor.dims, 1, [], { reverseWH: true });
                const unpackedTextureData = this.createTextureData(unpackedTextureLayout, tensor.type, tensor.numberData, tensor, 1 /* Encoder.Usage.UploadOnly */);
                td = this.pack(unpackedTextureData);
            }
            else {
                td = this.createTextureData(layout, tensor.type, tensor.numberData, tensor, 1 /* Encoder.Usage.UploadOnly */);
            }
        }
        return td;
    }
    /**
     * Create a TextureData object using the given data and bind to the given tensor.
     * Usage = Encoder.Usage.UploadOnly.
     * NOTE: this function is a hack for Conv implementation. should remove this function, after rewriting Conv
     * implementation by Graph.Transformer
     * @param dataType the tensor data type
     * @param data the actual data to upload
     * @param tensor the tensor to bind. tensor's data is ignored.
     */
    createTextureDataFromLayoutBindTensor(layout, dataType, data, tensor) {
        return this.createTextureData(layout, dataType, data, tensor, 1 /* Encoder.Usage.UploadOnly */);
    }
    createTextureData(layout, dataType, data, tensor, usage) {
        instrument_1.Logger.verbose('InferenceHandler', `Creating TextureData: layout:[${JSON.stringify(layout)}]`);
        const texture = this.session.textureManager.createTextureFromLayout(dataType, layout, data, usage);
        return this.createTextureDataFromTexture(layout, dataType, texture, tensor);
    }
    reshapeUnpacked(input, reshapedDims) {
        const inputTD = this.getOrCreateTextureData(input, types_1.TextureType.unpacked);
        const newTextureLayout = {
            channels: inputTD.channels,
            height: inputTD.height,
            width: inputTD.width,
            // handle reshaping into scalar Tensors
            shape: reshapedDims.length !== 0 ? reshapedDims : [1],
            strides: util_1.ShapeUtil.computeStrides(reshapedDims),
            unpackedShape: reshapedDims,
        };
        const newTextureData = this.createTextureDataFromTexture(newTextureLayout, input.type, inputTD.texture);
        return newTextureData.tensor;
    }
    reshapePacked(input, reshapedDims) {
        const inputTD = this.getOrCreateTextureData(input, types_1.TextureType.packed);
        // check if the reshape is 'cheap'
        if ((0, reshape_packed_1.isReshapeCheap)(input.dims, reshapedDims)) {
            const newTextureLayout = {
                channels: inputTD.channels,
                height: inputTD.height,
                width: inputTD.width,
                // handle reshaping into scalar Tensors
                shape: reshapedDims.length !== 0 ? reshapedDims : [1],
                strides: util_1.ShapeUtil.computeStrides(reshapedDims),
                unpackedShape: reshapedDims,
                isPacked: true
            };
            const newTextureData = this.createTextureDataFromTexture(newTextureLayout, input.type, inputTD.texture);
            return newTextureData.tensor;
        }
        const squeezedInputShape = (0, reshape_packed_1.processDims3D)(input.dims);
        const squeezedOutputShape = (0, reshape_packed_1.processDims3D)(reshapedDims);
        const squeezedInputTensor = this.reshapePacked(input, squeezedInputShape);
        const squeezedOutputTensor = this.run((0, reshape_packed_1.createPackedReshape3DProgramInfoLoader)(this, squeezedInputTensor, squeezedOutputShape), [squeezedInputTensor]);
        const outputTensor = this.reshapePacked(squeezedOutputTensor, reshapedDims);
        return outputTensor;
    }
    cast(input, type) {
        const inputTD = this.getOrCreateTextureData(input, types_1.TextureType.unpacked);
        const newTextureData = this.createTextureDataFromTexture(inputTD, type, inputTD.texture);
        return newTextureData.tensor;
    }
    createTextureDataFromTexture(layout, dataType, texture, tensor, tensorId) {
        const textureData = Object.assign(Object.assign({}, layout), { tensor: tensor ||
                new tensor_1.Tensor(layout.unpackedShape, dataType, (_id) => this.readTexture(textureData), async (_id) => this.readTextureAsync(textureData), undefined, tensorId), texture });
        this.setTextureData(textureData.tensor.dataId, textureData, layout.isPacked);
        return textureData;
    }
    getTextureData(tensorId, isPacked = false) {
        return this.session.isInitializer(tensorId) ? this.session.getTextureData(tensorId, isPacked) :
            isPacked ? this.packedTextureDataCache.get(tensorId) :
                this.unpackedTextureDataCache.get(tensorId);
    }
    setTextureData(tensorId, td, isPacked = false) {
        if (this.session.isInitializer(tensorId)) {
            this.session.setTextureData(tensorId, td, isPacked);
        }
        else {
            (isPacked ? this.packedTextureDataCache : this.unpackedTextureDataCache).set(tensorId, td);
        }
    }
    isTextureLayoutCached(tensor, isPacked = false) {
        return !!this.getTextureData(tensor.dataId, isPacked);
    }
    dispose() {
        this.session.textureManager.clearActiveTextures();
        this.packedTextureDataCache.forEach(td => this.session.textureManager.releaseTexture(td));
        this.packedTextureDataCache = new Map();
        this.unpackedTextureDataCache.forEach(td => this.session.textureManager.releaseTexture(td));
        this.unpackedTextureDataCache = new Map();
    }
    readTexture(textureData) {
        if (textureData.isPacked) {
            return this.readTexture(this.unpack(textureData));
        }
        if (!this.session.backend.glContext.isFloat32DownloadSupported) {
            return this.session.textureManager.readUint8TextureAsFloat((0, uint8_encode_1.encodeAsUint8)(this, textureData));
        }
        return this.session.textureManager.readTexture(textureData, textureData.tensor.type, textureData.channels);
    }
    async readTextureAsync(textureData) {
        if (textureData.isPacked) {
            return this.readTextureAsync(this.unpack(textureData));
        }
        if (!this.session.backend.glContext.isFloat32DownloadSupported) {
            return this.session.textureManager.readUint8TextureAsFloat((0, uint8_encode_1.encodeAsUint8)(this, textureData));
        }
        return this.session.textureManager.readTextureAsync(textureData, textureData.tensor.type, textureData.channels);
    }
    pack(input) {
        const outputTextureData = this.executeProgram((0, pack_1.createPackProgramInfoLoader)(this, input.tensor), [input.tensor]);
        return outputTextureData;
    }
    unpack(input) {
        const outputTextureData = this.executeProgram((0, unpack_1.createUnpackProgramInfoLoader)(this, input.tensor), [input.tensor]);
        return outputTextureData;
    }
}
exports.WebGLInferenceHandler = WebGLInferenceHandler;


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/op-resolve-rules.ts":
/*!*******************************************************!*\
  !*** ./lib/onnxjs/backends/webgl/op-resolve-rules.ts ***!
  \*******************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.WEBGL_OP_RESOLVE_RULES = void 0;
const batch_normalization_1 = __webpack_require__(/*! ./ops/batch-normalization */ "./lib/onnxjs/backends/webgl/ops/batch-normalization.ts");
const binaryOps = __importStar(__webpack_require__(/*! ./ops/binary-op */ "./lib/onnxjs/backends/webgl/ops/binary-op.ts"));
const cast_1 = __webpack_require__(/*! ./ops/cast */ "./lib/onnxjs/backends/webgl/ops/cast.ts");
const concat_1 = __webpack_require__(/*! ./ops/concat */ "./lib/onnxjs/backends/webgl/ops/concat.ts");
const conv_1 = __webpack_require__(/*! ./ops/conv */ "./lib/onnxjs/backends/webgl/ops/conv.ts");
const conv_transpose_1 = __webpack_require__(/*! ./ops/conv-transpose */ "./lib/onnxjs/backends/webgl/ops/conv-transpose.ts");
const depth_to_space_1 = __webpack_require__(/*! ./ops/depth-to-space */ "./lib/onnxjs/backends/webgl/ops/depth-to-space.ts");
const flatten_1 = __webpack_require__(/*! ./ops/flatten */ "./lib/onnxjs/backends/webgl/ops/flatten.ts");
const gather_1 = __webpack_require__(/*! ./ops/gather */ "./lib/onnxjs/backends/webgl/ops/gather.ts");
const gemm_1 = __webpack_require__(/*! ./ops/gemm */ "./lib/onnxjs/backends/webgl/ops/gemm.ts");
const image_scaler_1 = __webpack_require__(/*! ./ops/image-scaler */ "./lib/onnxjs/backends/webgl/ops/image-scaler.ts");
const instance_normalization_1 = __webpack_require__(/*! ./ops/instance-normalization */ "./lib/onnxjs/backends/webgl/ops/instance-normalization.ts");
const matmul_1 = __webpack_require__(/*! ./ops/matmul */ "./lib/onnxjs/backends/webgl/ops/matmul.ts");
const pad_1 = __webpack_require__(/*! ./ops/pad */ "./lib/onnxjs/backends/webgl/ops/pad.ts");
const pool_1 = __webpack_require__(/*! ./ops/pool */ "./lib/onnxjs/backends/webgl/ops/pool.ts");
const reduce_1 = __webpack_require__(/*! ./ops/reduce */ "./lib/onnxjs/backends/webgl/ops/reduce.ts");
const reshape_1 = __webpack_require__(/*! ./ops/reshape */ "./lib/onnxjs/backends/webgl/ops/reshape.ts");
const resize_packed_1 = __webpack_require__(/*! ./ops/resize-packed */ "./lib/onnxjs/backends/webgl/ops/resize-packed.ts");
const shape_1 = __webpack_require__(/*! ./ops/shape */ "./lib/onnxjs/backends/webgl/ops/shape.ts");
const slice_1 = __webpack_require__(/*! ./ops/slice */ "./lib/onnxjs/backends/webgl/ops/slice.ts");
const softmax_1 = __webpack_require__(/*! ./ops/softmax */ "./lib/onnxjs/backends/webgl/ops/softmax.ts");
const split_1 = __webpack_require__(/*! ./ops/split */ "./lib/onnxjs/backends/webgl/ops/split.ts");
const squeeze_1 = __webpack_require__(/*! ./ops/squeeze */ "./lib/onnxjs/backends/webgl/ops/squeeze.ts");
const sum_1 = __webpack_require__(/*! ./ops/sum */ "./lib/onnxjs/backends/webgl/ops/sum.ts");
const tile_1 = __webpack_require__(/*! ./ops/tile */ "./lib/onnxjs/backends/webgl/ops/tile.ts");
const transpose_1 = __webpack_require__(/*! ./ops/transpose */ "./lib/onnxjs/backends/webgl/ops/transpose.ts");
const unaryOps = __importStar(__webpack_require__(/*! ./ops/unary-op */ "./lib/onnxjs/backends/webgl/ops/unary-op.ts"));
const unsqueeze_1 = __webpack_require__(/*! ./ops/unsqueeze */ "./lib/onnxjs/backends/webgl/ops/unsqueeze.ts");
const upsample_1 = __webpack_require__(/*! ./ops/upsample */ "./lib/onnxjs/backends/webgl/ops/upsample.ts");
exports.WEBGL_OP_RESOLVE_RULES = [
    ['Abs', '', '6+', unaryOps.abs],
    ['Acos', '', '7+', unaryOps.acos],
    ['Add', '', '7+', binaryOps.add],
    ['And', '', '7+', binaryOps.and],
    ['Asin', '', '7+', unaryOps.asin],
    ['Atan', '', '7+', unaryOps.atan],
    // TODO: support new attributes for AveragePool-10
    ['AveragePool', '', '7+', pool_1.averagePool, pool_1.parseAveragePoolAttributes],
    ['BatchNormalization', '', '7+', batch_normalization_1.batchNormalization, batch_normalization_1.parseBatchNormalizationAttributes],
    ['Cast', '', '6+', cast_1.cast, cast_1.parseCastAttributes],
    ['Ceil', '', '6+', unaryOps.ceil],
    ['Clip', '', '6-10', unaryOps.clip, unaryOps.parseClipAttributes],
    ['Clip', '', '11+', unaryOps.clipV11],
    ['Concat', '', '4+', concat_1.concat, concat_1.parseConcatAttributes],
    ['Conv', '', '1+', conv_1.conv, conv_1.parseConvAttributes],
    ['ConvTranspose', '', '1+', conv_transpose_1.convTranspose, conv_transpose_1.parseConvTransposeAttributes],
    ['Cos', '', '7+', unaryOps.cos],
    ['Div', '', '7+', binaryOps.div],
    ['Dropout', '', '7+', unaryOps.identity],
    ['DepthToSpace', '', '1+', depth_to_space_1.depthToSpace, depth_to_space_1.parseDepthToSpaceAttributes],
    ['Equal', '', '7+', binaryOps.equal],
    ['Elu', '', '6+', unaryOps.elu, unaryOps.parseEluAttributes],
    ['Exp', '', '6+', unaryOps.exp],
    ['Flatten', '', '1+', flatten_1.flatten, flatten_1.parseFlattenAttributes],
    ['Floor', '', '6+', unaryOps.floor],
    ['FusedConv', 'com.microsoft', '1+', conv_1.conv, conv_1.parseConvAttributes],
    ['Gather', '', '1+', gather_1.gather, gather_1.parseGatherAttributes],
    ['Gemm', '', '7-10', gemm_1.gemm, gemm_1.parseGemmAttributesV7],
    ['Gemm', '', '11+', gemm_1.gemm, gemm_1.parseGemmAttributesV11],
    ['GlobalAveragePool', '', '1+', pool_1.globalAveragePool, pool_1.parseGlobalAveragePoolAttributes],
    ['GlobalMaxPool', '', '1+', pool_1.globalMaxPool],
    ['Greater', '', '7+', binaryOps.greater],
    ['Identity', '', '1+', unaryOps.identity],
    ['ImageScaler', '', '1+', image_scaler_1.imageScaler, image_scaler_1.parseImageScalerAttributes],
    ['InstanceNormalization', '', '6+', instance_normalization_1.instanceNormalization, instance_normalization_1.parseInstanceNormalizationAttributes],
    ['LeakyRelu', '', '6+', unaryOps.leakyRelu, unaryOps.parseLeakyReluAttributes],
    ['Less', '', '7+', binaryOps.less],
    ['Log', '', '6+', unaryOps.log],
    ['MatMul', '', '1+', matmul_1.matMul, matmul_1.parseMatMulAttributes],
    // TODO: support new attributes for MaxPool-8 and MaxPool-10
    ['MaxPool', '', '1+', pool_1.maxPool, pool_1.parseMaxPoolAttributes],
    ['Mul', '', '7+', binaryOps.mul],
    ['Neg', '', '6+', unaryOps.neg],
    ['Not', '', '1+', unaryOps.not],
    ['Or', '', '7+', binaryOps.or],
    ['Pad', '', '2-10', pad_1.padV2, pad_1.parsePadAttributesV2],
    ['Pad', '', '11+', pad_1.padV11, pad_1.parsePadAttributesV11],
    ['Pow', '', '7+', binaryOps.pow],
    ['PRelu', '', '7+', binaryOps.pRelu],
    ['ReduceLogSum', '', '1+', reduce_1.reduceLogSum, reduce_1.parseReduceAttributes],
    ['ReduceMax', '', '1+', reduce_1.reduceMax, reduce_1.parseReduceAttributes],
    ['ReduceMean', '', '1+', reduce_1.reduceMean, reduce_1.parseReduceAttributes],
    ['ReduceMin', '', '1+', reduce_1.reduceMin, reduce_1.parseReduceAttributes],
    ['ReduceProd', '', '1+', reduce_1.reduceProd, reduce_1.parseReduceAttributes],
    ['ReduceSum', '', '1-12', reduce_1.reduceSum, reduce_1.parseReduceAttributes],
    ['ReduceSumSquare', '', '1+', reduce_1.reduceLogSumSquare, reduce_1.parseReduceAttributes],
    ['Relu', '', '6+', unaryOps.relu],
    ['Reshape', '', '5+', reshape_1.reshape],
    ['Resize', '', '10', resize_packed_1.resize, resize_packed_1.parseResizeAttributesV10],
    ['Resize', '', '11+', resize_packed_1.resize, resize_packed_1.parseResizeAttributesV11],
    ['Shape', '', '1+', shape_1.shape],
    ['Sigmoid', '', '6+', unaryOps.sigmoid],
    ['Sin', '', '7+', unaryOps.sin],
    ['Slice', '', '10+', slice_1.sliceV10],
    ['Slice', '', '1-9', slice_1.slice, slice_1.parseSliceAttributes],
    // The "semantic" meaning of axis has changed in opset-13.
    ['Softmax', '', '1-12', softmax_1.softmax, softmax_1.parseSoftmaxAttributes],
    ['Softmax', '', '13+', softmax_1.softmaxV13, softmax_1.parseSoftmaxAttributesV13],
    // 'Split' operator has an optional attribute 'split'
    // this attribute determines how the specified axis of input data is split.
    // When the attribute is missing, we need the count of number of outputs
    // so that we can determine the 'split' attribute from the runtime input to the Operator
    ['Split', '', '2-12', split_1.split, split_1.parseSplitAttributes],
    ['Sqrt', '', '6+', unaryOps.sqrt],
    ['Squeeze', '', '1-12', squeeze_1.squeeze, squeeze_1.parseSqueezeAttributes],
    ['Squeeze', '', '13+', squeeze_1.squeezeV13],
    ['Sub', '', '7+', binaryOps.sub],
    ['Sum', '', '6+', sum_1.sum],
    ['Tan', '', '7+', unaryOps.tan],
    ['Tanh', '', '6+', unaryOps.tanh],
    ['Tile', '', '6+', tile_1.tile],
    ['Transpose', '', '1+', transpose_1.transpose, transpose_1.parseTransposeAttributes],
    ['Upsample', '', '7-8', upsample_1.upsample, upsample_1.parseUpsampleAttributesV7],
    ['Upsample', '', '9', upsample_1.upsample, upsample_1.parseUpsampleAttributesV9],
    ['Unsqueeze', '', '1-12', unsqueeze_1.unsqueeze, unsqueeze_1.parseUnsqueezeAttributes],
    ['Unsqueeze', '', '13+', unsqueeze_1.unsqueezeV13],
    ['Xor', '', '7+', binaryOps.xor],
];


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/ops/batch-normalization.ts":
/*!**************************************************************!*\
  !*** ./lib/onnxjs/backends/webgl/ops/batch-normalization.ts ***!
  \**************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.parseBatchNormalizationAttributes = exports.batchNormalization = void 0;
const attribute_with_cache_key_1 = __webpack_require__(/*! ../../../attribute-with-cache-key */ "./lib/onnxjs/attribute-with-cache-key.ts");
const glsl_source_1 = __webpack_require__(/*! ../glsl-source */ "./lib/onnxjs/backends/webgl/glsl-source.ts");
const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
const batchNormalizationProgramMetadata = {
    name: 'BatchNormalization',
    inputNames: ['A', 'Scale', 'B', 'Mean', 'Variance'],
    inputTypes: [types_1.TextureType.unpacked, types_1.TextureType.unpacked, types_1.TextureType.unpacked, types_1.TextureType.unpacked, types_1.TextureType.unpacked]
};
const batchNormalization = (inferenceHandler, inputs, attributes) => {
    validateInputs(inputs);
    const output = inferenceHandler.run(Object.assign(Object.assign({}, batchNormalizationProgramMetadata), { cacheHint: attributes.cacheKey, get: () => createBatchNormalizationProgramInfo(inferenceHandler, inputs, attributes) }), inputs);
    return [output];
};
exports.batchNormalization = batchNormalization;
const parseBatchNormalizationAttributes = (node) => {
    const epsilon = node.attributes.getFloat('epsilon', 1e-5);
    const momentum = node.attributes.getFloat('momentum', 0.9);
    const spatial = node.attributes.getInt('spatial', 1);
    return (0, attribute_with_cache_key_1.createAttributeWithCacheKey)({ epsilon, momentum, spatial });
};
exports.parseBatchNormalizationAttributes = parseBatchNormalizationAttributes;
const createBatchNormalizationProgramInfo = (inferenceHandler, inputs, attributes) => {
    const glsl = (0, glsl_source_1.getGlsl)(inferenceHandler.session.backend.glContext.version);
    const rank = inputs[0].dims.length;
    const [scaleWidth, scaleHeight] = inferenceHandler.calculateTextureWidthAndHeight(inputs[1].dims, types_1.TextureType.unpacked);
    const shaderSource = `
  float process(int[${rank}] indices) {
    vec2 position = offsetToCoords(indices[1], ${scaleWidth}, ${scaleHeight});
    float scale = getColorAsFloat(${glsl.texture2D}(Scale, position));
    float mean = getColorAsFloat(${glsl.texture2D}(Mean, position));
    float variance = getColorAsFloat(${glsl.texture2D}(Variance, position));
    float b = getColorAsFloat(${glsl.texture2D}(B, position));

    return scale * ( (_A(indices) - mean) / sqrt(variance + float(${attributes.epsilon})) ) + b;
  }`;
    return Object.assign(Object.assign({}, batchNormalizationProgramMetadata), { output: { dims: inputs[0].dims, type: inputs[0].type, textureType: types_1.TextureType.unpacked }, shaderSource });
};
const validateInputs = (inputs) => {
    if (!inputs || inputs.length !== 5) {
        throw new Error('BatchNormalization requires 5 inputs.');
    }
    const X = inputs[0];
    const scale = inputs[1];
    const B = inputs[2];
    const mean = inputs[3];
    const var_ = inputs[4];
    // input should atleast have three dimensions - N,C,dim1,...,dimn
    // other inputs can have only one dimensions
    if (X.dims.length < 3 || scale.dims.length !== 1 || B.dims.length !== 1 || mean.dims.length !== 1 ||
        var_.dims.length !== 1) {
        throw new Error('invalid input shape.');
    }
    if (scale.dims[0] !== X.dims[1] || B.dims[0] !== X.dims[1] || mean.dims[0] !== X.dims[1] ||
        var_.dims[0] !== X.dims[1]) {
        throw new Error('invalid input shape.');
    }
    if ((X.type !== 'float32' && X.type !== 'float64') || (scale.type !== 'float32' && scale.type !== 'float64') ||
        (B.type !== 'float32' && B.type !== 'float64') || (mean.type !== 'float32' && mean.type !== 'float64') ||
        (var_.type !== 'float32' && var_.type !== 'float64')) {
        throw new Error('invalid input tensor types.');
    }
};


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/ops/binary-op.ts":
/*!****************************************************!*\
  !*** ./lib/onnxjs/backends/webgl/ops/binary-op.ts ***!
  \****************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.xor = exports.sub = exports.pRelu = exports.pow = exports.or = exports.mul = exports.less = exports.greater = exports.equal = exports.div = exports.and = exports.add = exports.glslPRelu = exports.glslPow = exports.glslXor = exports.glslOr = exports.glslAnd = exports.glslLess = exports.glslGreater = exports.glslEqual = exports.glslSub = exports.glslMul = exports.glslDiv = exports.glslAdd = void 0;
const util_1 = __webpack_require__(/*! ../../../util */ "./lib/onnxjs/util.ts");
const glsl_definitions_1 = __webpack_require__(/*! ../glsl-definitions */ "./lib/onnxjs/backends/webgl/glsl-definitions.ts");
const glsl_source_1 = __webpack_require__(/*! ../glsl-source */ "./lib/onnxjs/backends/webgl/glsl-source.ts");
const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
function glslAdd() {
    const name = 'add_';
    const body = `
  float ${name}(float a, float b) {
    return a + b;
  }
  vec4 ${name}(vec4 v1, vec4 v2) {
    return v1 + v2;
  }
  `;
    return { body, name, type: glsl_definitions_1.FunctionType.ValueBased };
}
exports.glslAdd = glslAdd;
function glslDiv() {
    const name = 'div_';
    const body = `
  float ${name}(float a, float b) {
    return a / b;
  }
  vec4 ${name}(vec4 v1, vec4 v2) {
    return v1 / v2;
  }
  `;
    return { body, name, type: glsl_definitions_1.FunctionType.ValueBased };
}
exports.glslDiv = glslDiv;
function glslMul() {
    const name = 'mul_';
    const body = `
  float ${name}(float a, float b) {
    return a * b;
  }
  vec4 ${name}(vec4 v1, vec4 v2) {
    return v1 * v2;
  }
  `;
    return { body, name, type: glsl_definitions_1.FunctionType.ValueBased };
}
exports.glslMul = glslMul;
function glslSub() {
    const name = 'sub_';
    const body = `
  float ${name}(float a, float b) {
    return a - b;
  }
  vec4 ${name}(vec4 v1, vec4 v2) {
    return v1 - v2;
  }
  `;
    return { body, name, type: glsl_definitions_1.FunctionType.ValueBased };
}
exports.glslSub = glslSub;
function glslEqual() {
    const name = 'equal_';
    const body = `
  float ${name}(float a, float b) {
    return float(a == b);
  }
  vec4 ${name}(vec4 v1, vec4 v2) {
    return vec4(equal(v1, v2));
  }
  `;
    return { body, name, type: glsl_definitions_1.FunctionType.ValueBased };
}
exports.glslEqual = glslEqual;
function glslGreater() {
    const name = 'greater_';
    const body = `
  float ${name}(float a, float b) {
    return float(a > b);
  }
  vec4 ${name}(vec4 v1, vec4 v2) {
    return vec4( v1.r > v2.r ,
      v1.g > v2.g,
      v1.b > v2.b,
      v1.a > v2.a );
  }
  `;
    return { body, name, type: glsl_definitions_1.FunctionType.ValueBased };
}
exports.glslGreater = glslGreater;
function glslLess() {
    const name = 'less_';
    const body = `
  float ${name}(float a, float b) {
    return float(a < b);
  }
  vec4 ${name}(vec4 v1, vec4 v2) {
    return vec4( v1.r < v2.r ,
                v1.g < v2.g,
                v1.b < v2.b,
                v1.a < v2.a );
  }
  `;
    return { body, name, type: glsl_definitions_1.FunctionType.ValueBased };
}
exports.glslLess = glslLess;
function glslAnd() {
    const name = 'and_';
    const body = `
  float ${name}(float a, float b) {
    return float( bool(a) && bool(b) );
  }
  vec4 ${name}(vec4 v1, vec4 v2) {
    bvec4 b1 = bvec4(v1);
    bvec4 b2 = bvec4(v2);
    return vec4( b1.r && b2.r ,
                b1.g && b2.g,
                b1.b && b2.b,
                b1.a && b2.a );
  }
  `;
    return { body, name, type: glsl_definitions_1.FunctionType.ValueBased };
}
exports.glslAnd = glslAnd;
function glslOr() {
    const name = 'or_';
    const body = `
  float ${name}(float a, float b) {
    return float( bool(a) || bool(b) );
  }
  vec4 ${name}(vec4 v1, vec4 v2) {
    bvec4 b1 = bvec4(v1);
    bvec4 b2 = bvec4(v2);
    return vec4( b1.r || b2.r ,
                b1.g || b2.g,
                b1.b || b2.b,
                b1.a || b2.a );
  }
  `;
    return { body, name, type: glsl_definitions_1.FunctionType.ValueBased };
}
exports.glslOr = glslOr;
function glslXor() {
    const name = 'xor_';
    const body = `
  float ${name}(float a, float b) {
    return float( bool(a) ^^ bool(b) );
  }
  vec4 ${name}(vec4 v1, vec4 v2) {
    bvec4 b1 = bvec4(v1);
    bvec4 b2 = bvec4(v2);
    return vec4( b1.r ^^ b2.r ,
                b1.g ^^ b2.g,
                b1.b ^^ b2.b,
                b1.a ^^ b2.a );
  }
  `;
    return { body, name, type: glsl_definitions_1.FunctionType.ValueBased };
}
exports.glslXor = glslXor;
function glslPow() {
    return glslBuiltinBinary('pow');
}
exports.glslPow = glslPow;
function glslPRelu() {
    const name = 'prelu_';
    const body = `
  float ${name}(float a, float b) {
    return a < 0.0 ? a * b: a;
  }
  vec4 ${name}(vec4 v1, vec4 v2) {
    return vec4(
      v1.r < 0.0 ? v1.r * v2.r: v1.r,
      v1.g < 0.0 ? v1.g * v2.g: v1.g,
      v1.b < 0.0 ? v1.b * v2.b: v1.b,
      v1.a < 0.0 ? v1.a * v2.a: v1.a
      );
  }
  `;
    return { body, name, type: glsl_definitions_1.FunctionType.ValueBased };
}
exports.glslPRelu = glslPRelu;
function glslBuiltinBinary(fname) {
    const name = `${fname}_`;
    const body = `
  float ${name}(float a, float b) {
    return ${fname}(a, b);
  }
  vec4 ${name}(vec4 v1, vec4 v2) {
    return ${fname}(v1, v2);
  }
  `;
    return { body, name, type: glsl_definitions_1.FunctionType.ValueBased };
}
const createBinaryProgramInfoLoader = (handler, inputs, glslFunc, outputTensorType = inputs[0].type, cacheKey) => {
    const textureType = handler.session.pack ? types_1.TextureType.packed : types_1.TextureType.unpacked;
    return {
        name: glslFunc.name,
        inputNames: ['A', 'B'],
        inputTypes: [textureType, textureType],
        cacheHint: cacheKey,
        get: () => createBinaryProgramInfo(handler, inputs, glslFunc, outputTensorType)
    };
};
const createBinaryProgramInfo = (handler, inputs, glslFunc, outputTensorType = inputs[0].type) => {
    const textureType = handler.session.pack ? types_1.TextureType.packed : types_1.TextureType.unpacked;
    const isBroadcast = !util_1.ShapeUtil.areEqual(inputs[0].dims, inputs[1].dims);
    let outputShape = inputs[0].dims;
    const usePackedTexture = handler.session.pack;
    if (isBroadcast) {
        const calculatedShape = util_1.BroadcastUtil.calcShape(inputs[0].dims, inputs[1].dims, false);
        if (!calculatedShape) {
            throw new Error('Can\'t perform binary op on the given tensors');
        }
        outputShape = calculatedShape;
        const outputRank = outputShape.length;
        const aRank = inputs[0].dims.length !== 0 ? inputs[0].dims.length : 1;
        const bRank = inputs[1].dims.length !== 0 ? inputs[1].dims.length : 1;
        const aBcast = inputs[0].dims.length !== 0 ? 'bcastIndices_A(indices, aindices);' : 'aindices[0] = 0;';
        const bBcast = inputs[1].dims.length !== 0 ? 'bcastIndices_B(indices, bindices);' : 'bindices[0] = 0;';
        const glsl = (0, glsl_source_1.getGlsl)(handler.session.backend.glContext.version);
        const shaderSource = usePackedTexture ? `
      ${glslFunc.body}
      void main() {
        vec4 a = getAAtOutCoords();
        vec4 b = getBAtOutCoords();
        vec4 result = ${glslFunc.name}(a, b);
        ${glsl.output} = result;
      }` :
            `
      ${glslFunc.body}
      float process(int indices[${outputRank}]) {
        int aindices[${aRank}];
        int bindices[${bRank}];
        ${aBcast}
        ${bBcast}
        return ${glslFunc.name}(_A(aindices), _B(bindices));
      }`;
        return {
            name: glslFunc.name,
            inputNames: ['A', 'B'],
            inputTypes: [textureType, textureType],
            output: { dims: outputShape, type: outputTensorType, textureType },
            shaderSource,
            hasMain: usePackedTexture
        };
    }
    const glsl = (0, glsl_source_1.getGlsl)(handler.session.backend.glContext.version);
    const shaderSource = `
    ${glslFunc.body}
    void main() {
      vec4 v1 = ${glsl.texture2D}(A, TexCoords);
      vec4 v2 = ${glsl.texture2D}(B, TexCoords);
      vec4 result = ${glslFunc.name}(v1, v2);
      ${glsl.output} = result;
    }
    `;
    return {
        name: glslFunc.name,
        inputNames: ['A', 'B'],
        inputTypes: [textureType, textureType],
        output: { dims: inputs[0].dims, type: outputTensorType, textureType },
        shaderSource,
        hasMain: true
    };
};
const add = (handler, inputs) => [handler.run(createBinaryProgramInfoLoader(handler, inputs, glslAdd()), inputs)];
exports.add = add;
const and = (handler, inputs) => [handler.run(createBinaryProgramInfoLoader(handler, inputs, glslAnd(), 'bool'), inputs)];
exports.and = and;
const div = (handler, inputs) => [handler.run(createBinaryProgramInfoLoader(handler, inputs, glslDiv()), inputs)];
exports.div = div;
const equal = (handler, inputs) => [handler.run(createBinaryProgramInfoLoader(handler, inputs, glslEqual(), 'bool'), inputs)];
exports.equal = equal;
const greater = (handler, inputs) => [handler.run(createBinaryProgramInfoLoader(handler, inputs, glslGreater(), 'bool'), inputs)];
exports.greater = greater;
const less = (handler, inputs) => [handler.run(createBinaryProgramInfoLoader(handler, inputs, glslLess(), 'bool'), inputs)];
exports.less = less;
const mul = (handler, inputs) => [handler.run(createBinaryProgramInfoLoader(handler, inputs, glslMul()), inputs)];
exports.mul = mul;
const or = (handler, inputs) => [handler.run(createBinaryProgramInfoLoader(handler, inputs, glslOr(), 'bool'), inputs)];
exports.or = or;
const pow = (handler, inputs) => [handler.run(createBinaryProgramInfoLoader(handler, inputs, glslPow()), inputs)];
exports.pow = pow;
const pRelu = (handler, inputs) => [handler.run(createBinaryProgramInfoLoader(handler, inputs, glslPRelu()), inputs)];
exports.pRelu = pRelu;
const sub = (handler, inputs) => [handler.run(createBinaryProgramInfoLoader(handler, inputs, glslSub()), inputs)];
exports.sub = sub;
const xor = (handler, inputs) => [handler.run(createBinaryProgramInfoLoader(handler, inputs, glslXor(), 'bool'), inputs)];
exports.xor = xor;


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/ops/cast.ts":
/*!***********************************************!*\
  !*** ./lib/onnxjs/backends/webgl/ops/cast.ts ***!
  \***********************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.parseCastAttributes = exports.cast = void 0;
const util_1 = __webpack_require__(/*! ../../../util */ "./lib/onnxjs/util.ts");
const cast = (handler, inputs, to) => {
    validateInputs(inputs);
    return [handler.cast(inputs[0], to)];
};
exports.cast = cast;
const parseCastAttributes = (node) => util_1.ProtoUtil.tensorDataTypeFromProto(node.attributes.getInt('to'));
exports.parseCastAttributes = parseCastAttributes;
const validateInputs = (inputs) => {
    if (!inputs || inputs.length !== 1) {
        throw new Error('Cast requires 1 input.');
    }
    if (inputs[0].type === 'string') {
        throw new Error('Invalid input type.');
    }
};


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/ops/concat-packed.ts":
/*!********************************************************!*\
  !*** ./lib/onnxjs/backends/webgl/ops/concat-packed.ts ***!
  \********************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.createPackedConcatProgramInfoLoader = void 0;
const glsl_source_1 = __webpack_require__(/*! ../glsl-source */ "./lib/onnxjs/backends/webgl/glsl-source.ts");
const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
const utils_1 = __webpack_require__(/*! ../utils */ "./lib/onnxjs/backends/webgl/utils.ts");
const packing_utils_1 = __webpack_require__(/*! ./packing-utils */ "./lib/onnxjs/backends/webgl/ops/packing-utils.ts");
const createPackedConcatProgramMetadata = (inputCount, cacheHint) => ({
    name: 'Concat (packed)',
    inputNames: Array.from({ length: inputCount }, (v, i) => `X${i}`),
    inputTypes: Array(inputCount).fill(types_1.TextureType.packed),
    cacheHint
});
const createPackedConcatProgramInfo = (handler, metadata, inputs, axis) => {
    const inputShape = inputs[0].dims.slice();
    if (axis >= inputShape.length || axis < (-1 * inputShape.length)) {
        throw new Error('axis specified for concat doesn\'t match input dimensionality');
    }
    if (axis < 0) {
        axis = inputShape.length + axis;
    }
    // ensure all of the non-concatenated axes match each other
    // calculate the shape of the output tensor while we do that
    const outputShape = inputShape.slice(0);
    for (let i = 1; i < inputs.length; i++) {
        const dataNShape = inputs[i].dims.slice();
        for (let axisIndex = 0; axisIndex < inputShape.length; axisIndex++) {
            // add to the placeholder for computing output shape
            if (axisIndex === axis) {
                outputShape[axis] += dataNShape[axisIndex];
            }
            // ensure all non-cancatenated axes match each other
            else if (inputShape[axisIndex] !== dataNShape[axisIndex]) {
                throw new Error('non concat dimensions must match');
            }
        }
    }
    const rank = outputShape.length;
    const coords = (0, packing_utils_1.getChannels)('coords', rank);
    const dtype = (0, utils_1.getCoordsDataType)(rank);
    const unpackChannel = (0, packing_utils_1.unpackFromChannel)();
    const shapes = inputs.map(i => i.dims);
    const channels = (0, utils_1.getGlChannels)(rank);
    const offsets = new Array(shapes.length - 1);
    offsets[0] = shapes[0][axis];
    for (let i = 1; i < offsets.length; i++) {
        offsets[i] = offsets[i - 1] + shapes[i][axis];
    }
    const channel = channels[axis];
    const lastChannels = channels.slice(-2);
    const allChannels = channels.join();
    let getValueSnippet = `if (${channel} < ${offsets[0]}) {
        return getChannel(
            getX0(${allChannels}), vec2(${lastChannels.join()}));
        }`;
    for (let i = 1; i < offsets.length; i++) {
        const shift = offsets[i - 1];
        getValueSnippet += `
            if (${channel} < ${offsets[i]}  && ${channel} >= ${offsets[i - 1]}) {
              return getChannel(
                getX${i}(${getShiftedChannelsSnippet(channels, channel, shift)}),
                vec2(${getShiftedChannelsSnippet(lastChannels, channel, shift)}));
            }`;
    }
    const lastIndex = offsets.length;
    const shift = offsets[offsets.length - 1];
    getValueSnippet += `
            return getChannel(
              getX${lastIndex}(${getShiftedChannelsSnippet(channels, channel, shift)}),
              vec2(${getShiftedChannelsSnippet(lastChannels, channel, shift)}));`;
    const glsl = (0, glsl_source_1.getGlsl)(handler.session.backend.glContext.version);
    const shaderSource = `
          ${unpackChannel}
          float getValue(${channels.map(x => 'int ' + x)}) {
            ${getValueSnippet}
          }

          void main() {
            ${dtype} coords = getOutputCoords();
            int lastDim = coords.${channels[rank - 1]};
            coords.${channels[rank - 1]} = coords.${channels[rank - 2]};
            coords.${channels[rank - 2]} = lastDim;

            vec4 result = vec4(getValue(${coords}), 0., 0., 0.);

            ${coords[rank - 1]} = ${coords[rank - 1]} + 1;
            if (${coords[rank - 1]} < ${outputShape[rank - 1]}) {
              result.g = getValue(${coords});
            }

            ${coords[rank - 2]} = ${coords[rank - 2]} + 1;
            if (${coords[rank - 2]} < ${outputShape[rank - 2]}) {
              result.a = getValue(${coords});
            }

            ${coords[rank - 1]} = ${coords[rank - 1]} - 1;
            if (${coords[rank - 2]} < ${outputShape[rank - 2]} &&
                ${coords[rank - 1]} < ${outputShape[rank - 1]}) {
              result.b = getValue(${coords});
            }
            ${glsl.output} = result;
          }
        `;
    return Object.assign(Object.assign({}, metadata), { output: { dims: outputShape, type: inputs[0].type, textureType: types_1.TextureType.packed }, shaderSource, hasMain: true });
};
const createPackedConcatProgramInfoLoader = (handler, inputs, attributes) => {
    const metadata = createPackedConcatProgramMetadata(inputs.length, attributes.cacheKey);
    return Object.assign(Object.assign({}, metadata), { get: () => createPackedConcatProgramInfo(handler, metadata, inputs, attributes.axis) });
};
exports.createPackedConcatProgramInfoLoader = createPackedConcatProgramInfoLoader;
const getShiftedChannelsSnippet = (channels, channel, shift) => {
    const channelIdx = channels.indexOf(channel);
    const res = channels.map((c, idx) => {
        if (idx === channelIdx) {
            return `${c} - ${shift}`;
        }
        else {
            return c;
        }
    });
    return res.join();
};


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/ops/concat.ts":
/*!*************************************************!*\
  !*** ./lib/onnxjs/backends/webgl/ops/concat.ts ***!
  \*************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.parseConcatAttributes = exports.concat = void 0;
const attribute_with_cache_key_1 = __webpack_require__(/*! ../../../attribute-with-cache-key */ "./lib/onnxjs/attribute-with-cache-key.ts");
const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
const concat_packed_1 = __webpack_require__(/*! ./concat-packed */ "./lib/onnxjs/backends/webgl/ops/concat-packed.ts");
const concat = (inferenceHandler, inputs, attributes) => {
    validateInputs(inputs);
    if (inferenceHandler.session.pack && inputs[0].dims.length > 1) {
        const output = inferenceHandler.run((0, concat_packed_1.createPackedConcatProgramInfoLoader)(inferenceHandler, inputs, attributes), inputs);
        return [output];
    }
    else {
        const output = inferenceHandler.run(createUnpackedConcatProgramInfoLoader(inferenceHandler, inputs, attributes), inputs);
        return [output];
    }
};
exports.concat = concat;
const createUnpackedConcatProgramMetadata = (inputCount, cacheHint) => ({
    name: 'Concat',
    inputNames: Array.from({ length: inputCount }, (v, i) => `X${i}`),
    inputTypes: Array(inputCount).fill(types_1.TextureType.unpacked),
    cacheHint
});
const createUnpackedConcatProgramInfo = (handler, metadata, inputs, axis) => {
    const inputShape = inputs[0].dims.slice();
    if (axis >= inputShape.length || axis < (-1 * inputShape.length)) {
        throw new Error('axis specified for concat doesn\'t match input dimensionality');
    }
    if (axis < 0) {
        axis = inputShape.length + axis;
    }
    // ensure all of the non-concatenated axes match each other
    // calculate the shape of the output tensor while we do that
    const outputShape = inputShape.slice(0);
    for (let i = 1; i < inputs.length; i++) {
        const dataNShape = inputs[i].dims.slice();
        for (let axisIndex = 0; axisIndex < inputShape.length; axisIndex++) {
            // add to the placeholder for computing output shape
            if (axisIndex === axis) {
                outputShape[axis] += dataNShape[axisIndex];
            }
            // ensure all non-cancatenated axes match each other
            else if (inputShape[axisIndex] !== dataNShape[axisIndex]) {
                throw new Error('non concat dimensions must match');
            }
        }
    }
    const rank = outputShape.length;
    const sizeInConcatAxis = new Array(inputs.length);
    let previousSum = 0;
    for (let i = 0; i < sizeInConcatAxis.length; ++i) {
        previousSum += inputs[i].dims[axis];
        sizeInConcatAxis[i] = previousSum;
    }
    let getTextureIndexWhereDataResidesMethod = '';
    // in most cases linear search is sufficient, as in most scenarios, only 2 tensors are concatenated
    if (inputs.length < 5) {
        getTextureIndexWhereDataResidesMethod = getTextureIndexWhereDataResidesLinearSearch(sizeInConcatAxis);
    }
    else {
        getTextureIndexWhereDataResidesMethod = getTextureIndexWhereDataResidesBinarySearch(sizeInConcatAxis);
    }
    const fetchDataFromCorrectTextureMethod = getFetchDataFromCorrectTextureMethod(inputs.length, rank);
    const getSizeInConcatAxisValueFromIndexMethod = getGetSizeInConcatAxisValueFromIndexMethod(sizeInConcatAxis);
    const shaderSource = `
        ${fetchDataFromCorrectTextureMethod}
        ${getSizeInConcatAxisValueFromIndexMethod}
        ${getTextureIndexWhereDataResidesMethod}
        float process(int indices[${rank}]) {
          int textureIndex = getTextureWhereDataResides (indices[${axis}]);

          if(textureIndex != 0) {
            indices[${axis}] = indices[${axis}] - int(getSizeInConcatAxisValueFromIndex(textureIndex-int(1)));
          }

          return fetchDataFromCorrectTexture(textureIndex, indices);
        }`;
    return Object.assign(Object.assign({}, metadata), { output: { dims: outputShape, type: inputs[0].type, textureType: types_1.TextureType.unpacked }, shaderSource });
};
const createUnpackedConcatProgramInfoLoader = (handler, inputs, attributes) => {
    const metadata = createUnpackedConcatProgramMetadata(inputs.length, attributes.cacheKey);
    return Object.assign(Object.assign({}, metadata), { get: () => createUnpackedConcatProgramInfo(handler, metadata, inputs, attributes.axis) });
};
const getTextureIndexWhereDataResidesLinearSearch = (sizeInConcatAxis) => {
    const searchAxis = sizeInConcatAxis.map((size, i) => `if(index<${size}) {return ${i};}
`);
    return `int getTextureWhereDataResides(int index) {
      ${searchAxis.join('')}
    }`;
};
// TODO: Implement BinarySearch in GLSL
const getTextureIndexWhereDataResidesBinarySearch = (sizeInConcatAxis) => getTextureIndexWhereDataResidesLinearSearch(sizeInConcatAxis);
const getFetchDataFromCorrectTextureMethod = (numberOfTensors, tensorRank) => {
    const codeLines = [`float fetchDataFromCorrectTexture(int textureIndex, int indices[${tensorRank}]) {`];
    for (let i = 0; i < numberOfTensors; ++i) {
        if (i === 0) {
            codeLines.push('\t' +
                `if (textureIndex == ${i}) { return _X${i}(indices); }`);
        }
        else if (i === numberOfTensors - 1) {
            codeLines.push('\t' +
                `else { return _X${i}(indices); }`);
        }
        else {
            codeLines.push('\t' +
                `else if (textureIndex == ${i}) { return _X${i}(indices); }`);
        }
    }
    codeLines.push('\t' +
        '}');
    return codeLines.join('\n');
};
const getGetSizeInConcatAxisValueFromIndexMethod = (sizeInConcatAxis) => {
    const codeLines = ['int getSizeInConcatAxisValueFromIndex(int index) {'];
    for (let i = 0; i < sizeInConcatAxis.length; ++i) {
        if (i === 0) {
            codeLines.push('\t' +
                `if (index == ${i}) { return ${sizeInConcatAxis[i]}; }`);
        }
        else if (i === sizeInConcatAxis.length - 1) {
            codeLines.push('\t' +
                `else { return ${sizeInConcatAxis[i]}; }`);
        }
        else {
            codeLines.push('\t' +
                `else if (index == ${i}) { return ${sizeInConcatAxis[i]}; }`);
        }
    }
    codeLines.push('\t' +
        '}');
    return codeLines.join('\n');
};
const parseConcatAttributes = (node) => (0, attribute_with_cache_key_1.createAttributeWithCacheKey)({ axis: node.attributes.getInt('axis') });
exports.parseConcatAttributes = parseConcatAttributes;
const validateInputs = (inputs) => {
    if (!inputs || inputs.length < 1) {
        throw new Error('too few inputs');
    }
    const inputType = inputs[0].type;
    const inputDimensionality = inputs[0].dims.length;
    // TODO: Support string concat
    if (inputType === 'string') {
        throw new Error('string tensor is not supported yet');
    }
    for (const input of inputs) {
        // make sure types of all inputs match
        if (input.type !== inputType) {
            throw new Error('input tensors should be one type');
        }
        // make sure the dimensionality of all inputs are the same
        if (input.dims.length !== inputDimensionality) {
            throw new Error('input tensors should have the same shape');
        }
    }
};


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/ops/conv-grouped.ts":
/*!*******************************************************!*\
  !*** ./lib/onnxjs/backends/webgl/ops/conv-grouped.ts ***!
  \*******************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.createUnpackedGroupedConvProgramInfoLoader = void 0;
const instrument_1 = __webpack_require__(/*! ../../../instrument */ "./lib/onnxjs/instrument.ts");
const glsl_source_1 = __webpack_require__(/*! ../glsl-source */ "./lib/onnxjs/backends/webgl/glsl-source.ts");
const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
const conv_1 = __webpack_require__(/*! ./conv */ "./lib/onnxjs/backends/webgl/ops/conv.ts");
const fuse_utils_1 = __webpack_require__(/*! ./fuse-utils */ "./lib/onnxjs/backends/webgl/ops/fuse-utils.ts");
const createUnpackedGroupedConvProgramMetadata = (hasBias, cacheHint) => ({
    name: 'GroupedConv',
    inputNames: hasBias ? ['X', 'W', 'Bias'] : ['X', 'W'],
    inputTypes: hasBias ? [types_1.TextureType.unpacked, types_1.TextureType.unpacked, types_1.TextureType.unpacked] :
        [types_1.TextureType.unpacked, types_1.TextureType.unpacked],
    cacheHint
});
const createUnpackedGroupedConvProgramInfo = (inferenceHandler, inputs, metadata, attributes) => {
    const hasBias = inputs.length > 2;
    const processBias = hasBias ? 'value += getBias(output_channel);' : '';
    const xShape = inputs[0].dims.slice();
    const wShape = inputs[1].dims.slice();
    const outputChannelsPerGroup = wShape[0] / attributes.group;
    instrument_1.Logger.verbose('GroupedConv', `autpPad:${attributes.autoPad}, dilations:${attributes.dilations}, group:${attributes.group}, kernelShape:${attributes.kernelShape}, pads:${attributes.pads}, strides:${attributes.strides}`);
    const outputShape = (0, conv_1.calculateOutputShape)(xShape, wShape, attributes.dilations, attributes.pads, attributes.strides);
    const glsl = (0, glsl_source_1.getGlsl)(inferenceHandler.session.backend.glContext.version);
    const { activationFunction, applyActivation } = (0, fuse_utils_1.getActivationSnippet)(attributes);
    const shaderSource = `
  const ivec2 strides = ivec2(${attributes.strides[0]}, ${attributes.strides[1]});
  const ivec2 pads = ivec2(${attributes.pads[0]}, ${attributes.pads[1]});
  ${activationFunction}
  void main() {
    ivec4 coords = getOutputCoords();
    int batch = coords.x;
    int output_channel = coords.y;
    ivec2 xRCCorner = coords.zw * strides - pads;
    int group_id = output_channel / ${outputChannelsPerGroup};

    float value = 0.0;
    for (int wInChannel = 0; wInChannel < ${wShape[1]}; wInChannel++) {
      int input_channel = group_id * ${wShape[1]} + wInChannel;
      for (int wHeight = 0; wHeight < ${wShape[2]}; wHeight++) {
        int xHeight = xRCCorner.x + wHeight * ${attributes.dilations[0]};

        if (xHeight < 0 || xHeight >= ${xShape[2]}) {
          continue;
        }

        for (int wWidth = 0; wWidth < ${wShape[3]}; wWidth++) {
          int xWidth = xRCCorner.y + wWidth * ${attributes.dilations[1]};
          if (xWidth < 0 || xWidth >= ${xShape[3]}) {
            continue;
          }

          float xVal = getX(batch, input_channel, xWidth, xHeight);
          float wVal = getW(output_channel, wInChannel, wWidth, wHeight);
          value += xVal*wVal;
        }
      }
    }
    ${processBias}
    ${applyActivation}
    ${glsl.output} = vec4(value, .0, .0, .0);
  }
`;
    return Object.assign(Object.assign({}, metadata), { output: { dims: outputShape, type: inputs[0].type, textureType: types_1.TextureType.unpacked }, shaderSource, hasMain: true });
};
const createUnpackedGroupedConvProgramInfoLoader = (inferenceHandler, inputs, attributes) => {
    const metadata = createUnpackedGroupedConvProgramMetadata(inputs.length > 2, attributes.cacheKey);
    return Object.assign(Object.assign({}, metadata), { get: () => createUnpackedGroupedConvProgramInfo(inferenceHandler, inputs, metadata, attributes) });
};
exports.createUnpackedGroupedConvProgramInfoLoader = createUnpackedGroupedConvProgramInfoLoader;


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/ops/conv-pack.ts":
/*!****************************************************!*\
  !*** ./lib/onnxjs/backends/webgl/ops/conv-pack.ts ***!
  \****************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.conv2DPacked = exports.conv2DPackedPointwise = void 0;
const conv_1 = __webpack_require__(/*! ./conv */ "./lib/onnxjs/backends/webgl/ops/conv.ts");
const im2col_pack_1 = __webpack_require__(/*! ./im2col-pack */ "./lib/onnxjs/backends/webgl/ops/im2col-pack.ts");
const matmul_pack_1 = __webpack_require__(/*! ./matmul-pack */ "./lib/onnxjs/backends/webgl/ops/matmul-pack.ts");
const conv2DPackedPointwise = (inferenceHandler, inputs, attributes) => {
    const xshape = inputs[0].dims;
    const kshape = inputs[1].dims;
    const outputShape = (0, conv_1.calculateOutputShape)(xshape, kshape, attributes.dilations, attributes.pads, attributes.strides);
    const reshapedX = inferenceHandler.reshapePacked(inputs[0], [xshape[1], xshape[2] * xshape[3]]);
    const reshapedK = inferenceHandler.reshapePacked(inputs[1], [kshape[0], kshape[1]]);
    const matmulInputs = inputs.length > 2 ? [reshapedK, reshapedX, inputs[2]] : [reshapedK, reshapedX];
    const matmulOutput = inferenceHandler.run((0, matmul_pack_1.createPackedMatmulProgramInfoLoader)(inferenceHandler, matmulInputs, attributes), matmulInputs);
    return inferenceHandler.reshapePacked(matmulOutput, outputShape);
};
exports.conv2DPackedPointwise = conv2DPackedPointwise;
const conv2DPacked = (inferenceHandler, inputs, attributes) => {
    const xshape = inputs[0].dims;
    const kshape = inputs[1].dims;
    const outputShape = (0, conv_1.calculateOutputShape)(xshape, kshape, attributes.dilations, attributes.pads, attributes.strides);
    // run im2col
    const im2colOutput = inferenceHandler.run((0, im2col_pack_1.createPackedIm2ColProgramInfoLoader)(inferenceHandler, inputs[0], inputs[1], outputShape, attributes), [inputs[0]]);
    // reshape kernel
    const kernelReshaped = inferenceHandler.reshapePacked(inputs[1], [kshape[0], kshape[1] * kshape[2] * kshape[3]]);
    // run matmul
    const matmulInputs = (inputs.length === 3) ? [kernelReshaped, im2colOutput, inputs[2]] : [kernelReshaped, im2colOutput];
    const matmulOutput = inferenceHandler.run((0, matmul_pack_1.createPackedMatmulProgramInfoLoader)(inferenceHandler, matmulInputs, attributes), matmulInputs);
    // reshape output
    const outputReshaped = inferenceHandler.reshapePacked(matmulOutput, outputShape);
    return outputReshaped;
};
exports.conv2DPacked = conv2DPacked;


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/ops/conv-transpose.ts":
/*!*********************************************************!*\
  !*** ./lib/onnxjs/backends/webgl/ops/conv-transpose.ts ***!
  \*********************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.parseConvTransposeAttributes = exports.convTranspose = void 0;
const attribute_with_cache_key_1 = __webpack_require__(/*! ../../../attribute-with-cache-key */ "./lib/onnxjs/attribute-with-cache-key.ts");
const glsl_source_1 = __webpack_require__(/*! ../glsl-source */ "./lib/onnxjs/backends/webgl/glsl-source.ts");
const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
const fuse_utils_1 = __webpack_require__(/*! ./fuse-utils */ "./lib/onnxjs/backends/webgl/ops/fuse-utils.ts");
const computeTotalPad = (inDim, stride, adj, kernel, dilation, outSize) => (inDim - 1) * stride + adj + (kernel - 1) * dilation + 1 - outSize;
const distributePadding = (totalPad, autoPad, pads, head, tail) => {
    const smallPad = Math.floor(totalPad / 2);
    if (autoPad === 'SAME_UPPER') {
        pads[head] = smallPad;
        pads[tail] = totalPad - smallPad;
    }
    else if (autoPad === 'SAME_LOWER') {
        pads[head] = totalPad - smallPad;
        pads[tail] = smallPad;
    }
};
const calculateOutputShapeAndPads = (inputShape, kernelShape, dilations, autoPad, pads, strides, outputPadding, outputShape) => {
    const spatialRank = inputShape.length - 2;
    const updateShape = outputShape.length === 0;
    for (let i = 0; i < spatialRank; ++i) {
        const outSize = updateShape ? inputShape[i + 2] * strides[i] : outputShape[i];
        const totalPad = computeTotalPad(inputShape[i + 2], strides[i], pads[i], kernelShape[i], dilations[i], outSize);
        distributePadding(totalPad, autoPad, pads, i, i + spatialRank);
        if (updateShape) {
            outputShape.push(strides[i] * (inputShape[i + 2] - 1) + outputPadding[i] + (kernelShape[i] - 1) * dilations[i] + 1 -
                pads[i] - pads[i + spatialRank]);
        }
    }
};
const convTranspose = (inferenceHandler, inputs, attributes) => {
    validateInputs(inputs, attributes); // currently will fail if not convTranspose2D
    return convTranspose2d(inferenceHandler, inputs, attributes);
};
exports.convTranspose = convTranspose;
const convTranspose2d = (inferenceHandler, inputs, attributes) => {
    const adjustedAttributes = getAdjustedConvTransposeAttributes(attributes, inputs);
    return [convTranspose2DUnpacked(inferenceHandler, inputs, adjustedAttributes)];
};
const createConvTransposeProgramMetadata = (hasBias, cacheHint) => ({
    name: 'ConvTranspose',
    inputNames: hasBias ? ['X', 'W', 'B'] : ['X', 'W'],
    inputTypes: hasBias ? [types_1.TextureType.unpacked, types_1.TextureType.unpacked, types_1.TextureType.unpacked] :
        [types_1.TextureType.unpacked, types_1.TextureType.unpacked],
    cacheHint
});
const createUnpackedConvTransposeProgramInfo = (inferenceHandler, inputs, metadata, attributes) => {
    const hasBias = inputs.length > 2;
    const valueInit = hasBias ? 'getB(output_channel)' : '0.0';
    const xShape = inputs[0].dims;
    const wShape = inputs[1].dims;
    const outputChannelsPerGroup = wShape[1];
    const inputChannelsPerGroup = wShape[0] / attributes.group;
    const outputShape = [inputs[0].dims[0], inputs[1].dims[1] * attributes.group, ...attributes.outputShape];
    const glsl = (0, glsl_source_1.getGlsl)(inferenceHandler.session.backend.glContext.version);
    const { activationFunction, applyActivation } = (0, fuse_utils_1.getActivationSnippet)(attributes);
    const shaderSource = `
  const ivec2 strides = ivec2(${attributes.strides[0]}, ${attributes.strides[1]});
  const ivec2 pads = ivec2(${attributes.pads[0]}, ${attributes.pads[1]});
  ${activationFunction}
  void main() {
    ivec4 coords = getOutputCoords();
    int batch = coords.x;
    int output_channel = coords.y;

    ivec2 loc = coords.zw + pads;

    int group_id = output_channel / ${outputChannelsPerGroup};
    int wOutChannel = output_channel - group_id * ${outputChannelsPerGroup};

    float value = ${valueInit};
    for (int inChannelOffset = 0; inChannelOffset < ${inputChannelsPerGroup}; inChannelOffset++) {
      int input_channel = group_id * ${inputChannelsPerGroup} + inChannelOffset;
      for (int wWOff = 0; wWOff < ${wShape[2]}; wWOff++) {
        for (int wHOff = 0; wHOff < ${wShape[3]}; wHOff++) {
          ivec2 wOff = ivec2(wWOff * ${attributes.dilations[0]}, wHOff * ${attributes.dilations[1]});
          ivec2 wLoc = loc - wOff;
          ivec2 wLocIn = wLoc / strides;
          if (
            wLocIn * strides == wLoc &&
            wLocIn.x >= 0 && wLocIn.x < ${xShape[2]} &&
            wLocIn.y >= 0 && wLocIn.y < ${xShape[3]}
          ) {
            float xVal = getX(batch, input_channel, wLocIn.y, wLocIn.x);
            float wVal = getW(input_channel, wOutChannel, wHOff, wWOff);
            value += xVal * wVal;
          }
        }
      }
    }
    ${applyActivation}
    ${glsl.output} = vec4(value, .0, .0, .0);
  }
`;
    return Object.assign(Object.assign({}, metadata), { output: { dims: outputShape, type: inputs[0].type, textureType: types_1.TextureType.unpacked }, shaderSource, hasMain: true });
};
const createUnpackedConvTransposeProgramInfoLoader = (inferenceHandler, inputs, attributes) => {
    const metadata = createConvTransposeProgramMetadata(inputs.length > 2, attributes.cacheKey);
    return Object.assign(Object.assign({}, metadata), { get: () => createUnpackedConvTransposeProgramInfo(inferenceHandler, inputs, metadata, attributes) });
};
const convTranspose2DUnpacked = (inferenceHandler, inputs, attributes) => {
    const result = inferenceHandler.run(createUnpackedConvTransposeProgramInfoLoader(inferenceHandler, inputs, attributes), inputs);
    return result;
};
const getAdjustedConvTransposeAttributes = (attributes, inputs) => {
    const kernelShape = attributes.kernelShape.slice();
    // if kernelShape is not specified in the attributes of this op, infer it from the weight tensor dims
    if (attributes.kernelShape.length === 0) {
        for (let i = 2; i < inputs[1].dims.length; ++i) {
            kernelShape.push(inputs[1].dims[i]);
        }
    }
    const pads = attributes.pads.slice();
    const outputShape = attributes.outputShape.slice();
    const inputShape = inputs[0].dims;
    // If outputShape is not specified in the attributes of this op, infer it from the parameters
    // Similarly, automatically infer pads if not specified
    calculateOutputShapeAndPads(inputShape, kernelShape, attributes.dilations, attributes.autoPad, pads, attributes.strides, attributes.outputPadding, outputShape);
    // always return a new object so does not modify the original attributes
    const newAttributes = Object.assign({}, attributes);
    Object.assign(newAttributes, { kernelShape, pads, outputShape, cacheKey: attributes.cacheKey });
    return newAttributes;
};
const parseConvTransposeAttributes = (node) => {
    const attributes = node.attributes;
    const activationAttributes = (0, fuse_utils_1.parseInternalActivationAttributes)(attributes);
    // TODO : Make this generic enough to compute default attributes for multi-dimensional conv
    const autoPad = attributes.getString('auto_pad', 'NOTSET');
    const dilations = attributes.getInts('dilations', [1, 1]);
    const group = attributes.getInt('group', 1);
    const kernelShape = attributes.getInts('kernel_shape', []);
    const outputPadding = attributes.getInts('output_padding', [0, 0]);
    const outputShape = attributes.getInts('output_shape', []);
    const pads = attributes.getInts('pads', [0, 0, 0, 0]);
    const strides = attributes.getInts('strides', [1, 1]);
    return (0, attribute_with_cache_key_1.createAttributeWithCacheKey)(Object.assign({ autoPad, dilations, group, kernelShape, outputPadding, outputShape, pads, strides }, activationAttributes));
};
exports.parseConvTransposeAttributes = parseConvTransposeAttributes;
const validateInputs = (inputs, attributes) => {
    // Refer to the below link for all input checks
    // https://github.com/onnx/onnx/blob/main/docs/Operators.md#Conv
    if (!inputs || (inputs.length !== 2 && inputs.length !== 3)) {
        throw new Error('Conv requires 2 or 3 inputs');
    }
    // TODO : Need to add support for multi-dimensional conv
    if (inputs[0].dims.length !== 4 || inputs[1].dims.length !== 4) {
        throw new Error('currently only support 2-dimensional conv');
    }
    // FILTER_IN_CHANNEL should be equal to DATA_CHANNEL
    const dataChannel = inputs[0].dims[1];
    const filterInChannel = inputs[1].dims[0];
    if (dataChannel !== filterInChannel) {
        throw new Error('FILTER_IN_CHANNEL should be equal to DATA_CHANNEL');
    }
    const featureMaps = inputs[1].dims[1] * attributes.group;
    // if bias is provided it should be 1D and the number of elements should be equal to the number of feature maps
    if (inputs.length === 3 && (inputs[2].dims.length !== 1 || inputs[2].dims[0] !== featureMaps)) {
        throw new Error('invalid bias');
    }
    const spatialRank = inputs[0].dims.length - 2;
    // wrong dilations dimension
    if (attributes.dilations.length !== spatialRank) {
        throw new Error(`dilations should be ${spatialRank}D`);
    }
    // Wrong strides dimension
    if (attributes.strides.length !== spatialRank) {
        throw new Error(`strides should be ${spatialRank}D`);
    }
    // Wrong pads dimension
    if (attributes.pads.length !== spatialRank * 2) {
        throw new Error(`pads should be ${spatialRank * 2}D`);
    }
    // Wrong output padding dimension
    if (attributes.outputPadding.length !== spatialRank) {
        throw new Error(`output_padding should be ${spatialRank}D`);
    }
    // if kernelShape is specified, it's data length must be 2 less than dims length of the weights tensor
    // (the first 2 dims are batch_size and channels)
    if (attributes.kernelShape.length !== 0 && attributes.kernelShape.length !== inputs[1].dims.length - 2) {
        throw new Error('invalid kernel shape');
    }
    // as with kernelShape, must have same number of spatial dims as input
    if (attributes.outputShape.length !== 0 && attributes.outputShape.length !== inputs[0].dims.length - 2) {
        throw new Error('invalid output shape');
    }
    // TODO : Need to add support for float64
    if (inputs[0].type !== 'float32' || inputs[1].type !== 'float32') {
        throw new Error('ConvTranspose input(X,W) should be float tensor');
    }
    if (inputs.length === 3 && inputs[2].type !== 'float32') {
        throw new Error('ConvTranspose input(bias) should be float tensor');
    }
};


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/ops/conv.ts":
/*!***********************************************!*\
  !*** ./lib/onnxjs/backends/webgl/ops/conv.ts ***!
  \***********************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.parseConvAttributes = exports.conv = exports.calculateOutputShape = void 0;
const attribute_with_cache_key_1 = __webpack_require__(/*! ../../../attribute-with-cache-key */ "./lib/onnxjs/attribute-with-cache-key.ts");
const util_1 = __webpack_require__(/*! ../../../util */ "./lib/onnxjs/util.ts");
const conv_grouped_1 = __webpack_require__(/*! ./conv-grouped */ "./lib/onnxjs/backends/webgl/ops/conv-grouped.ts");
const conv_pack_1 = __webpack_require__(/*! ./conv-pack */ "./lib/onnxjs/backends/webgl/ops/conv-pack.ts");
const dot_product_1 = __webpack_require__(/*! ./dot-product */ "./lib/onnxjs/backends/webgl/ops/dot-product.ts");
const fuse_utils_1 = __webpack_require__(/*! ./fuse-utils */ "./lib/onnxjs/backends/webgl/ops/fuse-utils.ts");
const im2col_1 = __webpack_require__(/*! ./im2col */ "./lib/onnxjs/backends/webgl/ops/im2col.ts");
const matmul_1 = __webpack_require__(/*! ./matmul */ "./lib/onnxjs/backends/webgl/ops/matmul.ts");
const calculateOutputShape = (inputShape, kernelShape, dilations, adjustPads, strides) => {
    const batchSize = inputShape[0];
    const inputSpatialShape = inputShape.slice(2);
    const spatialRank = inputSpatialShape.length;
    const outChannels = kernelShape[0];
    const kernelSpatialShape = kernelShape.slice(2);
    const dilatedKernelShape = kernelSpatialShape.map((v, i) => v + (v - 1) * (dilations[i] - 1));
    const inputSpatialShapeWithPad = inputSpatialShape.map((v, i) => v + adjustPads[i] + adjustPads[i + spatialRank]);
    const outputSpatialShape = inputSpatialShapeWithPad.map((v, i) => Math.floor((v - dilatedKernelShape[i] + strides[i]) / strides[i]));
    const outputShape = [batchSize, outChannels].concat(...outputSpatialShape);
    return outputShape;
};
exports.calculateOutputShape = calculateOutputShape;
const conv = (inferenceHandler, inputs, attributes) => {
    validateInputs(inputs, attributes); // currently will fail if not conv2D
    return conv2d(inferenceHandler, inputs, attributes);
};
exports.conv = conv;
const conv2d = (inferenceHandler, inputs, attributes) => {
    const adjustedAttributes = getAdjustedConvAttributes(attributes, inputs);
    const packMode = inferenceHandler.session.pack;
    const isPointwise = adjustedAttributes.kernelShape[0] === 1 && adjustedAttributes.kernelShape[1] === 1;
    if (adjustedAttributes.group > 1) {
        const result = inferenceHandler.run((0, conv_grouped_1.createUnpackedGroupedConvProgramInfoLoader)(inferenceHandler, inputs, adjustedAttributes), inputs);
        return [result];
    }
    else if (isPointwise && packMode) {
        return [conv2DUnpackedPointwise(inferenceHandler, inputs, adjustedAttributes)];
    }
    else if (packMode && inputs[0].dims.length === 4 && inputs[0].dims[0] === 1 && !isPointwise) {
        return [(0, conv_pack_1.conv2DPacked)(inferenceHandler, inputs, adjustedAttributes)];
    }
    else {
        return [conv2DUnpacked(inferenceHandler, inputs, adjustedAttributes)];
    }
};
const conv2DUnpackedPointwise = (inferenceHandler, inputs, attributes) => {
    const xshape = inputs[0].dims;
    const kshape = inputs[1].dims;
    const outputShape = (0, exports.calculateOutputShape)(xshape, kshape, attributes.dilations, attributes.pads, attributes.strides);
    const reshapedX = inferenceHandler.reshapeUnpacked(inputs[0], [xshape[1], xshape[2] * xshape[3]]);
    const reshapedK = inferenceHandler.reshapeUnpacked(inputs[1], [kshape[0], kshape[1]]);
    const matmulInputs = inputs.length > 2 ? [reshapedK, reshapedX, inputs[2]] : [reshapedK, reshapedX];
    const matmulOutput = inferenceHandler.run((0, matmul_1.createMatmulProgramInfoLoader)(matmulInputs, attributes), matmulInputs);
    return inferenceHandler.reshapeUnpacked(matmulOutput, outputShape);
};
const conv2DUnpacked = (inferenceHandler, inputs, attributes) => {
    const xshape = inputs[0].dims;
    const kshape = inputs[1].dims;
    const outputShape = (0, exports.calculateOutputShape)(xshape, kshape, attributes.dilations, attributes.pads, attributes.strides);
    const xIm2Col = inferenceHandler.run((0, im2col_1.createIm2ColProgramInfoLoader)(inferenceHandler, inputs[0], inputs[1], outputShape, attributes), [inputs[0]]);
    const dotProductInputs = inputs.length === 3 ? [xIm2Col, inputs[1], inputs[2]] : [xIm2Col, inputs[1]];
    const output = inferenceHandler.run((0, dot_product_1.createDotProductProgramInfoLoader)(inferenceHandler, inputs, outputShape, attributes), dotProductInputs);
    return output;
};
const getAdjustedConvAttributes = (attributes, inputs) => {
    const kernelShape = attributes.kernelShape.slice();
    // if kernelShape is not specified in the attributes of this op, infer it from the weight tensor dims
    if (attributes.kernelShape.length === 0) {
        for (let i = 2; i < inputs[1].dims.length; ++i) {
            kernelShape.push(inputs[1].dims[i]);
        }
    }
    const pads = attributes.pads.slice();
    util_1.PoolConvUtil.adjustPadsBasedOnAutoPad(inputs[0].dims, attributes.strides, attributes.dilations, kernelShape, pads, attributes.autoPad);
    // always return a new object so does not modify the original attributes
    const newAttributes = Object.assign({}, attributes);
    Object.assign(newAttributes, { kernelShape, pads, cacheKey: attributes.cacheKey });
    return newAttributes;
};
const parseConvAttributes = (node) => {
    const attributes = node.attributes;
    const activationAttributes = (0, fuse_utils_1.parseInternalActivationAttributes)(attributes);
    // TODO : Make this generic enough to compute default attributes for multi-dimensional conv
    const autoPad = attributes.getString('auto_pad', 'NOTSET');
    const dilations = attributes.getInts('dilations', [1, 1]);
    const group = attributes.getInt('group', 1);
    const kernelShape = attributes.getInts('kernel_shape', []);
    const pads = attributes.getInts('pads', [0, 0, 0, 0]);
    const strides = attributes.getInts('strides', [1, 1]);
    return (0, attribute_with_cache_key_1.createAttributeWithCacheKey)(Object.assign({ autoPad, dilations, group, kernelShape, pads, strides }, activationAttributes));
};
exports.parseConvAttributes = parseConvAttributes;
const validateInputs = (inputs, attributes) => {
    // Refer to the below link for all input checks
    // https://github.com/onnx/onnx/blob/main/docs/Operators.md#Conv
    if (!inputs || (inputs.length !== 2 && inputs.length !== 3)) {
        throw new Error('Conv requires 2 or 3 inputs');
    }
    // TODO : Need to add support for multi-dimensional conv
    if (inputs[0].dims.length !== 4 || inputs[1].dims.length !== 4) {
        throw new Error('currently only support 2-dimensional conv');
    }
    // FILTER_IN_CHANNEL should be equal to DATA_CHANNEL
    const dataChannel = inputs[0].dims[1];
    const filterInChannel = inputs[1].dims[1] * attributes.group;
    if (dataChannel !== filterInChannel) {
        throw new Error('FILTER_IN_CHANNEL should be equal to DATA_CHANNEL');
    }
    // if bias is provided it should be 1D and the number of elements should be equal to the number of feature maps
    if (inputs.length === 3 && (inputs[2].dims.length !== 1 || inputs[1].dims[0] !== inputs[2].dims[0])) {
        throw new Error('invalid bias');
    }
    const spatialRank = inputs[0].dims.length - 2;
    // wrong dilations dimension
    if (attributes.dilations.length !== spatialRank) {
        throw new Error(`dilations should be ${spatialRank}D`);
    }
    // Wrong strides dimension
    if (attributes.strides.length !== spatialRank) {
        throw new Error(`strides should be ${spatialRank}D`);
    }
    // Wrong pads dimension
    if (attributes.pads.length !== spatialRank * 2) {
        throw new Error(`pads should be ${spatialRank * 2}D`);
    }
    // if kernelShape is specified, it's data length must be 2 less than dims length of the weights tensor
    // (the first 2 dims are batch_size and channels)
    if (attributes.kernelShape.length !== 0 && attributes.kernelShape.length !== inputs[1].dims.length - 2) {
        throw new Error('invalid kernel shape');
    }
    // TODO : Need to add support for float64
    if (inputs[0].type !== 'float32' || inputs[1].type !== 'float32') {
        throw new Error('Conv input(X,W) should be float tensor');
    }
    if (inputs.length === 3 && inputs[2].type !== 'float32') {
        throw new Error('Conv input(bias) should be float tensor');
    }
};


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/ops/depth-to-space.ts":
/*!*********************************************************!*\
  !*** ./lib/onnxjs/backends/webgl/ops/depth-to-space.ts ***!
  \*********************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.parseDepthToSpaceAttributes = exports.depthToSpace = void 0;
const transpose_1 = __webpack_require__(/*! ./transpose */ "./lib/onnxjs/backends/webgl/ops/transpose.ts");
const depthToSpace = (inferenceHandler, inputs, attributes) => {
    validateInputs(inputs);
    const blocksize = attributes.blocksize;
    const blocksizeSqr = blocksize * blocksize;
    const transposePerm = attributes.mode === 'DCR' ? [0, 3, 4, 1, 5, 2] : [0, 1, 4, 2, 5, 3];
    const firstReshapeShape = attributes.mode === 'DCR' ?
        [
            inputs[0].dims[0], blocksize, blocksize, inputs[0].dims[1] / blocksizeSqr, inputs[0].dims[2],
            inputs[0].dims[3]
        ] :
        [
            inputs[0].dims[0], inputs[0].dims[1] / blocksizeSqr, blocksize, blocksize, inputs[0].dims[2],
            inputs[0].dims[3]
        ];
    // const transpose = new WebGLTranspose();
    // const attributes = new Attribute(undefined);
    // attributes.set('perm', 'ints', transposePerm);
    // transpose.initialize(attributes);
    // First reshape
    const firstReshapedTensor = inferenceHandler.reshapeUnpacked(inputs[0], firstReshapeShape);
    // transpose
    const transposeAttributes = { perm: transposePerm, cacheKey: `${transposePerm}` };
    const [transposeOutput] = (0, transpose_1.transpose)(inferenceHandler, [firstReshapedTensor], transposeAttributes);
    // Second reshape
    const secondReshapeShape = [
        inputs[0].dims[0], inputs[0].dims[1] / blocksizeSqr, inputs[0].dims[2] * blocksize,
        inputs[0].dims[3] * blocksize
    ];
    const result = inferenceHandler.reshapeUnpacked(transposeOutput, secondReshapeShape);
    return [result];
};
exports.depthToSpace = depthToSpace;
const parseDepthToSpaceAttributes = (node) => {
    // processing node attributes
    const blocksize = node.attributes.getInt('blocksize');
    if (blocksize < 1) {
        throw new Error(`blocksize must be >= 1, but got : ${blocksize} for DepthToSpace`);
    }
    const mode = node.attributes.getString('mode', 'DCR');
    if (mode !== 'DCR' && mode !== 'CRD') {
        throw new Error(`unrecognized mode: ${mode} for DepthToSpace`);
    }
    return { mode, blocksize };
};
exports.parseDepthToSpaceAttributes = parseDepthToSpaceAttributes;
const validateInputs = (inputs) => {
    if (inputs.length !== 1) {
        throw new Error(`DepthToSpace expect 1 inputs, but got ${inputs.length}`);
    }
    // Input has to be a 4-D tensor
    // TODO: Support string depth-to-space.
    if (inputs[0].type === 'string' || inputs[0].dims.length !== 4) {
        throw new TypeError('DepthToSpace input should be a 4-D numeric tensor');
    }
};


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/ops/dot-product.ts":
/*!******************************************************!*\
  !*** ./lib/onnxjs/backends/webgl/ops/dot-product.ts ***!
  \******************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.createDotProductProgramInfoLoader = void 0;
const util_1 = __webpack_require__(/*! ../../../util */ "./lib/onnxjs/util.ts");
const glsl_source_1 = __webpack_require__(/*! ../glsl-source */ "./lib/onnxjs/backends/webgl/glsl-source.ts");
const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
const fuse_utils_1 = __webpack_require__(/*! ./fuse-utils */ "./lib/onnxjs/backends/webgl/ops/fuse-utils.ts");
const im2col_1 = __webpack_require__(/*! ./im2col */ "./lib/onnxjs/backends/webgl/ops/im2col.ts");
const createDotProductProgramMetadata = (hasBias, attributes) => ({
    name: 'ConvDotProduct',
    inputNames: hasBias ? ['Im2Col', 'K', 'B'] : ['Im2Col', 'K'],
    inputTypes: hasBias ? [types_1.TextureType.unpacked, types_1.TextureType.packedLastDimension, types_1.TextureType.unpacked] :
        [types_1.TextureType.unpacked, types_1.TextureType.packedLastDimension],
    cacheKey: attributes.activationCacheKey
});
const createDotProductProgramInfo = (inferenceHandler, metadata, inputs, outputShape, attributes) => {
    const xshape = inputs[0].dims;
    const kshape = inputs[1].dims;
    const adjustedKernelShape = [kshape[0], Math.ceil((xshape[1] * kshape[2] * kshape[3]) / 4)];
    const im2colShape = (0, im2col_1.calculateIm2ColDims)(xshape, kshape, outputShape);
    const [kWidth, kHeight] = inferenceHandler.calculateTextureWidthAndHeight(adjustedKernelShape, types_1.TextureType.packedLastDimension);
    const im2colStrides = util_1.ShapeUtil.computeStrides(im2colShape);
    const [im2colWidth, im2colHeight] = inferenceHandler.calculateTextureWidthAndHeight(im2colShape, types_1.TextureType.packedLastDimension);
    const rank = outputShape.length;
    const initValue = (inputs.length < 3) ? '0.0' : '_B(b)';
    const sharedDim = Math.ceil(xshape[1] * kshape[2] * kshape[3] / 4);
    const { activationFunction, applyActivation } = (0, fuse_utils_1.getActivationSnippet)(attributes);
    const glsl = (0, glsl_source_1.getGlsl)(inferenceHandler.session.backend.glContext.version);
    const shaderSource = `
${activationFunction}
float process(int indices[${rank}]) {
  int b[1];
  b[0] = indices[1];
  int im2col[4];
  im2col[0] = indices[0];
  im2col[1] = indices[2];
  im2col[2] = indices[3];
  int im2colOffset = im2col[0] * ${im2colStrides[0]} + im2col[1] * ${im2colStrides[1]} + im2col[2] * ${im2colStrides[2]};
  int kernelOffset = indices[1] * ${adjustedKernelShape[1]};
  float value = ${initValue};
  for (int i = 0; i < ${sharedDim}; ++i) {
    vec2 im2colCoords = offsetToCoords(im2colOffset, ${im2colWidth}, ${im2colHeight});
    vec2 kernelCoords = offsetToCoords(kernelOffset, ${kWidth}, ${kHeight});
    value += dot(${glsl.texture2D}(Im2Col, im2colCoords), ${glsl.texture2D}(K, kernelCoords));
    ++im2colOffset;
    ++kernelOffset;
  }
  ${applyActivation}
  return value;
}`;
    return Object.assign(Object.assign({}, metadata), { output: { dims: outputShape, type: inputs[0].type, textureType: types_1.TextureType.unpacked }, shaderSource });
};
const createDotProductProgramInfoLoader = (inferenceHandler, inputs, outputShape, attributes) => {
    const metadata = createDotProductProgramMetadata(inputs.length > 2, attributes);
    return Object.assign(Object.assign({}, metadata), { get: () => createDotProductProgramInfo(inferenceHandler, metadata, inputs, outputShape, attributes) });
};
exports.createDotProductProgramInfoLoader = createDotProductProgramInfoLoader;


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/ops/flatten.ts":
/*!**************************************************!*\
  !*** ./lib/onnxjs/backends/webgl/ops/flatten.ts ***!
  \**************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.parseFlattenAttributes = exports.flatten = void 0;
const util_1 = __webpack_require__(/*! ../../../util */ "./lib/onnxjs/util.ts");
const flatten = (inferenceHandler, inputs, axis) => {
    validateInputs(inputs, axis);
    const outputDims = util_1.ShapeUtil.flattenShape(inputs[0].dims, axis);
    return [inferenceHandler.reshapeUnpacked(inputs[0], outputDims)];
};
exports.flatten = flatten;
const parseFlattenAttributes = (node) => node.attributes.getInt('axis', 1); // default axis is 1
exports.parseFlattenAttributes = parseFlattenAttributes;
const validateInputs = (inputs, axis) => {
    if (!inputs || inputs.length !== 1) {
        throw new Error('Flatten requires 1 input.');
    }
    const r = inputs[0].dims.length;
    if (r === 0) {
        throw new Error('scalar tensor is not supported.');
    }
    if (axis < -r || axis > r) {
        throw new Error('Invalid axis');
    }
    // TODO: Support string type
    if (inputs[0].type === 'string') {
        throw new Error('string tensor is not supported.');
    }
};


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/ops/fuse-utils.ts":
/*!*****************************************************!*\
  !*** ./lib/onnxjs/backends/webgl/ops/fuse-utils.ts ***!
  \*****************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.parseInternalActivationAttributes = exports.getActivationSnippet = void 0;
const util_1 = __webpack_require__(/*! ../../../util */ "./lib/onnxjs/util.ts");
const unary_op_1 = __webpack_require__(/*! ./unary-op */ "./lib/onnxjs/backends/webgl/ops/unary-op.ts");
function getActivationSnippet(attributes) {
    let func;
    switch (attributes.activation) {
        case 'Relu':
            func = (0, unary_op_1.glslRelu)();
            break;
        case 'Sigmoid':
            func = (0, unary_op_1.glslSigmoid)();
            break;
        case 'Clip':
            func = (0, unary_op_1.glslClip)(attributes.clipMin, attributes.clipMax);
            break;
        // TODO: adding other activations that can be fused.
        default:
            return { activationFunction: '', applyActivation: '' };
    }
    const activationName = func.name;
    const activationFunction = func.body;
    const applyActivation = `value = ${activationName}_(value);`;
    return { activationFunction, applyActivation };
}
exports.getActivationSnippet = getActivationSnippet;
const parseInternalActivationAttributes = (attributes) => {
    const activation = attributes.getString('activation', '');
    if (activation === 'Clip') {
        const [clipMin, clipMax] = attributes.getFloats('activation_params', [util_1.MIN_CLIP, util_1.MAX_CLIP]);
        return { activation, clipMax, clipMin, activationCacheKey: `${activation}:${clipMin},${clipMax}` };
    }
    return { activation, activationCacheKey: activation };
};
exports.parseInternalActivationAttributes = parseInternalActivationAttributes;


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/ops/gather.ts":
/*!*************************************************!*\
  !*** ./lib/onnxjs/backends/webgl/ops/gather.ts ***!
  \*************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.parseGatherAttributes = exports.gather = void 0;
const attribute_with_cache_key_1 = __webpack_require__(/*! ../../../attribute-with-cache-key */ "./lib/onnxjs/attribute-with-cache-key.ts");
const operators_1 = __webpack_require__(/*! ../../../operators */ "./lib/onnxjs/operators.ts");
const util_1 = __webpack_require__(/*! ../../../util */ "./lib/onnxjs/util.ts");
const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
const gather = (inferenceHandler, inputs, attributes) => {
    validateInputs(inputs, attributes.axis);
    const output = inferenceHandler.run(createGatherProgramInfoLoader(inferenceHandler, inputs, attributes), inputs);
    return [output];
};
exports.gather = gather;
const parseGatherAttributes = (node) => (0, attribute_with_cache_key_1.createAttributeWithCacheKey)({ axis: node.attributes.getInt('axis', 0) });
exports.parseGatherAttributes = parseGatherAttributes;
const gatherProgramMetadata = {
    name: 'Gather',
    inputNames: ['A', 'B'],
    inputTypes: [types_1.TextureType.unpacked, types_1.TextureType.unpacked],
};
const createGatherProgramInfo = (handler, metadata, inputs, axis) => {
    const inputShape = inputs[0].dims.slice();
    const indexDataShape = inputs[1].dims.slice();
    const outputShape = new Array(inputShape.length + indexDataShape.length - 1);
    axis = util_1.ShapeUtil.normalizeAxis(axis, inputShape.length);
    const indexCopyOps = [];
    for (let i = 0; i < outputShape.length; i++) {
        // outputShape is divided into three parts: A, B, C
        // |0        axis|  axis + indexDataShape.length |          end|
        // |     A       |             B                 |      C      |
        //
        // inputIdx: [A, inputs[1][B], C]
        if (i < axis) { // A
            outputShape[i] = inputShape[i];
            indexCopyOps.push(`inputIdx[${i}] = outputIdx[${i}];`);
        }
        else {
            if (i < axis + indexDataShape.length) { // B
                outputShape[i] = indexDataShape[i - axis];
                indexCopyOps.push(`indexDataIdx[${i - axis}] = outputIdx[${i}];`);
            }
            else { // C
                outputShape[i] = inputShape[i - indexDataShape.length + 1]; // skip 1 for axis
                indexCopyOps.push(`inputIdx[${i - indexDataShape.length + 1}] = outputIdx[${i}];`);
            }
        }
    }
    const orank = outputShape.length || 1;
    const irank = inputShape.length;
    const iDrank = indexDataShape.length || 1;
    const shaderSource = `
      float process(int outputIdx[${orank}]) {
        int inputIdx[${irank}];
        int indexDataIdx[${iDrank}];
        indexDataIdx[0] = 0;
        ${indexCopyOps.join('\n        ')}
        int idx = int(_B(indexDataIdx));
        inputIdx[${axis}] = idx < 0 ? idx + ${inputShape[axis]} : idx;
        return _A(inputIdx);
      }`;
    return Object.assign(Object.assign({}, metadata), { output: { dims: outputShape, type: inputs[0].type, textureType: types_1.TextureType.unpacked }, shaderSource });
};
const createGatherProgramInfoLoader = (handler, inputs, attributes) => {
    const metadata = Object.assign(Object.assign({}, gatherProgramMetadata), { cacheHint: attributes.cacheKey });
    return Object.assign(Object.assign({}, metadata), { get: () => createGatherProgramInfo(handler, metadata, inputs, attributes.axis) });
};
const validateInputs = (inputs, axis) => {
    if (!inputs || inputs.length !== 2) {
        throw new Error('Gather requires 2 inputs.');
    }
    const tensorRank = inputs[0].dims.length;
    if (tensorRank < 1) {
        throw new Error('Invalid input shape.');
    }
    if (axis < -tensorRank || axis > tensorRank - 1) {
        throw new Error('Invalid axis.');
    }
    if (operators_1.NUMBER_TYPES.indexOf(inputs[0].type) === -1) {
        throw new Error('Invaid input type.');
    }
    if (inputs[1].type !== 'int32' && inputs[1].type !== 'int16') {
        throw new Error('Invaid input type.');
    }
};


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/ops/gemm.ts":
/*!***********************************************!*\
  !*** ./lib/onnxjs/backends/webgl/ops/gemm.ts ***!
  \***********************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.parseGemmAttributesV11 = exports.parseGemmAttributesV7 = exports.gemm = void 0;
const attribute_with_cache_key_1 = __webpack_require__(/*! ../../../attribute-with-cache-key */ "./lib/onnxjs/attribute-with-cache-key.ts");
const util_1 = __webpack_require__(/*! ../../../util */ "./lib/onnxjs/util.ts");
const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
const gemm = (inferenceHandler, inputs, attributes) => {
    validateInputs(inputs, attributes);
    const output = inferenceHandler.run(createGemmProgramInfoLoader(inputs, attributes), inputs);
    return [output];
};
exports.gemm = gemm;
const parseGemmAttributes = (node, isOptionalC) => {
    const transA = node.attributes.getInt('transA', 0) !== 0;
    const transB = node.attributes.getInt('transB', 0) !== 0;
    const alpha = node.attributes.getFloat('alpha', 1.0);
    const beta = node.attributes.getFloat('beta', 1.0);
    return (0, attribute_with_cache_key_1.createAttributeWithCacheKey)({ transA, transB, alpha, beta, isOptionalC });
};
const parseGemmAttributesV7 = (node) => parseGemmAttributes(node, false);
exports.parseGemmAttributesV7 = parseGemmAttributesV7;
const parseGemmAttributesV11 = (node) => parseGemmAttributes(node, true);
exports.parseGemmAttributesV11 = parseGemmAttributesV11;
const createGemmProgramInfoLoader = (inputs, attributes) => {
    const metadata = {
        name: 'Gemm',
        inputNames: inputs.length === 3 ? ['A', 'B', 'C'] : ['A', 'B'],
        inputTypes: inputs.length === 3 ? [types_1.TextureType.unpacked, types_1.TextureType.unpacked, types_1.TextureType.unpacked] :
            [types_1.TextureType.unpacked, types_1.TextureType.unpacked],
        key: attributes.cacheKey
    };
    return Object.assign(Object.assign({}, metadata), { get: () => createGemmProgramInfo(metadata, inputs, attributes) });
};
const createGemmProgramInfo = (metadata, inputs, attributes) => {
    const aShape = inputs[0].dims.slice();
    const bShape = inputs[1].dims.slice();
    const [M, N] = util_1.GemmUtil.getShapeOfGemmResult(aShape, attributes.transA, bShape, attributes.transB, inputs.length === 3 ? inputs[2].dims : undefined);
    const outputShape = [M, N];
    if (!outputShape) {
        throw new Error('Can\'t use gemm on the given tensors');
    }
    let sharedDim = aShape[aShape.length - 1];
    let line = '';
    if (attributes.transA) {
        sharedDim = aShape[0];
    }
    if (attributes.transA && attributes.transB) {
        line = 'value += _A_T(a) * _B_T(b);';
    }
    else if (attributes.transA && !attributes.transB) {
        line = 'value += _A_T(a) * _B(b);';
    }
    else if (!attributes.transA && attributes.transB) {
        line = 'value += _A(a) * _B_T(b);';
    }
    else if (!attributes.transA && !attributes.transB) {
        line = 'value += _A(a) * _B(b);';
    }
    const rank = outputShape.length;
    const declareC = inputs.length === 3 ? `int c[${inputs[2].dims.length}];` : '';
    const broadcastC = inputs.length === 3 ? 'bcastIndices_C(indices, c);' : '';
    const calculateC = inputs.length === 3 ? 'value += beta * _C(c);' : '';
    const shaderSource = `
      float process(int indices[${rank}]) {
          int a[${rank}];
          int b[${rank}];
          ${declareC}

          copyVec(indices, a);
          copyVec(indices, b);
          ${broadcastC}

          float value = 0.0;
          for (int k=0; k<${sharedDim}; ++k) {
              a[${rank - 1}] = k;
              b[${rank - 2}] = k;
              ${line}
          }

          value = value * alpha;
          ${calculateC}
          return value;
      }`;
    return Object.assign(Object.assign({}, metadata), { output: { dims: outputShape, type: inputs[0].type, textureType: types_1.TextureType.unpacked }, variables: [
            { name: 'alpha', type: 'float', data: attributes.alpha }, { name: 'beta', type: 'float', data: attributes.beta }
        ], shaderSource });
};
const validateInputs = (inputs, attributes) => {
    if (!inputs) {
        throw new Error('Input is missing');
    }
    if (attributes.isOptionalC && (inputs.length < 2 || inputs.length > 3)) {
        throw new Error('Invaid input shape.');
    }
    if (!attributes.isOptionalC && inputs.length !== 3) {
        throw new Error('Gemm requires 3 inputs');
    }
    // 'C' can be of dimensionality 1 or 2 only
    if (inputs.length === 3 && inputs[2].dims.length !== 1 && inputs[2].dims.length !== 2) {
        throw new Error('Invalid input shape of C');
    }
    if ((inputs[0].type !== 'float32' && inputs[0].type !== 'float64') ||
        (inputs[1].type !== 'float32' && inputs[1].type !== 'float64') ||
        (inputs.length === 3 && inputs[2].type !== 'float32' && inputs[2].type !== 'float64')) {
        throw new Error('Invalid input type.');
    }
    if ((inputs[0].type !== inputs[1].type) || (inputs.length === 3 && inputs[0].type !== inputs[2].type)) {
        throw new Error('Input types are mismatched');
    }
};


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/ops/im2col-pack.ts":
/*!******************************************************!*\
  !*** ./lib/onnxjs/backends/webgl/ops/im2col-pack.ts ***!
  \******************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.createPackedIm2ColProgramInfoLoader = void 0;
const glsl_source_1 = __webpack_require__(/*! ../glsl-source */ "./lib/onnxjs/backends/webgl/glsl-source.ts");
const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
const packing_utils_1 = __webpack_require__(/*! ./packing-utils */ "./lib/onnxjs/backends/webgl/ops/packing-utils.ts");
const createPackedIm2ColProgramMetadata = (cacheHint) => ({
    name: 'Im2Col (packed)',
    inputNames: ['A'],
    inputTypes: [types_1.TextureType.packed],
    cacheHint,
});
const createPackedIm2ColProgramInfo = (inferenceHandler, metadata, x, w, outputShape, attributes) => {
    const xshape = x.dims;
    const wshape = w.dims;
    const rowDim = 2;
    const colDim = 3;
    const rank = outputShape.length;
    const im2colShape = [wshape[1] * wshape[2] * wshape[3], outputShape[2] * outputShape[3]];
    const kernelSize = wshape[2] * wshape[3];
    const unpackChannel = (0, packing_utils_1.unpackFromChannel)();
    const glsl = (0, glsl_source_1.getGlsl)(inferenceHandler.session.backend.glContext.version);
    let unrolled = '';
    for (let row = 0; row <= 1; row++) {
        for (let col = 0; col <= 1; col++) {
            unrolled += `
            blockIndex = rc.x + ${col};
            pos = rc.y + ${row};

            if(blockIndex < ${im2colShape[1]} && pos < ${im2colShape[0]}) {
              offsetY = int(blockIndex / (${outputShape[rank - 1]})) * ${attributes.strides[0]} -
                ${attributes.pads[0]};
              d0 = offsetY + ${attributes.dilations[0]} * (imod(pos, ${kernelSize}) / ${wshape[2]});

              if(d0 < ${xshape[rowDim]} && d0 >= 0) {
                offsetX = imod(blockIndex, ${outputShape[rank - 1]}) * ${attributes.strides[1]} -
                  ${attributes.pads[1]};
                d1 = offsetX + ${attributes.dilations[1]} * imod(imod(pos, ${kernelSize}), ${wshape[2]});

                if(d1 < ${xshape[colDim]} && d1 >= 0) {

                  ch = int(float(pos)/ ${kernelSize}.);
                    innerDims = vec2(d0, d1);
                    result[${row * 2 + col}] = getChannel(
                      getA(0, ch, int(innerDims.x),
                      int(innerDims.y)), innerDims);
                }
              }
            }

          `;
        }
    }
    const shaderSource = `
      ${unpackChannel}

      void main() {
        ivec2 rc = getOutputCoords();
          vec4 result = vec4(0.0);
          int blockIndex, pos, offsetY, d0, offsetX, d1, ch;
          vec2 innerDims;
          ${unrolled}
          ${glsl.output} = result;
      }
            `;
    return Object.assign(Object.assign({}, metadata), { output: { dims: im2colShape, type: x.type, textureType: types_1.TextureType.packed }, shaderSource, hasMain: true });
};
const createPackedIm2ColProgramInfoLoader = (inferenceHandler, x, w, outputShape, attributes) => {
    const metadata = createPackedIm2ColProgramMetadata(attributes.cacheKey);
    return Object.assign(Object.assign({}, metadata), { get: () => createPackedIm2ColProgramInfo(inferenceHandler, metadata, x, w, outputShape, attributes) });
};
exports.createPackedIm2ColProgramInfoLoader = createPackedIm2ColProgramInfoLoader;


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/ops/im2col.ts":
/*!*************************************************!*\
  !*** ./lib/onnxjs/backends/webgl/ops/im2col.ts ***!
  \*************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.calculateIm2ColDims = exports.createIm2ColProgramInfoLoader = void 0;
const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
const createIm2ColProgramMetadata = (cacheHint) => ({
    name: 'Im2Col',
    inputNames: ['X'],
    inputTypes: [types_1.TextureType.unpacked],
    cacheHint,
});
const createIm2ColProgramInfo = (inferenceHandler, metadata, x, w, outputShape, attributes) => {
    const xshape = x.dims;
    const wshape = w.dims;
    const rank = outputShape.length;
    const im2colDims = (0, exports.calculateIm2ColDims)(xshape, wshape, outputShape, 4);
    const shaderSource = `
        const int XC = ${xshape[1]};
        const int XH = ${xshape[2]};
        const int XW = ${xshape[3]};
        const int KH = ${attributes.kernelShape[0]};
        const int KW = ${attributes.kernelShape[1]};
        const int dilationH = ${attributes.dilations[0]};
        const int dilationW = ${attributes.dilations[1]};
        const int strideH = ${attributes.strides[0]};
        const int strideW = ${attributes.strides[1]};
        const int padH = ${attributes.pads[0]};
        const int padW = ${attributes.pads[1]};
        const int KHKW = KH*KW;
        const int XCKHKW = XC * KHKW;
        const int outputChannels = 4;
        vec4 process(int indices[${rank}]) {
          int b  = indices[0]; // batch size
          int oh = indices[1] * strideH - padH; //output height
          int ow = indices[2] * strideW - padW; //output width
          int p = indices[3] * outputChannels; //patch
          vec4 value = vec4(0.0);
          for(int i=0; i < outputChannels; ++i) {
            if(p < XCKHKW) {
              int patchC = p / KHKW;
              int patchH = (p - patchC*KHKW) / KW;
              int patchW = (p - patchC*KHKW) - patchH * KW;
              int xh2 = oh + patchH * dilationH;
              int xw2 = ow + patchW * dilationW;
              int x[${xshape.length}];
              x[0] = b;
              x[1] = patchC;
              x[2] = xh2;
              x[3] = xw2;
              if(xh2 >= 0 &&
                  xh2 < XH &&
                  xw2 >= 0 &&
                  xw2 < XW) {
                value[i] = _X(x);
              }
            }
            ++p;
          }
          return value;
        }
        `;
    return Object.assign(Object.assign({}, metadata), { output: { dims: im2colDims, type: x.type, textureType: types_1.TextureType.packedLastDimension }, shaderSource });
};
const createIm2ColProgramInfoLoader = (inferenceHandler, x, w, outputShape, attributes) => {
    const metadata = createIm2ColProgramMetadata(attributes.cacheKey);
    return Object.assign(Object.assign({}, metadata), { get: () => createIm2ColProgramInfo(inferenceHandler, metadata, x, w, outputShape, attributes) });
};
exports.createIm2ColProgramInfoLoader = createIm2ColProgramInfoLoader;
const calculateIm2ColDims = (inputShape, kernelShape, outputShape, channels = 4) => [outputShape[0], outputShape[2], outputShape[3],
    Math.ceil(inputShape[1] * kernelShape[2] * kernelShape[3] / channels)];
exports.calculateIm2ColDims = calculateIm2ColDims;


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/ops/image-scaler.ts":
/*!*******************************************************!*\
  !*** ./lib/onnxjs/backends/webgl/ops/image-scaler.ts ***!
  \*******************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.parseImageScalerAttributes = exports.imageScaler = void 0;
const attribute_with_cache_key_1 = __webpack_require__(/*! ../../../attribute-with-cache-key */ "./lib/onnxjs/attribute-with-cache-key.ts");
const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
const imageScaler = (inferenceHandler, inputs, attributes) => {
    validateInputs(inputs);
    const output = inferenceHandler.run(createImageScalerProgramInfoLoader(inferenceHandler, inputs, attributes), inputs);
    return [output];
};
exports.imageScaler = imageScaler;
const parseImageScalerAttributes = (node) => {
    const scale = node.attributes.getFloat('scale');
    const bias = node.attributes.getFloats('bias');
    return (0, attribute_with_cache_key_1.createAttributeWithCacheKey)({ scale, bias });
};
exports.parseImageScalerAttributes = parseImageScalerAttributes;
const imageScalerProgramMetadata = {
    name: 'ImageScaler',
    inputNames: ['X'],
    inputTypes: [types_1.TextureType.unpacked],
};
const createImageScalerProgramInfo = (handler, metadata, inputs, attributes) => {
    const outputShape = inputs[0].dims.slice();
    const rank = outputShape.length;
    const getBiasMethod = createGetBiasMethod(attributes.bias.length);
    const shaderSource = `
      ${getBiasMethod}
      float process(int indices[${rank}]) {
        return _X(indices) * scale + getBias(bias, indices[1]);
      }`;
    return Object.assign(Object.assign({}, metadata), { output: { dims: outputShape, type: inputs[0].type, textureType: types_1.TextureType.unpacked }, variables: [
            { name: 'bias', type: 'float', arrayLength: attributes.bias.length, data: attributes.bias },
            { name: 'scale', type: 'float', data: attributes.scale }
        ], shaderSource });
};
const createImageScalerProgramInfoLoader = (handler, inputs, attributes) => {
    const metadata = Object.assign(Object.assign({}, imageScalerProgramMetadata), { cacheHint: attributes.cacheKey });
    return Object.assign(Object.assign({}, metadata), { get: () => createImageScalerProgramInfo(handler, metadata, inputs, attributes) });
};
const createGetBiasMethod = (numChannels) => {
    const codeLines = [`float getBias(float bias[${numChannels}], int channel) {`];
    for (let i = 0; i < numChannels; ++i) {
        if (i === 0) {
            codeLines.push('\t' +
                `if (channel == ${i}) { return bias[${i}]; }`);
        }
        else if (i === numChannels - 1) {
            codeLines.push('\t' +
                `else { return bias[${i}]; }`);
        }
        else {
            codeLines.push('\t' +
                `else if (channel == ${i}) { return bias[${i}]; }`);
        }
    }
    codeLines.push('\t' +
        '}');
    return codeLines.join('\n');
};
const validateInputs = (inputs) => {
    if (!inputs || inputs.length !== 1) {
        throw new Error('ImageScaler requires 1 input.');
    }
    if (inputs[0].dims.length !== 4) {
        throw new Error('Invalid input shape.');
    }
    if (inputs[0].type !== 'float32' && inputs[0].type !== 'float64') {
        throw new Error('Invalid input type.');
    }
};


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/ops/instance-normalization.ts":
/*!*****************************************************************!*\
  !*** ./lib/onnxjs/backends/webgl/ops/instance-normalization.ts ***!
  \*****************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.parseInstanceNormalizationAttributes = exports.instanceNormalization = void 0;
const glsl_source_1 = __webpack_require__(/*! ../glsl-source */ "./lib/onnxjs/backends/webgl/glsl-source.ts");
const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
const instanceNormalization = (inferenceHandler, inputs, epsilon) => {
    validateInputs(inputs);
    const meanAndVariance = inferenceHandler.run(createMeanAndVarianceProgramInfoLoader(inputs[0]), inputs);
    const output = inferenceHandler.run(createComputeOutputProgramInfoLoader(inferenceHandler, inputs[0], epsilon, meanAndVariance.dims), [inputs[0], meanAndVariance, inputs[1], inputs[2]]);
    return [output];
};
exports.instanceNormalization = instanceNormalization;
const parseInstanceNormalizationAttributes = (node) => node.attributes.getFloat('epsilon', 1e-5);
exports.parseInstanceNormalizationAttributes = parseInstanceNormalizationAttributes;
const meanAndVarianceProgramMetadata = {
    name: 'InstanceNormalization_MeanAndVariance',
    inputNames: ['X'],
    inputTypes: [types_1.TextureType.unpacked],
};
const createMeanAndVarianceProgramInfo = (metadata, input) => {
    const xDims = input.dims.slice();
    const channel = xDims[1];
    const channelSize = xDims[2] * xDims[3];
    const outputShape = [xDims[0], channel];
    const shaderSource = `
      vec4 process(int[2] indices) {
        vec4 v = vec4(0.0);
        int a[4];
        a[0] = indices[0];
        a[1] = indices[1];
        float temp = 0.0;
        for(int a2=0; a2<${xDims[2]}; a2++) {
          a[2] = a2;
          for(int a3=0; a3<${xDims[3]}; a3++) {
            a[3] = a3;
            float x = _X(a);
            temp += x;
          }
        }
        float mean = temp / float(${channelSize});
        temp = 0.0;
        for(int a2=0; a2<${xDims[2]}; a2++) {
          a[2] = a2;
          for(int a3=0; a3<${xDims[3]}; a3++) {
            a[3] = a3;
            float x = _X(a);
            temp += (x - mean) * (x - mean);
          }
        }
        v.r = mean;
        v.g = temp / float(${channelSize});

        return v;
      }`;
    return Object.assign(Object.assign({}, metadata), { output: { dims: outputShape, type: input.type, textureType: types_1.TextureType.packedLastDimension }, shaderSource });
};
const createMeanAndVarianceProgramInfoLoader = (input) => (Object.assign(Object.assign({}, meanAndVarianceProgramMetadata), { get: () => createMeanAndVarianceProgramInfo(meanAndVarianceProgramMetadata, input) }));
const computeOutputProgramMetadata = {
    name: 'InstanceNormalization_ComputeOutput',
    inputNames: ['X', 'MeanAndVariance', 'Scale', 'B'],
    inputTypes: [types_1.TextureType.unpacked, types_1.TextureType.packedLastDimension, types_1.TextureType.unpacked, types_1.TextureType.unpacked],
};
const createComputeOutputProgramInfo = (inferenceHandler, metadata, input, epsilon, meanAndVarianceShape) => {
    const glsl = (0, glsl_source_1.getGlsl)(inferenceHandler.session.backend.glContext.version);
    const [textureWidth, textureHeight] = inferenceHandler.calculateTextureWidthAndHeight(meanAndVarianceShape, types_1.TextureType.packedLastDimension);
    const [meanAndVarianceWidth, meanAndVarianceHeight] = [textureWidth / 4, textureHeight];
    const shaderSource = `
      vec4 get_MeanAndVariance(int[2] mv) {
        int offset = indicesToOffset_MeanAndVariance(mv);
        vec2 coords = offsetToCoords(offset, ${meanAndVarianceWidth}, ${meanAndVarianceHeight});
        return ${glsl.texture2D}(MeanAndVariance, coords);
      }

      float process(int[4] indices) {
        int mv[2];
        mv[0] = indices[0];
        mv[1] = indices[1];
        vec4 mean_and_variance = get_MeanAndVariance(mv);
        float mean = mean_and_variance.r;
        float variance = mean_and_variance.g;

        int sb[1];
        sb[0] = indices[1];
        float scale = _Scale(sb);
        float b = _B(sb);

        return scale * (_X(indices) - mean) / sqrt(variance + epsilon) + b;
      }`;
    return Object.assign(Object.assign({}, metadata), { output: { dims: input.dims, type: input.type, textureType: types_1.TextureType.unpacked }, variables: [{ name: 'epsilon', type: 'float', data: epsilon }], shaderSource });
};
const createComputeOutputProgramInfoLoader = (inferenceHandler, input, epsilon, meanAndVarianceShape) => {
    const metadata = Object.assign(Object.assign({}, computeOutputProgramMetadata), { cacheHint: `${epsilon}` });
    return Object.assign(Object.assign({}, metadata), { get: () => createComputeOutputProgramInfo(inferenceHandler, metadata, input, epsilon, meanAndVarianceShape) });
};
const validateInputs = (inputs) => {
    if (!inputs || inputs.length !== 3) {
        throw new Error('InstanceNormalization requires 3 inputs.');
    }
    const X = inputs[0];
    const scale = inputs[1];
    const B = inputs[2];
    // input should at least have three dimensions - N,C,dim1,...,dimn
    // other inputs can have only one dimensions
    if (X.dims.length < 3 || scale.dims.length !== 1 || B.dims.length !== 1) {
        throw new Error('Invalid input shape.');
    }
    if (scale.dims[0] !== X.dims[1] || B.dims[0] !== X.dims[1]) {
        throw new Error('Input shapes are mismatched.');
    }
    if ((X.type !== 'float32' && X.type !== 'float64') || (scale.type !== 'float32' && scale.type !== 'float64') ||
        (B.type !== 'float32' && B.type !== 'float64')) {
        throw new Error('Invalid input type.');
    }
    if (inputs[0].dims.length !== 4) {
        throw new Error('Only support 4-D input shape.');
    }
};


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/ops/matmul-pack.ts":
/*!******************************************************!*\
  !*** ./lib/onnxjs/backends/webgl/ops/matmul-pack.ts ***!
  \******************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.createPackedMatmulProgramInfoLoader = void 0;
const util_1 = __webpack_require__(/*! ../../../util */ "./lib/onnxjs/util.ts");
const glsl_source_1 = __webpack_require__(/*! ../glsl-source */ "./lib/onnxjs/backends/webgl/glsl-source.ts");
const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
const utils_1 = __webpack_require__(/*! ../utils */ "./lib/onnxjs/backends/webgl/utils.ts");
const fuse_utils_1 = __webpack_require__(/*! ./fuse-utils */ "./lib/onnxjs/backends/webgl/ops/fuse-utils.ts");
const matmul_1 = __webpack_require__(/*! ./matmul */ "./lib/onnxjs/backends/webgl/ops/matmul.ts");
const createPackedMatmulProgramMetadata = (hasBias, cacheHint) => ({
    name: 'MatMul (packed)',
    inputNames: hasBias ? ['A', 'B', 'Bias'] : ['A', 'B'],
    inputTypes: hasBias ? [types_1.TextureType.packed, types_1.TextureType.packed, types_1.TextureType.packed] :
        [types_1.TextureType.packed, types_1.TextureType.packed],
    cacheHint
});
const createPackedMatmulProgramInfo = (inferenceHandler, metadata, inputs, activationAttributes) => {
    const hasBias = inputs.length > 2;
    const processBias = hasBias ? 'value += getBiasForMatmul();' : '';
    const aShape = inputs[0].dims;
    const bShape = inputs[1].dims;
    const outputShape = util_1.BroadcastUtil.calcShape(aShape, bShape, true);
    const isBroadcast = !util_1.ShapeUtil.areEqual(inputs[0].dims, inputs[1].dims);
    if (!outputShape) {
        throw new Error('Can\'t use matmul on the given tensors');
    }
    const sharedDim = aShape[aShape.length - 1];
    const sharedDimIndex = Math.ceil(sharedDim / 2);
    const aRank = aShape.length;
    const bRank = bShape.length;
    const glsl = (0, glsl_source_1.getGlsl)(inferenceHandler.session.backend.glContext.version);
    const coordsDataType = (0, utils_1.getCoordsDataType)(outputShape.length);
    const outRank = outputShape.length;
    const allGlChannels = (0, utils_1.getGlChannels)();
    const { activationFunction, applyActivation } = (0, fuse_utils_1.getActivationSnippet)(activationAttributes);
    const getBiasForMatmulSnippet = hasBias ? `${(0, matmul_1.getBiasForMatmul)(coordsDataType, allGlChannels, inputs[2].dims, outputShape, true)}` : '';
    const getBcastedSamplerForMatmulSnippet = isBroadcast ? `${getBcastSamplerForMatmul(coordsDataType, allGlChannels, inputs, outputShape)}` : '';
    const getSamplerAInLoopSnippet = isBroadcast ? 'getAAtOutCoordsMatmul(i)' : `getA(${getA(allGlChannels, aRank)})`;
    const getSamplerBInLoopSnippet = isBroadcast ? 'getBAtOutCoordsMatmul(i)' : `getB(${getB(allGlChannels, bRank)})`;
    const getOutputCoordsSnippet = isBroadcast ? '' : `${coordsDataType} rc =
          getOutputCoords(); int lastDim = rc.${allGlChannels[outRank - 1]}; rc.${allGlChannels[outRank - 1]} =
          rc.${allGlChannels[outRank - 2]}; rc.${allGlChannels[outRank - 2]} = lastDim;
      `;
    const shaderSource = `
            ${getBcastedSamplerForMatmulSnippet}
            ${getBiasForMatmulSnippet}
            ${activationFunction}
            void main() {
              ${getOutputCoordsSnippet}

              vec4 value = vec4(0);
              for (int i = 0; i < ${sharedDimIndex}; i++) {
                vec4 a = ${getSamplerAInLoopSnippet};
                vec4 b = ${getSamplerBInLoopSnippet};

                value += (a.rrbb * b.rgrg);
                value += (a.ggaa * b.baba);
              }
              ${processBias}
              ${applyActivation}
              ${glsl.output} = value;
            }`;
    return Object.assign(Object.assign({}, metadata), { output: { dims: outputShape, type: inputs[0].type, textureType: types_1.TextureType.packed }, shaderSource, hasMain: true });
};
const createPackedMatmulProgramInfoLoader = (inferenceHandler, inputs, activationAttributes) => {
    const metadata = createPackedMatmulProgramMetadata(inputs.length > 2, activationAttributes.activationCacheKey);
    return Object.assign(Object.assign({}, metadata), { get: () => createPackedMatmulProgramInfo(inferenceHandler, metadata, inputs, activationAttributes) });
};
exports.createPackedMatmulProgramInfoLoader = createPackedMatmulProgramInfoLoader;
function getBcastSamplerForMatmul(coordsDataType, allGlChannels, inputs, outShape) {
    let unpackedACoordsSnippet = [];
    let unpackedBCoordsSnippet = [];
    const inAShape = inputs[0].dims;
    const inBShape = inputs[1].dims;
    const inARank = inAShape.length;
    const inBRank = inBShape.length;
    const outRank = outShape.length;
    const rankADiff = outRank - inARank;
    const rankBDiff = outRank - inBRank;
    unpackedACoordsSnippet = inAShape.map((s, i) => `coords.${allGlChannels[i + rankADiff]}`);
    unpackedACoordsSnippet[inARank - 1] = 'i*2';
    unpackedACoordsSnippet.join(', ');
    unpackedBCoordsSnippet = inBShape.map((s, i) => `coords.${allGlChannels[i + rankBDiff]}`);
    unpackedBCoordsSnippet[inBRank - 2] = 'i*2';
    unpackedBCoordsSnippet.join(', ');
    const broadcastADims = util_1.BroadcastUtil.getBroadcastDims(inAShape, outShape);
    const broadcastBDims = util_1.BroadcastUtil.getBroadcastDims(inBShape, outShape);
    const coordsASnippet = broadcastADims.map(d => `coords.${allGlChannels[d + rankADiff]} = 0;`).join('\n');
    const coordsBSnippet = broadcastBDims.map(d => `coords.${allGlChannels[d + rankBDiff]} = 0;`).join('\n');
    const swapDimSnippet = `int lastDim = coords.${allGlChannels[outRank - 1]};
  coords.${allGlChannels[outRank - 1]} = coords.${allGlChannels[outRank - 2]};
  coords.${allGlChannels[outRank - 2]} = lastDim;`;
    const getBcastSamplerMatmulSource = `
vec4 getAAtOutCoordsMatmul(int i) {
  ${coordsDataType} coords = getOutputCoords();
  ${swapDimSnippet}
  ${coordsASnippet}
  vec4 outputValue = getA(${unpackedACoordsSnippet});
  return outputValue;
}

vec4 getBAtOutCoordsMatmul(int i) {
  ${coordsDataType} coords = getOutputCoords();
  ${swapDimSnippet}
  ${coordsBSnippet}
  vec4 outputValue = getB(${unpackedBCoordsSnippet});
  return outputValue;
}`;
    return getBcastSamplerMatmulSource;
}
function getA(allGlChannels, rank) {
    let res = '';
    for (let i = 0; i < rank - 2; i++) {
        res += `rc.${allGlChannels[i]}, `;
    }
    res += `rc.${allGlChannels[rank - 2]}, ` +
        'i*2';
    return res;
}
function getB(allGlChannels, rank) {
    let res = '';
    for (let i = 0; i < rank - 2; i++) {
        res += `rc.${allGlChannels[i]}, `;
    }
    res += 'i*2, ' +
        `rc.${allGlChannels[rank - 1]}`;
    return res;
}


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/ops/matmul.ts":
/*!*************************************************!*\
  !*** ./lib/onnxjs/backends/webgl/ops/matmul.ts ***!
  \*************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getBiasForMatmul = exports.createMatmulProgramInfoLoader = exports.parseMatMulAttributes = exports.matMul = void 0;
const util_1 = __webpack_require__(/*! ../../../util */ "./lib/onnxjs/util.ts");
const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
const utils_1 = __webpack_require__(/*! ../utils */ "./lib/onnxjs/backends/webgl/utils.ts");
const fuse_utils_1 = __webpack_require__(/*! ./fuse-utils */ "./lib/onnxjs/backends/webgl/ops/fuse-utils.ts");
const matmul_pack_1 = __webpack_require__(/*! ./matmul-pack */ "./lib/onnxjs/backends/webgl/ops/matmul-pack.ts");
const matMul = (inferenceHandler, inputs, attributes) => {
    validateInputs(inputs);
    if (inferenceHandler.session.pack) {
        return [inferenceHandler.run((0, matmul_pack_1.createPackedMatmulProgramInfoLoader)(inferenceHandler, inputs, attributes), inputs)];
    }
    else {
        return [inferenceHandler.run(createMatmulProgramInfoLoader(inputs, attributes), inputs)];
    }
};
exports.matMul = matMul;
const parseMatMulAttributes = (node) => (0, fuse_utils_1.parseInternalActivationAttributes)(node.attributes);
exports.parseMatMulAttributes = parseMatMulAttributes;
const createMatmulProgramMetadata = (hasBias, cacheHint) => ({
    name: 'MatMul',
    inputNames: hasBias ? ['A', 'B', 'Bias'] : ['A', 'B'],
    inputTypes: hasBias ? [types_1.TextureType.unpacked, types_1.TextureType.unpacked, types_1.TextureType.unpacked] :
        [types_1.TextureType.unpacked, types_1.TextureType.unpacked],
    cacheHint
});
function createMatmulProgramInfo(metadata, inputs, activationAttributes) {
    const aShape = inputs[0].dims;
    const bShape = inputs[1].dims;
    const outputShape = util_1.BroadcastUtil.calcShape(aShape, bShape, true);
    if (!outputShape) {
        throw new Error('Can\'t use matmul on the given tensors');
    }
    const coordsDataType = (0, utils_1.getCoordsDataType)(outputShape.length);
    const allGlChannels = (0, utils_1.getGlChannels)();
    const { activationFunction, applyActivation } = (0, fuse_utils_1.getActivationSnippet)(activationAttributes);
    const hasBias = inputs.length > 2;
    const processBias = hasBias ? 'value += getBiasForMatmul();' : '';
    const getBiasForMatmulSnippet = hasBias ? `${getBiasForMatmul(coordsDataType, allGlChannels, inputs[2].dims, outputShape, false)}` : '';
    const rank = outputShape.length;
    const arank = aShape.length;
    const brank = bShape.length;
    const sharedDim = aShape[aShape.length - 1];
    const shaderSource = `
    ${activationFunction}
    ${getBiasForMatmulSnippet}
    float process(int indices[${rank}]) {
        int a[${arank}];
        int b[${brank}];
        bcastMatmulIndices_A(indices, a);
        bcastMatmulIndices_B(indices, b);

        float value;
        for (int k=0; k<${sharedDim}; ++k) {
            a[${arank - 1}] = k;
            b[${brank - 2}] = k;
            value += _A(a) * _B(b);
        }
        ${processBias}
        ${applyActivation}
        return value;
    }`;
    return Object.assign(Object.assign({}, metadata), { output: { dims: outputShape, type: inputs[0].type, textureType: types_1.TextureType.unpacked }, shaderSource });
}
function createMatmulProgramInfoLoader(inputs, activationAttributes) {
    const metadata = createMatmulProgramMetadata(inputs.length > 2, activationAttributes.activationCacheKey);
    return Object.assign(Object.assign({}, metadata), { get: () => createMatmulProgramInfo(metadata, inputs, activationAttributes) });
}
exports.createMatmulProgramInfoLoader = createMatmulProgramInfoLoader;
const validateInputs = (inputs) => {
    if (!inputs || inputs.length !== 2) {
        throw new Error('MatMul requires 2 inputs.');
    }
    if (inputs[0].dims[inputs[0].dims.length - 1] !== inputs[1].dims[inputs[1].dims.length - 2]) {
        throw new Error('shared dimension does not match.');
    }
    if ((inputs[0].type !== 'float32' && inputs[0].type !== 'float64') ||
        (inputs[1].type !== 'float32' && inputs[1].type !== 'float64')) {
        throw new Error('inputs should be float type');
    }
    if (inputs[0].type !== inputs[1].type) {
        throw new Error('inputs types should match');
    }
};
function getBiasForMatmul(coordsDataType, allGlChannels, inShape, outShape, isPacked) {
    let unpackedCoordsSnippet = '';
    const inRank = inShape.length;
    const outRank = outShape.length;
    const rankDiff = outRank - inRank;
    if (outRank < 2 && inRank > 0) {
        unpackedCoordsSnippet = 'coords';
    }
    else {
        unpackedCoordsSnippet = inShape.map((s, i) => `coords.${allGlChannels[i + rankDiff]}`).join(', ');
    }
    const broadcastDims = util_1.BroadcastUtil.getBroadcastDims(inShape, outShape);
    const coordsSnippet = broadcastDims.map(d => `coords.${allGlChannels[d + rankDiff]} = 0;`).join('\n');
    const inSize = util_1.ShapeUtil.size(inShape);
    const isInputScalar = inSize === 1;
    let output = 'vec4(outputValue.xx, outputValue.yy)';
    if (isInputScalar) {
        output = 'vec4(outputValue.x)';
    }
    const getBiasForMatmulSource = isPacked ? `
vec4 getBiasForMatmul() {
  ${coordsDataType} coords = getOutputCoords();
  ${coordsSnippet}
  vec4 outputValue = getBias(${unpackedCoordsSnippet});
  return ${output};
}` :
        `
float getBiasForMatmul() {
  ${coordsDataType} coords = getOutputCoords();
  ${coordsSnippet}
  return getBias(coords.x);
}`;
    return getBiasForMatmulSource;
}
exports.getBiasForMatmul = getBiasForMatmul;


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/ops/pack.ts":
/*!***********************************************!*\
  !*** ./lib/onnxjs/backends/webgl/ops/pack.ts ***!
  \***********************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.createPackProgramInfoLoader = void 0;
const glsl_source_1 = __webpack_require__(/*! ../glsl-source */ "./lib/onnxjs/backends/webgl/glsl-source.ts");
const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
const utils_1 = __webpack_require__(/*! ../utils */ "./lib/onnxjs/backends/webgl/utils.ts");
const packing_utils_1 = __webpack_require__(/*! ./packing-utils */ "./lib/onnxjs/backends/webgl/ops/packing-utils.ts");
const packProgramMetadata = {
    name: 'pack',
    inputNames: ['A'],
    inputTypes: [types_1.TextureType.unpackedReversed]
};
const createPackProgramInfo = (handler, input) => {
    const glsl = (0, glsl_source_1.getGlsl)(handler.session.backend.glContext.version);
    const inputShape = input.dims;
    const inputRank = inputShape.length;
    // createTextureLayoutFromShape won't change output rank. Need to verify by running tests
    const outputRank = input.dims.length;
    const coordsDataType = (0, utils_1.getCoordsDataType)(outputRank);
    const channels = (0, packing_utils_1.getChannels)('rc', outputRank);
    const setup = getSetup(outputRank, channels, inputShape[inputShape.length - 2], inputShape[inputShape.length - 1]);
    let reversedInputWH;
    if (inputRank === 0) {
        reversedInputWH = [1, 1];
    }
    else if (inputRank === 1) {
        reversedInputWH = [inputShape[0], 1];
    }
    else {
        reversedInputWH = [inputShape[outputRank - 1], inputShape[outputRank - 2]];
    }
    const outOfBoundsCondition = getOutOfBoundsCondition(outputRank, reversedInputWH, channels);
    const output = getOutput(inputShape, channels);
    const shaderSource = `
        void main() {
          ${coordsDataType} rc = getOutputCoords();

          if(${outOfBoundsCondition}) {
            ${glsl.output} = vec4(0);
          } else {
            ${setup}

            ${glsl.output} = vec4(${output});
          }
        }
      `;
    return Object.assign(Object.assign({}, packProgramMetadata), { hasMain: true, output: { dims: input.dims, type: input.type, textureType: types_1.TextureType.packed }, shaderSource });
};
const createPackProgramInfoLoader = (handler, input) => (Object.assign(Object.assign({}, packProgramMetadata), { get: () => createPackProgramInfo(handler, input) }));
exports.createPackProgramInfoLoader = createPackProgramInfoLoader;
/**
 * check output coordinate location and return false if it is outside input's width/height boundary
 */
function getOutOfBoundsCondition(rank, shape, dims) {
    if (rank === 0) {
        return 'false';
    }
    if (rank === 1) {
        return `rc > ${shape[0]}`;
    }
    let cond = '';
    for (let i = rank - 2; i < rank; i++) {
        cond += `${dims[i]} >= ${shape[i - rank + 2]}`;
        if (i < rank - 1) {
            cond += '||';
        }
    }
    return cond;
}
/**
 * code snippet to sample input texture with output coordiantes
 */
function getOutput(shape, dims) {
    const rank = shape.length;
    if (rank === 0) {
        return 'getA(), 0, 0, 0';
    }
    if (rank === 1) {
        return `getA(rc),
            rc + 1 >= ${shape[0]} ? 0. : getA(rc + 1),
            0, 0`;
    }
    const coord00 = 'r, c';
    const coord01 = 'r, cp1';
    const coord10 = 'rp1, c';
    const coord11 = 'rp1, cp1';
    let D = '';
    if (rank > 2) {
        for (let i = 0; i < rank - 2; ++i) {
            D = D + `${dims[i]},`;
        }
    }
    return `getA(${D}${coord00}),
          rEdge ? 0. : getA(${D}${coord10}),
          cEdge ? 0. : getA(${D}${coord01}),
          rEdge || cEdge ? 0. : getA(${D}${coord11})`;
}
/**
 * code snippet to setup 4 coordinates and edge conditions
 */
function getSetup(rank, dims, rows, cols) {
    if (rank === 0 || rank === 1) {
        return '';
    }
    // rank >= 2 for width+height pack.
    else {
        const setup = `
    int r = ${dims[rank - 2]};
    int c = ${dims[rank - 1]};
    int rp1 = ${dims[rank - 2]} + 1;
    int cp1 = ${dims[rank - 1]} + 1;
    bool rEdge = rp1 >= ${cols};
    bool cEdge = cp1 >= ${rows};
    `;
        return setup;
    }
}


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/ops/packing-utils.ts":
/*!********************************************************!*\
  !*** ./lib/onnxjs/backends/webgl/ops/packing-utils.ts ***!
  \********************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.unpackFromChannel = exports.getChannels = exports.getVecChannels = void 0;
const utils_1 = __webpack_require__(/*! ../utils */ "./lib/onnxjs/backends/webgl/utils.ts");
function getVecChannels(name, rank) {
    return (0, utils_1.getGlChannels)(rank).map(d => `${name}.${d}`);
}
exports.getVecChannels = getVecChannels;
function getChannels(name, rank) {
    if (rank === 1) {
        return [name];
    }
    return getVecChannels(name, rank);
}
exports.getChannels = getChannels;
function unpackFromChannel() {
    return `
    float getChannel(vec4 frag, int dim) {
      int modCoord = imod(dim, 2);
      return modCoord == 0 ? frag.r : frag.g;
    }

    float getChannel(vec4 frag, vec2 innerDims) {
      vec2 modCoord = mod(innerDims, 2.);
      return modCoord.x == 0. ?
        (modCoord.y == 0. ? frag.r : frag.g) :
        (modCoord.y == 0. ? frag.b : frag.a);
    }
  `;
}
exports.unpackFromChannel = unpackFromChannel;


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/ops/pad.ts":
/*!**********************************************!*\
  !*** ./lib/onnxjs/backends/webgl/ops/pad.ts ***!
  \**********************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.parsePadAttributesV11 = exports.padV11 = exports.parsePadAttributesV2 = exports.padV2 = void 0;
const attribute_with_cache_key_1 = __webpack_require__(/*! ../../../attribute-with-cache-key */ "./lib/onnxjs/attribute-with-cache-key.ts");
const util_1 = __webpack_require__(/*! ../../../util */ "./lib/onnxjs/util.ts");
const glsl_source_1 = __webpack_require__(/*! ../glsl-source */ "./lib/onnxjs/backends/webgl/glsl-source.ts");
const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
const padProgramMetadata = {
    name: 'Pad',
    inputNames: ['A'],
    inputTypes: [types_1.TextureType.unpacked],
};
const padV2 = (inferenceHandler, inputs, attributes) => {
    validateInputsV2(inputs);
    const output = inferenceHandler.run(Object.assign(Object.assign({}, padProgramMetadata), { cacheHint: attributes.cacheKey, get: () => createPadProgramInfo(inferenceHandler, inputs[0], attributes) }), inputs);
    return [output];
};
exports.padV2 = padV2;
const parsePadAttributesV2 = (node) => {
    const mode = node.attributes.getString('mode', 'constant');
    const value = node.attributes.getFloat('value', 0.0);
    const pads = node.attributes.getInts('pads');
    return (0, attribute_with_cache_key_1.createAttributeWithCacheKey)({ mode, value, pads });
};
exports.parsePadAttributesV2 = parsePadAttributesV2;
const padV11 = (inferenceHandler, inputs, mode) => {
    validateInputsV11(inputs);
    const attrubutes = generatePadAttributesFromInputs(inferenceHandler, inputs, mode);
    return (0, exports.padV2)(inferenceHandler, [inputs[0]], attrubutes);
};
exports.padV11 = padV11;
const parsePadAttributesV11 = (node) => node.attributes.getString('mode', 'constant');
exports.parsePadAttributesV11 = parsePadAttributesV11;
const generatePadAttributesFromInputs = (inferenceHandler, inputs, mode) => {
    if (!inferenceHandler.session.isInitializer(inputs[1].dataId) ||
        (inputs.length >= 3 && !inferenceHandler.session.isInitializer(inputs[2].dataId))) {
        throw new Error('dynamic pad attributes are not allowed');
    }
    const pads = Array.from(inputs[1].integerData);
    const value = (inputs.length >= 3) ? inputs[2].floatData[0] : 0.0;
    return (0, attribute_with_cache_key_1.createAttributeWithCacheKey)({ mode, pads, value });
};
const createPadProgramInfo = (inferenceHandler, input, attributes) => {
    const outputShape = util_1.ShapeUtil.padShape(input.dims.slice(), attributes.pads);
    const rank = outputShape.length;
    const padFunction = getPadFunction(inferenceHandler, input, attributes);
    const shaderSource = `
      ${padFunction}
      float process(int[${rank}] indices) {
          return padA(indices);
      }`;
    return {
        name: 'Pad',
        inputNames: ['A'],
        inputTypes: [types_1.TextureType.unpacked],
        output: { dims: outputShape, type: input.type, textureType: types_1.TextureType.unpacked },
        shaderSource
    };
};
const validateInputsV2 = (inputs) => {
    if (!inputs || inputs.length !== 1) {
        throw new Error('Pad requires 1 input');
    }
    if (inputs[0].type !== 'float32' && inputs[0].type !== 'float64') {
        throw new Error('Invalid input type.');
    }
};
const validateInputsV11 = (inputs) => {
    if (!inputs || (inputs.length !== 2 && inputs.length !== 3)) {
        throw new Error('Pad requires 2 or 3 inputs');
    }
    if (inputs[1].type !== 'int32') {
        throw new Error('Invalid input type.');
    }
    if (inputs.length >= 3 && inputs[2].type === 'string') {
        throw new Error('Invalid input type.');
    }
};
const getPadFunction = (inferenceHandler, input, attributes) => {
    const glsl = (0, glsl_source_1.getGlsl)(inferenceHandler.session.backend.glContext.version);
    const [width, height] = inferenceHandler.calculateTextureWidthAndHeight(input.dims, types_1.TextureType.unpacked);
    const strides = util_1.ShapeUtil.computeStrides(input.dims);
    switch (attributes.mode) {
        case 'constant':
            return getPadConstant(glsl, input.dims, strides, width, height, attributes.pads, attributes.value);
        case 'reflect':
            return getPadReflect(glsl, input.dims, strides, width, height, attributes.pads);
        case 'edge':
            return getPadEdge(glsl, input.dims, strides, width, height, attributes.pads);
        default:
            throw new Error('Invalid mode');
    }
};
const getPadConstant = (glsl, shape, strides, width, height, pads, value) => {
    const rank = shape.length;
    let block = '';
    for (let i = rank - 1; i >= 0; --i) {
        block += `
        k = m[${i}] - ${pads[i]};
        if (k < 0)  return constant;
        if (k >= ${shape[i]}) return constant;
        offset += k * ${strides[i]};
        `;
    }
    return `
      float padA(int m[${rank}]) {
        const float constant = float(${value});
        int offset = 0;
        int k = 0;
        ${block}
        vec2 coords = offsetToCoords(offset, ${width}, ${height});
        float value = getColorAsFloat(${glsl.texture2D}(A, coords));
        return value;
      }
      `;
};
const getPadReflect = (glsl, shape, strides, width, height, pads) => {
    const rank = shape.length;
    let block = '';
    for (let i = rank - 1; i >= 0; --i) {
        block += `
        k = m[${i}] - ${pads[i]};
        if (k < 0) { k = -k; }
        {
          const int _2n_1 = ${2 * (shape[i] - 1)};
          k = int( mod( float(k), float(_2n_1) ) ) ;
          if(k >= ${shape[i]}) { k = _2n_1 - k; }
        }
        offset += k * ${strides[i]};
        `;
    }
    return `
      float padA(int m[${rank}]) {
        int offset = 0;
        int k = 0;
        ${block}
        vec2 coords = offsetToCoords(offset, ${width}, ${height});
        float value = getColorAsFloat(${glsl.texture2D}(A, coords));
        return value;
      }
      `;
};
const getPadEdge = (glsl, shape, strides, width, height, pads) => {
    const rank = shape.length;
    let block = '';
    for (let i = rank - 1; i >= 0; --i) {
        block += `
        k = m[${i}] - ${pads[i]};
        if (k < 0)  k = 0;
        if (k >= ${shape[i]}) k = ${shape[i] - 1};
        offset += k * ${strides[i]};
      `;
    }
    return `
      float padA(int m[${rank}]) {
        int offset = 0;
        int k = 0;
        ${block}
        vec2 coords = offsetToCoords(offset, ${width}, ${height});
        float value = getColorAsFloat(${glsl.texture2D}(A, coords));
        return value;
      }
      `;
};


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/ops/pool.ts":
/*!***********************************************!*\
  !*** ./lib/onnxjs/backends/webgl/ops/pool.ts ***!
  \***********************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.globalMaxPool = exports.parseMaxPoolAttributes = exports.maxPool = exports.parseGlobalAveragePoolAttributes = exports.globalAveragePool = exports.parseAveragePoolAttributes = exports.averagePool = void 0;
const attribute_with_cache_key_1 = __webpack_require__(/*! ../../../attribute-with-cache-key */ "./lib/onnxjs/attribute-with-cache-key.ts");
const util_1 = __webpack_require__(/*! ../../../util */ "./lib/onnxjs/util.ts");
const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
const averagePool = (inferenceHandler, inputs, attributes) => {
    validateInputs(inputs);
    const metadata = { name: 'AveragePool', inputNames: ['X'], inputTypes: [types_1.TextureType.unpacked], cacheHint: attributes.cacheKey };
    const output = inferenceHandler.run(Object.assign(Object.assign({}, metadata), { get: () => createAveragePoolProgramInfo(inputs, metadata, false, attributes) }), inputs);
    return [output];
};
exports.averagePool = averagePool;
const parseAveragePoolAttributes = (node) => {
    const autoPad = node.attributes.getString('auto_pad', 'NOTSET');
    const ceilMode = node.attributes.getInt('ceil_mode', 0);
    const countIncludePad = (node.attributes.getInt('count_include_pad', 0) === 0 ? false : true);
    const kernelShape = node.attributes.getInts('kernel_shape');
    const strides = node.attributes.getInts('strides', []);
    const pads = node.attributes.getInts('pads', []);
    // TODO: support attribute 'ceil_mode'
    if (ceilMode !== 0) {
        throw new Error('using ceil() in shape computation is not yet supported for AveragePool');
    }
    return (0, attribute_with_cache_key_1.createAttributeWithCacheKey)({ autoPad, ceilMode, countIncludePad, kernelShape, strides, pads });
};
exports.parseAveragePoolAttributes = parseAveragePoolAttributes;
const createAveragePoolProgramInfo = (inputs, metadata, isGlobalOperator, attributes) => {
    const [adjustedAttributes, outputShape] = getAdjustedPoolAttributesAndOutputShape(inputs, attributes, isGlobalOperator);
    const kernelSize = util_1.ShapeUtil.size(adjustedAttributes.kernelShape);
    const op1 = 'value += _X(x);';
    let op2 = '';
    if (adjustedAttributes.countIncludePad) {
        op2 += `value /= float(${kernelSize});`;
    }
    else {
        op2 += `value /= float(${kernelSize} - pad);`;
    }
    const poolingCode = generatePoolingCode(inputs[0].dims, adjustedAttributes, op1, op2, '0.0');
    const shaderSource = `
        ${poolingCode}
      `;
    return Object.assign(Object.assign({}, metadata), { output: { dims: outputShape, type: inputs[0].type, textureType: types_1.TextureType.unpacked }, shaderSource });
};
const globalAveragePool = (inferenceHandler, inputs, attributes) => {
    validateInputs(inputs);
    const metadata = {
        name: 'GlobalAveragePool',
        inputNames: ['X'],
        inputTypes: [types_1.TextureType.unpacked],
        cacheHint: `${attributes.countIncludePad}`
    };
    const output = inferenceHandler.run(Object.assign(Object.assign({}, metadata), { get: () => createAveragePoolProgramInfo(inputs, metadata, true, attributes) }), inputs);
    return [output];
};
exports.globalAveragePool = globalAveragePool;
const parseGlobalAveragePoolAttributes = (node) => {
    const countIncludePad = (node.attributes.getInt('count_include_pad', 0) === 0 ? false : true);
    return (0, attribute_with_cache_key_1.createAttributeWithCacheKey)({ autoPad: '', ceilMode: 0, countIncludePad, kernelShape: [], strides: [], pads: [] });
};
exports.parseGlobalAveragePoolAttributes = parseGlobalAveragePoolAttributes;
const maxPool = (inferenceHandler, inputs, attributes) => {
    validateInputs(inputs);
    const metadata = { name: 'MaxPool', inputNames: ['X'], inputTypes: [types_1.TextureType.unpacked], cacheHint: attributes.cacheKey };
    const output = inferenceHandler.run(Object.assign(Object.assign({}, metadata), { get: () => createMaxPoolProgramInfo(inputs, metadata, false, attributes) }), inputs);
    return [output];
};
exports.maxPool = maxPool;
const parseMaxPoolAttributes = (node) => {
    const autoPad = node.attributes.getString('auto_pad', 'NOTSET');
    const ceilMode = node.attributes.getInt('ceil_mode', 0);
    const kernelShape = node.attributes.getInts('kernel_shape');
    const strides = node.attributes.getInts('strides', []);
    const pads = node.attributes.getInts('pads', []);
    const storageOrder = node.attributes.getInt('storage_order', 0);
    const dilations = node.attributes.getInts('dilations', []);
    // TODO: support attribute 'ceil_mode' and 'storage_order'
    if (storageOrder !== 0) {
        throw new Error('column major storage order is not yet supported for MaxPool');
    }
    if (ceilMode !== 0) {
        throw new Error('using ceil() in shape computation is not yet supported for MaxPool');
    }
    return (0, attribute_with_cache_key_1.createAttributeWithCacheKey)({ autoPad, ceilMode, countIncludePad: false, kernelShape, strides, pads, storageOrder, dilations });
};
exports.parseMaxPoolAttributes = parseMaxPoolAttributes;
const createMaxPoolProgramInfo = (inputs, metadata, isGlobalOperator, attributes) => {
    const [adjustedAttributes, outputShape] = getAdjustedPoolAttributesAndOutputShape(inputs, attributes, isGlobalOperator);
    const op1 = `
      value = max(_X(x), value);
    `;
    const op2 = '';
    const poolingCode = generatePoolingCode(inputs[0].dims, adjustedAttributes, op1, op2, '-1e5');
    const shaderSource = `
      ${poolingCode}
    `;
    return Object.assign(Object.assign({}, metadata), { output: { dims: outputShape, type: inputs[0].type, textureType: types_1.TextureType.unpacked }, shaderSource });
};
const getAdjustedPoolAttributesAndOutputShape = (inputs, attributes, isGlobalOperator) => {
    const inputShape = inputs[0].dims.slice();
    const hasDilations = Object.hasOwnProperty.call(attributes, 'dilations');
    const kernelShape = attributes.kernelShape.slice();
    const strides = attributes.strides.slice();
    const dilations = hasDilations ? attributes.dilations.slice() : [];
    const pads = attributes.pads.slice();
    util_1.PoolConvUtil.adjustPoolAttributes(isGlobalOperator, inputShape, kernelShape, strides, dilations, pads);
    const outputShape = util_1.PoolConvUtil.computePoolOutputShape(isGlobalOperator, inputShape, strides, dilations, kernelShape, pads, attributes.autoPad);
    const newAttributes = Object.assign({}, attributes);
    if (hasDilations) {
        Object.assign(newAttributes, { kernelShape, strides, pads, dilations, cacheKey: attributes.cacheKey });
    }
    else {
        Object.assign(newAttributes, { kernelShape, strides, pads, cacheKey: attributes.cacheKey });
    }
    return [newAttributes, outputShape];
};
const globalMaxPoolAttributes = {
    autoPad: '',
    ceilMode: 0,
    countIncludePad: false,
    kernelShape: [],
    strides: [],
    pads: [],
    storageOrder: 0,
    dilations: [],
    cacheKey: ''
};
const globalMaxPoolMetadata = {
    name: 'GlobalMaxPool',
    inputNames: ['X'],
    inputTypes: [types_1.TextureType.unpacked]
};
const globalMaxPool = (inferenceHandler, inputs) => {
    validateInputs(inputs);
    const output = inferenceHandler.run(Object.assign(Object.assign({}, globalMaxPoolMetadata), { get: () => createMaxPoolProgramInfo(inputs, globalMaxPoolMetadata, true, globalMaxPoolAttributes) }), inputs);
    return [output];
};
exports.globalMaxPool = globalMaxPool;
const validateInputs = (inputs) => {
    if (!inputs || inputs.length !== 1) {
        throw new Error('Pool ops requires 1 input.');
    }
    if (inputs[0].type !== 'float32' && inputs[0].type !== 'float64') {
        throw new Error('Invalid input type.');
    }
};
const generatePoolingCode = (inputDims, attributes, op1, op2, start) => {
    const rank = inputDims.length;
    if (attributes.kernelShape.length <= 2) {
        const kw = attributes.kernelShape[attributes.kernelShape.length - 1];
        const sw = attributes.strides[attributes.strides.length - 1];
        const pwStart = attributes.pads[attributes.pads.length / 2 - 1];
        const pwEnd = attributes.pads[attributes.pads.length - 1];
        const dimW = inputDims[rank - 1];
        let codeW = '';
        let codeH = '';
        let codeHEnd = '';
        if (pwStart + pwEnd !== 0) {
            codeW = `
          for (int i = 0; i < ${kw}; i++) {
            x[${rank} - 1] = indices[${rank} - 1] * ${sw} - ${pwStart} + i;
            if (x[${rank} - 1] < 0 || x[${rank} - 1] >= ${dimW}) {
              pad++;
              continue;
            }
            ${op1}
          }`;
        }
        else {
            codeW = `
          for (int i = 0; i < ${kw}; i++) {
            x[${rank} - 1] = indices[${rank} - 1] * ${sw} - ${pwStart} + i;
            ${op1}
          }`;
        }
        if (attributes.kernelShape.length === 2) {
            const kh = attributes.kernelShape[attributes.kernelShape.length - 2];
            const sh = attributes.strides[attributes.strides.length - 2];
            const phStart = attributes.pads[attributes.pads.length / 2 - 2];
            const phEnd = attributes.pads[attributes.pads.length - 2];
            const dimH = inputDims[rank - 2];
            if (phStart + phEnd !== 0) {
                codeH = `
            for (int j = 0; j < ${kh}; j++) {
              x[${rank} - 2] = indices[${rank} - 2] * ${sh} - ${phStart} + j;
              if (x[${rank} - 2] < 0 || x[${rank} - 2] >= ${dimH}) {
                pad+= ${kw};
                continue;
              }
          `;
            }
            else {
                codeH = `
            for (int j = 0; j < ${kh}; j++) {
              x[${rank} - 2] = indices[${rank} - 2] * ${sh} - ${phStart} + j;
            `;
            }
            codeHEnd = `
          }
        `;
        }
        const poolingCode = `
        float process(int indices[${rank}]) {
          int x[${rank}];
          copyVec(indices, x);

          float value = ${start};
          int pad = 0;
          ${codeH}
          ${codeW}
          ${codeHEnd}
          ${op2}
          return value;
        }
      `;
        return poolingCode;
    }
    else {
        const kernelSize = util_1.ShapeUtil.size(attributes.kernelShape);
        const kernelStrides = util_1.ShapeUtil.computeStrides(attributes.kernelShape);
        const stridesRank = kernelStrides.length;
        const padsRank = attributes.pads.length;
        const offsetToIndicesFunction = offsetToIndices(stridesRank);
        const copyInputDims = copyArray(inputDims, 'inputDims');
        const copyPads = copyArray(attributes.pads, 'pads');
        const copyKernelStrides = copyArray(kernelStrides, 'kernelStrides');
        const copyStrides = copyArray(attributes.strides, 'strides');
        const hasPads = attributes.pads.reduce((sum, cur) => sum + cur);
        let padCode = '';
        if (hasPads) {
            padCode = `
            if (x[j] >= inputDims[j] || x[j] < 0) {
              pad++;
              isPad = true;
              break;
            }
          }
          if (!isPad) {
            ${op1}
          }`;
        }
        else {
            padCode = `
          }
          ${op1}
        `;
        }
        const poolingCode = `
        ${offsetToIndicesFunction}
        float process(int indices[${rank}]) {
          int x[${rank}];
          copyVec(indices, x);
          int offset[${stridesRank}];
          int pads[${padsRank}];
          int inputDims[${rank}];
          int kernelStrides[${stridesRank}];
          int strides[${stridesRank}];
          ${copyPads}
          ${copyInputDims}
          ${copyStrides}
          ${copyKernelStrides}

          float value = ${start};
          int pad = 0;
          bool isPad = false;
          for (int i = 0; i < ${kernelSize}; i++) {
            offsetToIndices(i, kernelStrides, offset);
            isPad = false;
            for (int j = ${rank} - ${stridesRank}; j < ${rank}; j++) {
              x[j] = indices[j] * strides[j - ${rank} + ${stridesRank}]
                + offset[j - ${rank} + ${stridesRank}] - pads[j - 2];
              ${padCode}
          }
          ${op2}

          return value;
        }
      `;
        return poolingCode;
    }
};
const copyArray = (array, arrayName) => {
    let block = '';
    for (let i = 0; i < array.length; i++) {
        block += `
      ${arrayName}[${i}] = ${array[i]};
    `;
    }
    return block;
};
const offsetToIndices = (rank) => `
  void offsetToIndices(int offset, int[${rank}] strides, out int[${rank}] indices) {
    if (${rank} == 0) {
      return;
    }
    for (int i = 0; i < ${rank} - 1; ++i) {
      indices[i] = offset / strides[i];
      offset -= indices[i] * strides[i];
    }
    indices[${rank} - 1] = offset;
  }`;


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/ops/reduce.ts":
/*!*************************************************!*\
  !*** ./lib/onnxjs/backends/webgl/ops/reduce.ts ***!
  \*************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.reduceLogSumSquare = exports.reduceLogSum = exports.reduceProd = exports.reduceMin = exports.reduceMax = exports.reduceMean = exports.reduceSum = exports.parseReduceAttributes = void 0;
const attribute_with_cache_key_1 = __webpack_require__(/*! ../../../attribute-with-cache-key */ "./lib/onnxjs/attribute-with-cache-key.ts");
const operators_1 = __webpack_require__(/*! ../../../operators */ "./lib/onnxjs/operators.ts");
const util_1 = __webpack_require__(/*! ../../../util */ "./lib/onnxjs/util.ts");
const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
const reduce = (inferenceHandler, inputs, attributes, name, reduceOp) => {
    validateInputs(inputs);
    const reduceProgramMetadata = {
        name,
        inputNames: ['A'],
        inputTypes: [types_1.TextureType.unpacked],
    };
    const output = inferenceHandler.run(Object.assign(Object.assign({}, reduceProgramMetadata), { cacheHint: attributes.cacheKey, get: () => createReduceProgramInfo(inferenceHandler, inputs, attributes, name, reduceOp, reduceProgramMetadata) }), inputs);
    return [output];
};
const parseReduceAttributes = (node) => {
    const axes = node.attributes.getInts('axes', []);
    const keepDims = node.attributes.getInt('keepdims', 1) === 1;
    return (0, attribute_with_cache_key_1.createAttributeWithCacheKey)({ axes, keepDims });
};
exports.parseReduceAttributes = parseReduceAttributes;
const createReduceProgramInfo = (handler, inputs, attributes, name, reduceOp, reduceProgramMetadata) => {
    const outputShape = [];
    const iRank = inputs[0].dims.length || 1;
    const idxCopy = []; // copy output indexes to input indexes
    const axes = util_1.ShapeUtil.normalizeAxes(attributes.axes, inputs[0].dims.length);
    const ops = reduceOp(inputs, axes);
    let reduceOps = ops[1];
    for (let k = 0; k < inputs[0].dims.length; k++) {
        // if this axis is reduced
        if (axes.indexOf(k) >= 0 || axes.length === 0) {
            if (attributes.keepDims) {
                outputShape.push(1);
            } // else { remove the axis from outputShape; }
            // loop over the d-th axis
            reduceOps = `
          for(int j${k} = 0; j${k} < ${inputs[0].dims[k]}; j${k}++) {
            inputIdx[${k}] = j${k};
            ${reduceOps}
          }`;
        }
        else {
            idxCopy.push(`inputIdx[${k}] = outputIdx[${outputShape.length}];`);
            outputShape.push(inputs[0].dims[k]);
        }
    }
    const oRank = outputShape.length || 1;
    const shaderSource = `
      float process(int outputIdx[${oRank}]) {
        float value;                 // final result
        int inputIdx[${iRank}];      // addressing input data
        ${idxCopy.join('\n')}
        ${ops[0]}       // init ops for reduce max/min
        ${reduceOps}
        ${ops[2]}       // final computation for reduce mean
        return value;
      }`;
    return Object.assign(Object.assign({}, reduceProgramMetadata), { output: { dims: outputShape, type: inputs[0].type, textureType: types_1.TextureType.unpacked }, shaderSource });
};
const validateInputs = (inputs) => {
    if (!inputs || inputs.length !== 1) {
        throw new Error('Reduce op requires 1 input.');
    }
    if (operators_1.NUMBER_TYPES.indexOf(inputs[0].type) === -1) {
        throw new Error('Invalid input type.');
    }
};
const reduceSum = (inferenceHandler, inputs, attributes) => {
    const reduceOp = () => ['value = 0.0;', 'value += _A(inputIdx);', ''];
    return reduce(inferenceHandler, inputs, attributes, 'ReduceSum', reduceOp);
};
exports.reduceSum = reduceSum;
const reduceMean = (inferenceHandler, inputs, attributes) => {
    const reduceOp = (inputs, axes) => {
        let size = 1.0;
        for (let k = 0; k < inputs[0].dims.length; k++) {
            if (axes.indexOf(k) >= 0 || axes.length === 0) {
                size *= inputs[0].dims[k];
            }
        }
        return ['value = 0.0;', 'value += _A(inputIdx);', `value /= ${size}.;`]; // ensure real number with `.`
    };
    return reduce(inferenceHandler, inputs, attributes, 'ReduceMean', reduceOp);
};
exports.reduceMean = reduceMean;
const reduceMax = (inferenceHandler, inputs, attributes) => {
    const reduceOp = (inputs, axes) => {
        const idxZero = [];
        for (let k = 0; k < inputs[0].dims.length; k++) {
            if (axes.indexOf(k) >= 0 || axes.length === 0) {
                idxZero.push(`inputIdx[${k}] = 0;`); // first element
            }
        }
        return [`${idxZero.join('\n')}\nvalue = _A(inputIdx);`, 'value = max(value, _A(inputIdx));', ''];
    };
    return reduce(inferenceHandler, inputs, attributes, 'ReduceMax', reduceOp);
};
exports.reduceMax = reduceMax;
const reduceMin = (inferenceHandler, inputs, attributes) => {
    const reduceOp = (inputs, axes) => {
        const idxZero = [];
        for (let k = 0; k < inputs[0].dims.length; k++) {
            if (axes.indexOf(k) >= 0 || axes.length === 0) {
                idxZero.push(`inputIdx[${k}] = 0;`); // first element
            }
        }
        return [`${idxZero.join('\n')}\nvalue = _A(inputIdx);`, 'value = min(value, _A(inputIdx));', ''];
    };
    return reduce(inferenceHandler, inputs, attributes, 'ReduceMin', reduceOp);
};
exports.reduceMin = reduceMin;
const reduceProd = (inferenceHandler, inputs, attributes) => {
    const reduceOp = () => ['value = 1.0;', 'value *= _A(inputIdx);', ''];
    return reduce(inferenceHandler, inputs, attributes, 'ReduceProd', reduceOp);
};
exports.reduceProd = reduceProd;
const reduceLogSum = (inferenceHandler, inputs, attributes) => {
    const reduceOp = () => ['value = 0.0;', 'value += _A(inputIdx);', 'value = log(value);'];
    return reduce(inferenceHandler, inputs, attributes, 'ReduceLogSum', reduceOp);
};
exports.reduceLogSum = reduceLogSum;
const reduceLogSumSquare = (inferenceHandler, inputs, attributes) => {
    const reduceOp = () => ['float t; value = 0.0;', 't = _A(inputIdx); value += t * t;', ''];
    return reduce(inferenceHandler, inputs, attributes, 'ReduceLogSumSquare', reduceOp);
};
exports.reduceLogSumSquare = reduceLogSumSquare;


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/ops/reshape-packed.ts":
/*!*********************************************************!*\
  !*** ./lib/onnxjs/backends/webgl/ops/reshape-packed.ts ***!
  \*********************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.isReshapeCheap = exports.processDims3D = exports.createPackedReshape3DProgramInfoLoader = void 0;
const util_1 = __webpack_require__(/*! ../../../util */ "./lib/onnxjs/util.ts");
const glsl_source_1 = __webpack_require__(/*! ../glsl-source */ "./lib/onnxjs/backends/webgl/glsl-source.ts");
const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
const packing_utils_1 = __webpack_require__(/*! ./packing-utils */ "./lib/onnxjs/backends/webgl/ops/packing-utils.ts");
const createPackedReshape3DProgramMetadata = (outputShape3D) => ({ name: 'Reshape (packed)', inputTypes: [types_1.TextureType.packed], inputNames: ['A'], cacheHint: `${outputShape3D}` });
const createPackedReshape3DProgramInfo = (handler, input3D, metadata, outputShape3D) => {
    const inputShape3D = input3D.dims;
    const squeezedOutputShape = outputShape3D;
    let mainLoop = '';
    for (let i = 0; i < 4; i++) {
        let outputCoords = '';
        switch (i) {
            case 0:
                outputCoords = 'outputCoords = rc;';
                break;
            case 1:
                outputCoords = 'outputCoords = ivec3(rc.x, rc.y+1, rc.z);';
                break;
            case 2:
                outputCoords = 'outputCoords = ivec3(rc.x, rc.y, rc.z+1);';
                break;
            case 3:
                outputCoords = 'outputCoords = ivec3(rc.x, rc.y+1, rc.z+1);';
                break;
            default:
                throw new Error();
        }
        mainLoop += `
        ${outputCoords}
        ${i > 0 ? 'if(outputCoords.y < rows && outputCoords.z < cols){' : ''}
          int flattenedIndex = getFlattenedIndex(outputCoords);

          ivec3 inputRC = inputCoordsFromReshapedOutCoords(flattenedIndex);
          vec2 innerDims = vec2(float(inputRC.y),float(inputRC.z));

          result[${i}] = getChannel(getA(inputRC.x, inputRC.y, inputRC.z), innerDims);

        ${i > 0 ? '}' : ''}
      `;
    }
    const glsl = (0, glsl_source_1.getGlsl)(handler.session.backend.glContext.version);
    const shaderSource = `
      ${getReshapedInputCoords(inputShape3D)}
      ${getFlattenedIndexFrom3D(squeezedOutputShape)}
      ${(0, packing_utils_1.unpackFromChannel)()}

      void main() {
        ivec3 rc = getOutputCoords();

        vec4 result = vec4(0.0);

        ivec3 outputCoords;
        int rows = ${squeezedOutputShape[2]};
        int cols = ${squeezedOutputShape[1]};

        ${mainLoop}
        ${glsl.output} = result;
      }
    `;
    return Object.assign(Object.assign({}, metadata), { output: { dims: squeezedOutputShape, type: input3D.type, textureType: types_1.TextureType.packed }, shaderSource, hasMain: true });
};
const createPackedReshape3DProgramInfoLoader = (handler, input3D, outputShape3D) => {
    const metadata = createPackedReshape3DProgramMetadata(outputShape3D);
    return Object.assign(Object.assign({}, metadata), { get: () => createPackedReshape3DProgramInfo(handler, input3D, metadata, outputShape3D) });
};
exports.createPackedReshape3DProgramInfoLoader = createPackedReshape3DProgramInfoLoader;
function processDims3D(shape) {
    if (shape.length === 0) {
        return [1, 1, 1];
    }
    // TODO: squeeze other shapes to 2D case
    let batch = 1;
    for (let i = 0; i < shape.length - 2; ++i) {
        batch *= shape[i];
    }
    return [batch, shape.length > 1 ? shape[shape.length - 2] : 1, shape[shape.length - 1]];
}
exports.processDims3D = processDims3D;
// For packed reshape, we need to re-arrange texel data for output shape.
// Our pack is designed to pack a 2x2 tile in last h and w dimension, so
// for the reshaped new tensor, we just need to re-arrange the last h and
// w dimension. For any shape that is not in 3D, i.e. [batch, W, H], we
// first convert it to 3D by collapsing other dimension to batch dim, then
// process with the last two dimensions.
// Note: we only need the shape tensor to calculate output shape, so the
// content in shape tensor is never uploaded to GPU. It is always kept in CPU.
// TODO: optimize the algorithm -- in some cases, if the last two dims are
// the same between input shape and output shape, the packed reshape can be
// treated as no-op.
function isReshapeCheap(dims, reshapedDims) {
    let isCheapReshape = false;
    if (dims.length === 0 || reshapedDims.length === 0) { // scalar
        isCheapReshape = true;
    }
    else if (dims.length < 2 || reshapedDims.length < 2) { // 1D
        isCheapReshape = dims[dims.length - 1] === reshapedDims[reshapedDims.length - 1];
    }
    else { // 2D +
        isCheapReshape = dims[dims.length - 1] === reshapedDims[reshapedDims.length - 1] &&
            dims[dims.length - 2] === reshapedDims[reshapedDims.length - 2];
    }
    return isCheapReshape;
}
exports.isReshapeCheap = isReshapeCheap;
function getReshapedInputCoords(shape) {
    const strides = util_1.ShapeUtil.computeStrides(shape);
    const coords = ['b', 'r', 'c'];
    const index = 'index';
    const coordsFromIndexSnippet = strides
        .map((stride, i) => {
        const line1 = `int ${coords[i]} = ${index} / ${stride}`;
        const line2 = i === strides.length - 1 ?
            `int ${coords[i + 1]} = ${index} - ${coords[i]} * ${stride}` :
            `index -= ${coords[i]} * ${stride}`;
        return `${line1}; ${line2};`;
    })
        .join('');
    return `
    ivec3 inputCoordsFromReshapedOutCoords(int index) {
      ${coordsFromIndexSnippet}
      return ivec3(b, r, c);
    }
  `;
}
function getFlattenedIndexFrom3D(shape) {
    const strides = util_1.ShapeUtil.computeStrides(shape);
    return `
  int getFlattenedIndex(ivec3 coords) {
    // reverse y, z order
    return coords.x * ${strides[0]} + coords.z * ${strides[1]} + coords.y;
  }
`;
}


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/ops/reshape.ts":
/*!**************************************************!*\
  !*** ./lib/onnxjs/backends/webgl/ops/reshape.ts ***!
  \**************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.reshape = void 0;
const util_1 = __webpack_require__(/*! ../../../util */ "./lib/onnxjs/util.ts");
const reshape = (handler, inputs) => {
    const reshapedDims = util_1.ShapeUtil.calculateReshapedDims(inputs[0].dims, inputs[1].integerData);
    if (handler.session.pack) {
        return [handler.reshapePacked(inputs[0], reshapedDims)];
    }
    else {
        return [handler.reshapeUnpacked(inputs[0], reshapedDims)];
    }
};
exports.reshape = reshape;


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/ops/resize-packed.ts":
/*!********************************************************!*\
  !*** ./lib/onnxjs/backends/webgl/ops/resize-packed.ts ***!
  \********************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.parseResizeAttributesV11 = exports.parseResizeAttributesV10 = exports.resize = void 0;
const glsl_source_1 = __webpack_require__(/*! ../glsl-source */ "./lib/onnxjs/backends/webgl/glsl-source.ts");
const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
const utils_1 = __webpack_require__(/*! ../utils */ "./lib/onnxjs/backends/webgl/utils.ts");
const packing_utils_1 = __webpack_require__(/*! ./packing-utils */ "./lib/onnxjs/backends/webgl/ops/packing-utils.ts");
const upsample_1 = __webpack_require__(/*! ./upsample */ "./lib/onnxjs/backends/webgl/ops/upsample.ts");
const resizeProgramMetadata = {
    name: 'Resize',
    inputNames: ['A'],
    inputTypes: [types_1.TextureType.packed]
};
const resize = (inferenceHandler, inputs, attributes) => {
    (0, upsample_1.validateInputs)(inputs, attributes);
    const output = inferenceHandler.run(Object.assign(Object.assign({}, resizeProgramMetadata), { cacheHint: attributes.cacheKey, get: () => createPackedResizeProgramInfo(inferenceHandler, inputs, attributes) }), inputs);
    return [output];
};
exports.resize = resize;
const parseResizeAttributesV10 = (node) => (0, upsample_1.parseUpsampleAttributes)(node, 10);
exports.parseResizeAttributesV10 = parseResizeAttributesV10;
const parseResizeAttributesV11 = (node) => (0, upsample_1.parseUpsampleAttributes)(node, 11);
exports.parseResizeAttributesV11 = parseResizeAttributesV11;
const createPackedResizeProgramInfo = (inferenceHandler, inputs, attributes) => {
    const glsl = (0, glsl_source_1.getGlsl)(inferenceHandler.session.backend.glContext.version);
    const [scales, outputShape] = prepareInputs(inputs, attributes);
    const isSame = scales.every((s) => s === 1) && attributes.coordinateTransformMode !== 'tf_crop_and_resize';
    if (isSame) {
        return Object.assign(Object.assign({}, resizeProgramMetadata), { output: { dims: outputShape, type: inputs[0].type, textureType: types_1.TextureType.packed }, hasMain: true, shaderSource: `void main() {
                    vec4 v = ${glsl.texture2D}(X, TexCoords);
                    ${glsl.output} = v;
                }` });
    }
    const dim = outputShape.length;
    if (dim < 2) {
        throw new Error(`output dimension should be at least 2, but got ${dim}`);
    }
    const outputHeight = outputShape[dim - 2];
    const outputWidth = outputShape[dim - 1];
    const inputShape = inputs[0].dims;
    if (dim !== inputShape.length) {
        throw new Error(`output dimension should match input ${inputShape.length}, but got ${dim}`);
    }
    const inputHeight = inputShape[dim - 2];
    const inputWidth = inputShape[dim - 1];
    const scalesHeight = scales[dim - 2];
    const scalesWidth = scales[dim - 1];
    let getSourceFracIndex = '';
    if (attributes.mode !== 'linear') {
        // TODO: support other modes
        throw new Error(`resize (packed) does not support mode: '${attributes.mode}'`);
    }
    switch (attributes.coordinateTransformMode) {
        case 'asymmetric':
            getSourceFracIndex = `
                    vec4 getSourceFracIndex(ivec4 coords) {
                        return vec4(coords) / scaleWHWH;
                    }
                `;
            break;
        case 'half_pixel':
            getSourceFracIndex = `
                    vec4 getSourceFracIndex(ivec4 coords) {
                        return (vec4(coords) + 0.5) / scaleWHWH - 0.5;
                    }
                `;
            break;
        case 'pytorch_half_pixel':
            getSourceFracIndex = `
                    vec4 getSourceFracIndex(ivec4 coords) {
                        vec4 fcoords = vec4(coords);
                        return vec4(
                            ${outputWidth}.0 > 1.0 ? (fcoords.x + 0.5) / scaleWHWH.x - 0.5 : 0.0,
                            ${outputHeight}.0 > 1.0 ? (fcoords.y + 0.5) / scaleWHWH.y - 0.5 : 0.0,
                            ${outputWidth}.0 > 1.0 ? (fcoords.z + 0.5) / scaleWHWH.z - 0.5 : 0.0,
                            ${outputHeight}.0 > 1.0 ? (fcoords.w + 0.5) / scaleWHWH.w - 0.5 : 0.0
                          );
                    }
                `;
            break;
        case 'align_corners':
            getSourceFracIndex = `
                    vec4 getSourceFracIndex(ivec4 coords) {
                        vec4 resized = vec4(${outputWidth}.0 - 1.0, ${outputHeight}.0 - 1.0, ${outputWidth}.0 - 1.0,
                            ${outputHeight}.0 - 1.0);
                        vec4 original = vec4(${inputWidth}.0 - 1.0, ${inputHeight}.0 - 1.0, ${inputWidth}.0 - 1.0,
                            ${inputHeight}.0 - 1.0);
                        vec4 new_scale = original / resized;
                        return vec4(coords) * new_scale;
                    }
                `;
            break;
        default:
            // TODO:supporting other coordinateTransformModes
            throw new Error(`resize (packed) does not support coordinateTransformMode: \
                                '${attributes.coordinateTransformMode}'`);
    }
    const coordsDataType = (0, utils_1.getCoordsDataType)(dim);
    const unpackChannel = (0, packing_utils_1.unpackFromChannel)();
    const shaderSource = `
            const vec2 inputWH = vec2(${inputHeight}.0, ${inputWidth}.0);
            const vec4 scaleWHWH = vec4(float(${scalesHeight}), float(${scalesWidth}), float(${scalesHeight}), float(${scalesWidth}));
            ${unpackChannel}
            ${getSourceFracIndex}
            float getAValue(int x10, int r, int c, int d) {
                return getChannel(getA(x10, r, c, d), vec2(c, d));
            }
            void main() {
                ${coordsDataType} rc = getOutputCoords();

                int batch = rc[0];
                int depth = rc[1];

                // retrieve the 4 coordinates that is used in the 4 packed output values.
                ivec4 coords = ivec4(rc.wz, rc.w + 1, rc.z + 1);

                // calculate the source index in fraction
                vec4 sourceFrac = getSourceFracIndex(coords);

                // get the lower and upper bound of the 4 values that will be packed into one texel.
                ivec4 x00 = ivec4(max(sourceFrac.xy, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.xy)));
                ivec4 x01 = ivec4(max(sourceFrac.xw, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.xw)));
                ivec4 x10 = ivec4(max(sourceFrac.zy, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.zy)));
                ivec4 x11 = ivec4(max(sourceFrac.zw, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.zw)));

                bool hasNextRow = rc.w < ${outputHeight - 1};
                bool hasNextCol = rc.z < ${outputWidth - 1};

                // pack x00, x01, x10, x11's top-left corner into one vec4 structure
                vec4 topLeft = vec4(
                    getAValue(batch, depth, x00.x, x00.y),
                    hasNextCol ? getAValue(batch, depth, x01.x, x01.y) : 0.0,
                    hasNextRow ? getAValue(batch, depth, x10.x, x10.y) : 0.0,
                    (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.x, x11.y) : 0.0);

                // pack x00, x01, x10, x11's top-right corner into one vec4 structure
                vec4 topRight = vec4(
                    getAValue(batch, depth, x00.x, x00.w),
                    hasNextCol ? getAValue(batch, depth, x01.x, x01.w) : 0.0,
                    hasNextRow ? getAValue(batch, depth, x10.x, x10.w) : 0.0,
                    (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.x, x11.w) : 0.0);

                // pack x00, x01, x10, x11's bottom-left corner into one vec4 structure
                vec4 bottomLeft = vec4(
                    getAValue(batch, depth, x00.z, x00.y),
                    hasNextCol ? getAValue(batch, depth, x01.z, x01.y) : 0.0,
                    hasNextRow ? getAValue(batch, depth, x10.z, x10.y) : 0.0,
                    (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.z, x11.y) : 0.0);

                // pack x00, x01, x10, x11's bottom-right corner into one vec4 structure
                vec4 bottomRight = vec4(
                    getAValue(batch, depth, x00.z, x00.w),
                    hasNextCol ? getAValue(batch, depth, x01.z, x01.w) : 0.0,
                    hasNextRow ? getAValue(batch, depth, x10.z, x10.w) : 0.0,
                    (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.z, x11.w) : 0.0);

                // calculate the interpolation fraction on u and v direction
                vec4 frac = vec4(sourceFrac) - floor(sourceFrac);
                vec4 clampFrac = clamp(frac, vec4(0.0), vec4(1.0));

                vec4 top = mix(topLeft, topRight, clampFrac.ywyw);
                vec4 bottom = mix(bottomLeft, bottomRight, clampFrac.ywyw);
                vec4 newValue = mix(top, bottom, clampFrac.xxzz);

                ${glsl.output} = vec4(newValue);
            }
        `;
    return Object.assign(Object.assign({}, resizeProgramMetadata), { output: { dims: outputShape, type: inputs[0].type, textureType: types_1.TextureType.packed }, hasMain: true, shaderSource });
};
const prepareInputs = (inputs, attributes) => {
    const x = inputs[0];
    const xDims = x.dims;
    let scales = attributes.scales;
    let outputSizes;
    if (scales.length === 0) {
        const scalesTensor = inputs[attributes.scalesInputIdx];
        if (scalesTensor && scalesTensor.size !== 0) {
            if (inputs[attributes.sizesInputIdx]) {
                throw new Error('Only one of scales or sizes must be provided as input.');
            }
            scales = parseScalesData(scalesTensor, attributes.mode, attributes.isResize);
        }
        else {
            const sizesTensor = inputs[attributes.sizesInputIdx];
            if (!sizesTensor || sizesTensor.size === 0) {
                throw new Error('Either scales or sizes MUST be provided as input.');
            }
            outputSizes = Array.from(sizesTensor.integerData);
            scales = parseScalesDataFromOutputSize(outputSizes, xDims, attributes.mode, attributes.isResize);
        }
    }
    else {
        if (inputs[attributes.sizesInputIdx]) {
            throw new Error('Only one of scales or sizes must be provided as input.');
        }
    }
    const yDims = outputSizes || (xDims.map((dim, i) => Math.floor(dim * scales[i])));
    return [scales, yDims];
};
const parseScalesData = (scale, mode, isResize) => {
    const scales = Array.from(scale.floatData);
    (0, upsample_1.scalesValidation)(scales, mode, isResize);
    return scales;
};
const parseScalesDataFromOutputSize = (yDims, xDims, mode, isResize) => {
    const length = xDims.length;
    const scales = new Array(length);
    for (let i = 0, end = length; i < end; i++) {
        if (xDims[i] === 0) {
            if (yDims[i] !== 0) {
                throw new Error('Input dim is zero but required output dim is non-zero.');
            }
            scales[i] = 1;
        }
        else {
            scales[i] = yDims[i] / xDims[i];
        }
    }
    (0, upsample_1.scalesValidation)(scales, mode, isResize);
    return scales;
};
// roi data is not used yet. but leave here for future usage.
// const getRoi = (inputs: Tensor[], attributes: UpsampleAttributes) : number[] => {
//     let roi: number[] = [];
//     if (attributes.needRoiInput) {
//         if (attributes.roiInputIdx <= 0) {
//             throw new Error('Invalid roi input index.');
//         }
//         const roiTensor = inputs[attributes.roiInputIdx];
//         roi = roiTensor.size > 0 ? Array.from(roiTensor.floatData) : [];
//     } else {
//         roi = new Array(inputs[0].dims.length * 2).fill(0);
//     }
//     return roi;
// };


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/ops/shape.ts":
/*!************************************************!*\
  !*** ./lib/onnxjs/backends/webgl/ops/shape.ts ***!
  \************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.shape = void 0;
const tensor_1 = __webpack_require__(/*! ../../../tensor */ "./lib/onnxjs/tensor.ts");
const shape = (inferenceHandler, inputs) => {
    validateInputs(inputs);
    return [new tensor_1.Tensor([inputs[0].dims.length], 'int32', undefined, undefined, new Int32Array(inputs[0].dims))];
};
exports.shape = shape;
const validateInputs = (inputs) => {
    if (!inputs || inputs.length !== 1) {
        throw new Error('Shape requires 1 input.');
    }
};


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/ops/slice.ts":
/*!************************************************!*\
  !*** ./lib/onnxjs/backends/webgl/ops/slice.ts ***!
  \************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.sliceV10 = exports.parseSliceAttributes = exports.slice = void 0;
const attribute_with_cache_key_1 = __webpack_require__(/*! ../../../attribute-with-cache-key */ "./lib/onnxjs/attribute-with-cache-key.ts");
const operators_1 = __webpack_require__(/*! ../../../operators */ "./lib/onnxjs/operators.ts");
const util_1 = __webpack_require__(/*! ../../../util */ "./lib/onnxjs/util.ts");
const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
const sliceProgramMetadata = {
    name: 'Slice',
    inputNames: ['A'],
    inputTypes: [types_1.TextureType.unpacked]
};
const slice = (inferenceHandler, inputs, attributes) => {
    validateInputs(inputs);
    const output = inferenceHandler.run(Object.assign(Object.assign({}, sliceProgramMetadata), { cacheHint: attributes.cacheKey, get: () => createSliceProgramInfo(inferenceHandler, inputs[0], attributes) }), inputs);
    return [output];
};
exports.slice = slice;
const parseSliceAttributes = (node) => {
    const starts = node.attributes.getInts('starts');
    const ends = node.attributes.getInts('ends');
    const axes = node.attributes.getInts('axes', []);
    return (0, attribute_with_cache_key_1.createAttributeWithCacheKey)({ starts, ends, axes });
};
exports.parseSliceAttributes = parseSliceAttributes;
const createSliceProgramInfo = (inferenceHandler, input, attributes) => {
    const axes = (attributes.axes.length === 0) ? input.dims.slice(0).map((val, i) => i) : attributes.axes;
    const normalizedAxes = util_1.ShapeUtil.normalizeAxes(axes, input.dims.length);
    const starts = attributes.starts.map((start, i) => {
        if (start > input.dims[normalizedAxes[i]] - 1) {
            return input.dims[normalizedAxes[i]];
        }
        return util_1.ShapeUtil.normalizeAxis(start, input.dims[normalizedAxes[i]]);
    });
    const ends = attributes.ends.map((end, i) => {
        if (end > input.dims[normalizedAxes[i]] - 1) {
            return input.dims[normalizedAxes[i]];
        }
        return util_1.ShapeUtil.normalizeAxis(end, input.dims[normalizedAxes[i]]);
    });
    const outputShape = input.dims.slice();
    const sliceOps = [];
    for (let i = 0; i < normalizedAxes.length; i++) {
        outputShape[normalizedAxes[i]] = ends[i] - starts[i];
        if (starts[i] > 0) {
            sliceOps.push(`outputIdx[${normalizedAxes[i]}] += ${starts[i]};`);
        } // else { sliceOps.push(`outputIdx[${normalizedAxes[i]}] += 0;`); }
    }
    const rank = outputShape.length;
    const shaderSource = `
      float process(int outputIdx[${rank}]) {
        ${sliceOps.join('\n      ')}
        return _A(outputIdx);
      }`;
    return Object.assign(Object.assign({}, sliceProgramMetadata), { output: { dims: outputShape, type: input.type, textureType: types_1.TextureType.unpacked }, shaderSource });
};
const validateInputs = (inputs) => {
    if (!inputs || inputs.length !== 1) {
        throw new Error('Slice requires 1 input.');
    }
    if (operators_1.NUMBER_TYPES.indexOf(inputs[0].type) === -1) {
        throw new Error('Invalid input type.');
    }
};
const sliceV10 = (inferenceHandler, inputs) => {
    validateInputsV10(inputs);
    const attributes = generateSliceAttributesFromInputs(inferenceHandler, inputs);
    const output = inferenceHandler.run(Object.assign(Object.assign({}, sliceProgramMetadata), { cacheHint: attributes.cacheKey, get: () => createSliceProgramInfo(inferenceHandler, inputs[0], attributes) }), [inputs[0]]);
    return [output];
};
exports.sliceV10 = sliceV10;
const generateSliceAttributesFromInputs = (inferenceHandler, inputs) => {
    if (!inferenceHandler.session.isInitializer(inputs[1].dataId) ||
        !inferenceHandler.session.isInitializer(inputs[2].dataId) ||
        (inputs.length >= 4 && !inferenceHandler.session.isInitializer(inputs[3].dataId)) ||
        (inputs.length >= 5 && !inferenceHandler.session.isInitializer(inputs[4].dataId))) {
        throw new Error('dynamic slice attributes are not allowed');
    }
    if (inputs.length >= 5 && inputs[4].integerData.some((i) => i !== 1)) {
        throw new Error('currently non-1 steps is not supported for Slice');
    }
    const starts = Array.from(inputs[1].integerData);
    const ends = Array.from(inputs[2].integerData);
    const axes = inputs.length >= 4 ? Array.from(inputs[3].integerData) : [];
    const cacheKey = `${axes};${starts};${ends}`;
    return { starts, ends, axes, cacheKey };
};
const validateInputsV10 = (inputs) => {
    if (!inputs || inputs.length < 3 || inputs.length > 5) {
        throw new Error('Invalid input number.');
    }
    if (inputs[1].type !== 'int32' || inputs[1].dims.length !== 1) {
        throw new Error('Invalid input type.');
    }
    if (inputs[2].type !== 'int32' || inputs[2].dims.length !== 1) {
        throw new Error('Invalid input type.');
    }
    if (inputs.length >= 4 && (inputs[3].type !== 'int32' || inputs[3].dims.length !== 1)) {
        throw new Error('Invalid input type.');
    }
    if (inputs.length >= 5 && (inputs[4].type !== 'int32' || inputs[4].dims.length !== 1)) {
        throw new Error('Invalid input type.');
    }
};


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/ops/softmax.ts":
/*!**************************************************!*\
  !*** ./lib/onnxjs/backends/webgl/ops/softmax.ts ***!
  \**************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.softmaxV13 = exports.parseSoftmaxAttributesV13 = exports.parseSoftmaxAttributes = exports.softmax = void 0;
const attribute_with_cache_key_1 = __webpack_require__(/*! ../../../attribute-with-cache-key */ "./lib/onnxjs/attribute-with-cache-key.ts");
const util_1 = __webpack_require__(/*! ../../../util */ "./lib/onnxjs/util.ts");
const glsl_source_1 = __webpack_require__(/*! ../glsl-source */ "./lib/onnxjs/backends/webgl/glsl-source.ts");
const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
const transpose_1 = __webpack_require__(/*! ./transpose */ "./lib/onnxjs/backends/webgl/ops/transpose.ts");
const softmaxComputeMaxProgramMetadata = {
    name: 'SoftmaxComputeMax',
    inputNames: ['A'],
    inputTypes: [types_1.TextureType.unpacked],
};
const softmaxComputeScaleProgramMetadata = {
    name: 'SoftmaxComputeScale',
    inputNames: ['A', 'Max'],
    inputTypes: [types_1.TextureType.unpacked, types_1.TextureType.unpacked],
};
const softmaxProgramMetadata = {
    name: 'SoftMax',
    inputNames: ['A', 'Max', 'Norm'],
    inputTypes: [types_1.TextureType.unpacked, types_1.TextureType.unpacked, types_1.TextureType.unpacked],
};
const softmax = (inferenceHandler, inputs, attributes) => {
    validateInputs(inputs);
    const inputShape = inputs[0].dims.slice();
    const axis = util_1.ShapeUtil.normalizeAxis(attributes.axis, inputShape.length);
    const logicalRowCount = util_1.ShapeUtil.sizeToDimension(inputShape, axis);
    const featureCount = util_1.ShapeUtil.sizeFromDimension(inputShape, axis);
    const output = computeSoftmax(inferenceHandler, inputs, attributes, logicalRowCount, featureCount);
    return output;
};
exports.softmax = softmax;
const parseSoftmaxAttributes = (node) => (0, attribute_with_cache_key_1.createAttributeWithCacheKey)({ axis: node.attributes.getInt('axis', 1) });
exports.parseSoftmaxAttributes = parseSoftmaxAttributes;
const parseSoftmaxAttributesV13 = (node) => (0, attribute_with_cache_key_1.createAttributeWithCacheKey)({ axis: node.attributes.getInt('axis', -1) });
exports.parseSoftmaxAttributesV13 = parseSoftmaxAttributesV13;
// The "semantic" meaning of axis has changed in opset-13.
// Please compare: https://github.com/onnx/onnx/blob/main/docs/Operators.md#Softmax
// with https://github.com/onnx/onnx/blob/main/docs/Changelog.md#Softmax-11 for detailed explanations
// To account for the opset-13 behavior, our plan will be to transpose the "axis" dim to the innermost dim
// and perform softmax and then reverse the transpose. We can skip the transposing aspect if the axis is already
// the innermost dim
const softmaxV13 = (inferenceHandler, inputs, attributes) => {
    validateInputs(inputs);
    const inputShape = inputs[0].dims.slice();
    const axis = util_1.ShapeUtil.normalizeAxis(attributes.axis, inputShape.length);
    const rank = inputShape.length;
    const isTransposeRequired = (axis !== rank - 1) ? true : false;
    const transposedInputShape = [];
    let perm = [];
    let transposedInputs = [];
    let transposeAttribute;
    if (isTransposeRequired) {
        perm = Array.from({ length: rank }).map((_, i) => i);
        // swap the innermost dim with the dim corresponding to axis
        perm[axis] = rank - 1;
        perm[rank - 1] = axis;
        perm.map(p => transposedInputShape.push(inputShape[p]));
        transposeAttribute = (0, attribute_with_cache_key_1.createAttributeWithCacheKey)({ perm });
        transposedInputs = (0, transpose_1.transpose)(inferenceHandler, inputs, transposeAttribute);
    }
    const logicalRowCount = isTransposeRequired ? util_1.ShapeUtil.sizeToDimension(transposedInputShape, rank - 1) :
        util_1.ShapeUtil.sizeToDimension(inputShape, rank - 1);
    const featureCount = isTransposeRequired ? util_1.ShapeUtil.sizeFromDimension(transposedInputShape, rank - 1) :
        util_1.ShapeUtil.sizeFromDimension(inputShape, rank - 1);
    const output = computeSoftmax(inferenceHandler, isTransposeRequired ? transposedInputs : inputs, attributes, logicalRowCount, featureCount);
    if (isTransposeRequired) {
        const reversedOutput = (0, transpose_1.transpose)(inferenceHandler, output, transposeAttribute);
        return reversedOutput;
    }
    else {
        return output;
    }
};
exports.softmaxV13 = softmaxV13;
const computeSoftmax = (inferenceHandler, inputs, attributes, logicalRowCount, featureCount) => {
    const computeMaxProgramInfo = createComputeMaxProgramInfo(inferenceHandler, inputs[0], logicalRowCount, featureCount, [logicalRowCount]);
    const max = inferenceHandler.run(Object.assign(Object.assign({}, softmaxComputeMaxProgramMetadata), { cacheHint: attributes.cacheKey, get: () => computeMaxProgramInfo }), inputs);
    const computeScaleProgramInfo = createComputScaleProgramInfo(inferenceHandler, inputs[0], logicalRowCount, featureCount, computeMaxProgramInfo.output.dims, [logicalRowCount]);
    const scale = inferenceHandler.run(Object.assign(Object.assign({}, softmaxComputeScaleProgramMetadata), { cacheHint: attributes.cacheKey, get: () => computeScaleProgramInfo }), [inputs[0], max]);
    const softMaxProgramInfo = createSoftMaxProgramInfo(inferenceHandler, inputs[0], logicalRowCount, featureCount, computeMaxProgramInfo.output.dims, computeScaleProgramInfo.output.dims);
    const output = inferenceHandler.run(Object.assign(Object.assign({}, softmaxProgramMetadata), { cacheHint: attributes.cacheKey, get: () => softMaxProgramInfo }), [inputs[0], max, scale]);
    return [output];
};
/**
 * Create a texture that contains the maximum value of each of the 'N' rows
 */
const createComputeMaxProgramInfo = (inferenceHandler, input, logicalRowCount, featureCount, outputShape) => {
    const [textureWidth, textureHeight] = inferenceHandler.calculateTextureWidthAndHeight(input.dims, types_1.TextureType.unpacked);
    const rank = outputShape.length;
    if (logicalRowCount < 1 || featureCount < 1) {
        throw new Error('Logical row count N and feature count D must be greater than or equal to 1');
    }
    if (outputShape.length !== 1) {
        throw new Error('Dimensionality of the output should be 1');
    }
    if (outputShape[0] !== logicalRowCount) {
        throw new Error('Shape of the output should be equal to logical row count');
    }
    const glsl = (0, glsl_source_1.getGlsl)(inferenceHandler.session.backend.glContext.version);
    const shaderSource = `
      float process(int[${rank}] indices) {
        int logical_row_start_offset = indices[0] * ${featureCount};

        float max = getColorAsFloat(${glsl.texture2D}(A, offsetToCoords(logical_row_start_offset, ${textureWidth},
        ${textureHeight} )));
        for(int i=1; i<${featureCount}; ++i)
        {
          float current = getColorAsFloat(${glsl.texture2D}(A, offsetToCoords(logical_row_start_offset + i,
            ${textureWidth}, ${textureHeight})));
          if(current > max)
          max = current;
        }

        return max;
      }`;
    return Object.assign(Object.assign({}, softmaxComputeMaxProgramMetadata), { output: { dims: outputShape, type: input.type, textureType: types_1.TextureType.unpacked }, shaderSource });
};
/**
 * Create a texture that contains the normalization factor for each of the 'N' rows
 */
const createComputScaleProgramInfo = (inferenceHandler, input, logicalRowCount, featureCount, maxElementPerLogicalRow, outputShape) => {
    const [textureWidth, textureHeight] = inferenceHandler.calculateTextureWidthAndHeight(input.dims, types_1.TextureType.unpacked);
    const rank = outputShape.length;
    if (logicalRowCount < 1 || featureCount < 1) {
        throw new Error('Logical row count N and feature count D must be greater than or equal to 1');
    }
    if (outputShape.length !== 1) {
        throw new Error('Dimensionality of the output should be 1');
    }
    if (outputShape[0] !== logicalRowCount) {
        throw new Error('Shape of the output should be equal to logical row count');
    }
    if (maxElementPerLogicalRow.length !== 1) {
        throw new Error('Dimensionality of the intermediate results should be 1');
    }
    if (maxElementPerLogicalRow[0] !== logicalRowCount) {
        throw new Error('Shape of the intermediate results should be equal to logical row count');
    }
    const glsl = (0, glsl_source_1.getGlsl)(inferenceHandler.session.backend.glContext.version);
    const shaderSource = `
      float process(int[${rank}] indices) {
        int logical_row_start_offset = indices[0] * ${featureCount};

        float norm_factor = 0.0;
        float max = _Max(indices);
        for(int i=0; i<${featureCount}; ++i)
        {
          norm_factor += exp(getColorAsFloat(${glsl.texture2D}(A, offsetToCoords(logical_row_start_offset + i,
            ${textureWidth}, ${textureHeight}))) - max);
        }

        return norm_factor;
      }`;
    return Object.assign(Object.assign({}, softmaxComputeScaleProgramMetadata), { output: { dims: outputShape, type: input.type, textureType: types_1.TextureType.unpacked }, shaderSource });
};
const createSoftMaxProgramInfo = (inferenceHandler, input, logicalRowCount, featureCount, maxElementPerLogicalRow, normalizationPerLogicalRow) => {
    const [textureWidth, textureHeight] = inferenceHandler.calculateTextureWidthAndHeight(input.dims, types_1.TextureType.unpacked);
    const rank = input.dims.length;
    if (logicalRowCount < 1 || featureCount < 1) {
        throw new Error('Logical row count N and feature count D must be greater than or equal to 1');
    }
    if (maxElementPerLogicalRow.length !== 1 || normalizationPerLogicalRow.length !== 1) {
        throw new Error('Dimensionality of the intermediate results should be 1');
    }
    if (maxElementPerLogicalRow[0] !== logicalRowCount || normalizationPerLogicalRow[0] !== logicalRowCount) {
        throw new Error('Shape of the intermediate results should be equal to logical row count');
    }
    const shaderSource = `
      float process(int[${rank}] indices) {

      // get offset of current logical tensor index from the 2-D texture coordinates (TexCoords)
      int offset = coordsToOffset(TexCoords, ${textureWidth}, ${textureHeight});

      //determine the logical row for this index
      int logical_row_index[1];
      logical_row_index[0] = offset / ${featureCount};

      float norm_factor = _Norm(logical_row_index);

      // avoid possible division by 0
      // if norm_facor is 0, all elements are zero
      // if so, return 0
      if(norm_factor == 0.0)
        return 0.0;

      return exp(_A(indices) - _Max(logical_row_index)) / norm_factor;
    }`;
    return Object.assign(Object.assign({}, softmaxProgramMetadata), { output: { dims: input.dims, type: input.type, textureType: types_1.TextureType.unpacked }, shaderSource });
};
const validateInputs = (inputs) => {
    if (!inputs || inputs.length !== 1) {
        throw new Error('Softmax requires 1 input.');
    }
    if (inputs[0].type !== 'float32' && inputs[0].type !== 'float64') {
        throw new Error('Invalid input type');
    }
};


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/ops/split.ts":
/*!************************************************!*\
  !*** ./lib/onnxjs/backends/webgl/ops/split.ts ***!
  \************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.parseSplitAttributes = exports.split = void 0;
const attribute_with_cache_key_1 = __webpack_require__(/*! ../../../attribute-with-cache-key */ "./lib/onnxjs/attribute-with-cache-key.ts");
const util_1 = __webpack_require__(/*! ../../../util */ "./lib/onnxjs/util.ts");
const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
const splitProgramMetadata = {
    name: 'Split',
    inputNames: ['A'],
    inputTypes: [types_1.TextureType.unpacked],
};
const split = (inferenceHandler, inputs, attributes) => {
    validateInputs(inputs);
    const axis = util_1.ShapeUtil.normalizeAxis(attributes.axis, inputs[0].dims.length);
    const count = getProgramCount(inferenceHandler, inputs, axis, attributes);
    const output = [];
    for (let i = 0; i < count; ++i) {
        output.push(inferenceHandler.run(Object.assign(Object.assign({}, splitProgramMetadata), { cacheHint: `${attributes.cacheKey};${i}`, get: () => createSplitProgramInfo(inferenceHandler, inputs[0], attributes, axis, i) }), inputs));
    }
    return output;
};
exports.split = split;
const parseSplitAttributes = (node) => {
    const axis = node.attributes.getInt('axis', 0);
    const split = node.attributes.getInts('split', []);
    const numOutputs = node.outputs.length;
    return (0, attribute_with_cache_key_1.createAttributeWithCacheKey)({ axis, split, numOutputs });
};
exports.parseSplitAttributes = parseSplitAttributes;
const getProgramCount = (inferenceHandler, inputs, axis, attributes) => {
    const [, offsets] = util_1.SplitUtil.splitShape(inputs[0].dims, axis, attributes.split, attributes.numOutputs);
    return offsets.length;
};
const createSplitProgramInfo = (inferenceHandler, input, attributes, axis, index) => {
    const [shapes, offsets] = util_1.SplitUtil.splitShape(input.dims, axis, attributes.split, attributes.numOutputs);
    const offset = offsets[index];
    const outputShape = shapes[index];
    const rank = outputShape.length;
    const shaderSource = `
      float process(int indices[${rank}]) {
        indices[${axis}] += ${offset};
        return _A(indices);
      }
    `;
    return Object.assign(Object.assign({}, splitProgramMetadata), { cacheHint: `${attributes.cacheKey}:${index}`, output: { dims: outputShape, type: input.type, textureType: types_1.TextureType.unpacked }, shaderSource });
};
const validateInputs = (inputs) => {
    if (!inputs || inputs.length !== 1) {
        throw new Error('Split requires one input.');
    }
    if (inputs[0].type !== 'int8' && inputs[0].type !== 'uint8' && inputs[0].type !== 'int16' &&
        inputs[0].type !== 'uint16' && inputs[0].type !== 'int32' && inputs[0].type !== 'uint32' &&
        inputs[0].type !== 'float32' && inputs[0].type !== 'float64' && inputs[0].type !== 'bool') {
        throw new Error('Invalid input type.');
    }
};


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/ops/squeeze.ts":
/*!**************************************************!*\
  !*** ./lib/onnxjs/backends/webgl/ops/squeeze.ts ***!
  \**************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.parseSqueezeAttributes = exports.squeezeV13 = exports.squeeze = void 0;
const util_1 = __webpack_require__(/*! ../../../util */ "./lib/onnxjs/util.ts");
const squeeze = (inferenceHandler, inputs, axes) => {
    validateInputs(inputs);
    const outputShape = util_1.ShapeUtil.squeezeShape(inputs[0].dims, axes);
    const output = inferenceHandler.reshapeUnpacked(inputs[0], outputShape);
    return [output];
};
exports.squeeze = squeeze;
const squeezeV13 = (inferenceHandler, inputs) => {
    validateInputsV13(inputs);
    return (0, exports.squeeze)(inferenceHandler, [inputs[0]], Array.from(inputs[1].integerData));
};
exports.squeezeV13 = squeezeV13;
const parseSqueezeAttributes = (node) => node.attributes.getInts('axes');
exports.parseSqueezeAttributes = parseSqueezeAttributes;
const validateInputs = (inputs) => {
    if (!inputs || inputs.length !== 1) {
        throw new Error('Squeeze requires 1 input.');
    }
    if (inputs[0].type === 'string') {
        throw new Error('invalid input tensor types.');
    }
};
const validateInputsV13 = (inputs) => {
    if (!inputs || inputs.length !== 2) {
        throw new Error('Squeeze requires 2 inputs.');
    }
    if (inputs[1].type !== 'int32') {
        throw new Error('Invalid input type.');
    }
};


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/ops/sum.ts":
/*!**********************************************!*\
  !*** ./lib/onnxjs/backends/webgl/ops/sum.ts ***!
  \**********************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.sum = void 0;
const glsl_source_1 = __webpack_require__(/*! ../glsl-source */ "./lib/onnxjs/backends/webgl/glsl-source.ts");
const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
const sum = (inferenceHandler, inputs) => {
    validateInputs(inputs);
    const sumProgramMetadata = {
        name: 'Sum',
        inputNames: inputs.map((v, i) => `X${i}`),
        inputTypes: new Array(inputs.length).fill(types_1.TextureType.unpacked)
    };
    const output = inferenceHandler.run(Object.assign(Object.assign({}, sumProgramMetadata), { get: () => createSumProgramInfo(inferenceHandler, inputs, sumProgramMetadata) }), inputs);
    return [output];
};
exports.sum = sum;
const createSumProgramInfo = (inferenceHandler, inputs, sumProgramMetadata) => {
    const glsl = (0, glsl_source_1.getGlsl)(inferenceHandler.session.backend.glContext.version);
    const outputShape = inputs[0].dims.slice();
    const sumLine = inputs.map((v, i) => `${glsl.texture2D}(X${i},TexCoords)`).join(' + ');
    const shaderSource = `
      void main() {
        vec4 result = ${sumLine};
        ${glsl.output} = result;
      }
    `;
    return Object.assign(Object.assign({}, sumProgramMetadata), { output: { dims: outputShape, type: inputs[0].type, textureType: types_1.TextureType.unpacked }, hasMain: true, shaderSource });
};
const validateInputs = (inputs) => {
    if (!inputs || inputs.length === 0) {
        throw new Error('Sum requires inputs.');
    }
    const length = inputs[0].dims.length;
    for (let i = 1; i < inputs.length; i++) {
        if (length !== inputs[i].dims.length) {
            throw new Error('Input shapes are mismatched.');
        }
        for (let j = 0; j < length; j++) {
            if (inputs[0].dims[j] !== inputs[i].dims[j]) {
                throw new Error('Input shapes are not matched.');
            }
        }
    }
    if (inputs[0].type !== 'float32' && inputs[0].type !== 'float64') {
        throw new Error('Invalid input type.');
    }
    for (let i = 1; i < inputs.length; i++) {
        if (inputs[0].type !== inputs[i].type) {
            throw new Error('Input types are not matched.');
        }
    }
};


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/ops/tile.ts":
/*!***********************************************!*\
  !*** ./lib/onnxjs/backends/webgl/ops/tile.ts ***!
  \***********************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.tile = void 0;
const operators_1 = __webpack_require__(/*! ../../../operators */ "./lib/onnxjs/operators.ts");
const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
const tile = (inferenceHandler, inputs) => {
    validateInputs(inputs);
    const tileProgramMetadata = {
        name: 'Tile',
        inputNames: ['A'],
        inputTypes: [types_1.TextureType.unpacked],
    };
    const output = inferenceHandler.run(Object.assign(Object.assign({}, tileProgramMetadata), { get: () => createTileProgramInfo(inferenceHandler, inputs, tileProgramMetadata) }), inputs);
    return [output];
};
exports.tile = tile;
const createTileProgramInfo = (handler, inputs, tileProgramMetadata) => {
    const inputShape = inputs[0].dims.slice();
    const outputShape = new Array(inputShape.length);
    const tileOps = [];
    for (let i = 0; i < inputShape.length; i++) {
        outputShape[i] = inputShape[i] * inputs[1].numberData[i];
        tileOps.push(`inputIdx[${i}] = int(mod(float(outputIdx[${i}]), ${inputShape[i]}.));`);
    }
    const rank = outputShape.length;
    const shaderSource = `
      float process(int outputIdx[${rank}]) {
        int inputIdx[${rank}];
        ${tileOps.join('\n')}
        return _A(inputIdx);
      }
    `;
    return Object.assign(Object.assign({}, tileProgramMetadata), { output: { dims: outputShape, type: inputs[0].type, textureType: types_1.TextureType.unpacked }, shaderSource });
};
const validateInputs = (inputs) => {
    if (!inputs || inputs.length !== 2) {
        throw new Error('Tile requires 2 input.');
    }
    if (inputs[1].dims.length !== 1) {
        throw new Error('The second input shape must 1 dimension.');
    }
    if (inputs[1].dims[0] !== inputs[0].dims.length) {
        throw new Error('Invalid input shape.');
    }
    if (operators_1.NUMBER_TYPES.indexOf(inputs[0].type) === -1) {
        throw new Error('Invalid input type.');
    }
    if (inputs[1].type !== 'int32' && inputs[1].type !== 'int16') {
        throw new Error('Invalid repeat type.');
    }
};


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/ops/transpose.ts":
/*!****************************************************!*\
  !*** ./lib/onnxjs/backends/webgl/ops/transpose.ts ***!
  \****************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.parseTransposeAttributes = exports.transpose = void 0;
const attribute_with_cache_key_1 = __webpack_require__(/*! ../../../attribute-with-cache-key */ "./lib/onnxjs/attribute-with-cache-key.ts");
const util_1 = __webpack_require__(/*! ../../../util */ "./lib/onnxjs/util.ts");
const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
const transposeProgramMetadata = {
    name: 'Transpose',
    inputNames: ['A'],
    inputTypes: [types_1.TextureType.unpacked]
};
const transpose = (inferenceHandler, inputs, attributes) => {
    validateInputs(inputs);
    const output = inferenceHandler.run(Object.assign(Object.assign({}, transposeProgramMetadata), { cacheHint: attributes.cacheKey, get: () => createTransposeProgramInfo(inferenceHandler, inputs[0], attributes.perm) }), inputs);
    return [output];
};
exports.transpose = transpose;
const parseTransposeAttributes = (node) => (0, attribute_with_cache_key_1.createAttributeWithCacheKey)({ perm: node.attributes.getInts('perm', []) });
exports.parseTransposeAttributes = parseTransposeAttributes;
const createTransposeProgramInfo = (inferenceHandler, input, perm) => {
    const inputShape = input.dims;
    perm = getAdjustedPerm(inputShape, perm);
    const unpackedOutputShape = getOutputShape(inputShape, perm);
    const rank = inputShape.length;
    // A dims=[${inputs[0].dims.toString()}]
    // out Dims=[${unpackedOutputShape.toString()}]
    // based on perm=[${perm.toString()}]
    const shaderSource = `
      ${getPermFunctionBody('perm', perm, rank)}
      float process(int indices[${rank}]) {
        int a[${rank}];
        perm(a, indices);
        return _A(a);
      }`;
    return Object.assign(Object.assign({}, transposeProgramMetadata), { output: { dims: unpackedOutputShape, type: input.type, textureType: types_1.TextureType.unpacked }, shaderSource });
};
const getAdjustedPerm = (inputShape, perm) => {
    if (perm && perm.length !== inputShape.length) {
        perm = [...(inputShape.keys())].reverse();
    }
    return perm;
};
const getOutputShape = (inputShape, perm) => {
    perm = getAdjustedPerm(inputShape, perm);
    return util_1.ShapeUtil.sortBasedOnPerm(inputShape, perm);
};
const getPermFunctionBody = (name, perm, rank) => {
    const reverseFunc = [];
    reverseFunc.push(`void ${name}(out int a[${rank}], int src[${rank}]) {`);
    for (let i = 0; i < rank; ++i) {
        reverseFunc.push(`\ta[${perm[i]}]=src[${i}];`);
    }
    reverseFunc.push('\t}');
    return reverseFunc.join('\n');
};
const validateInputs = (inputs) => {
    if (!inputs || inputs.length !== 1) {
        throw new Error('Transpose requires 1 input.');
    }
    if (inputs[0].type !== 'float32' && inputs[0].type !== 'float64') {
        throw new Error('input should be float tensor');
    }
};


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/ops/uint8-encode.ts":
/*!*******************************************************!*\
  !*** ./lib/onnxjs/backends/webgl/ops/uint8-encode.ts ***!
  \*******************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.encodeAsUint8 = void 0;
const glsl_source_1 = __webpack_require__(/*! ../glsl-source */ "./lib/onnxjs/backends/webgl/glsl-source.ts");
const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
const encodeAsUint8 = (inferenceHandler, input) => {
    const outputShape = input.shape;
    const glsl = (0, glsl_source_1.getGlsl)(inferenceHandler.session.backend.glContext.version);
    /**
     * https://github.com/tensorflow/tfjs-core/blob/master/src/kernels/webgl/encode_float_gpu.ts
     */
    const shaderSource = `
    const float FLOAT_MAX = 1.70141184e38;
    const float FLOAT_MIN = 1.17549435e-38;

    bool isNaN(float val) {
      return (val < 1.0 || 0.0 < val || val == 0.0) ? false : true;
    }

    highp vec4 encodeAsUint8(highp float v) {
      if (isNaN(v)) {
        return vec4(255, 255, 255, 255);
      }

      highp float av = abs(v);

      if(av < FLOAT_MIN) {
        return vec4(0.0, 0.0, 0.0, 0.0);
      } else if(v > FLOAT_MAX) {
        return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;
      } else if(v < -FLOAT_MAX) {
        return vec4(0.0, 0.0,  128.0, 255.0) / 255.0;
      }

      highp vec4 c = vec4(0,0,0,0);

      highp float e = floor(log2(av));
      highp float m = exp2(fract(log2(av))) - 1.0;

      c[2] = floor(128.0 * m);
      m -= c[2] / 128.0;
      c[1] = floor(32768.0 * m);
      m -= c[1] / 32768.0;
      c[0] = floor(8388608.0 * m);

      highp float ebias = e + 127.0;
      c[3] = floor(ebias / 2.0);
      ebias -= c[3] * 2.0;
      c[2] += floor(ebias) * 128.0;

      c[3] += 128.0 * step(0.0, -v);

      return c / 255.0;
    }

    void main() {
      float value = ${glsl.texture2D}(X,TexCoords).r;
      ${glsl.output} = encodeAsUint8(value);
    }`;
    const programInfo = {
        name: 'Uint8Encode',
        inputTypes: [types_1.TextureType.unpacked],
        inputNames: ['X'],
        output: { dims: outputShape, type: input.tensor.type, textureType: types_1.TextureType.downloadUint8AsFloat },
        shaderSource,
        hasMain: true
    };
    return inferenceHandler.executeProgram(programInfo, [input.tensor]);
};
exports.encodeAsUint8 = encodeAsUint8;


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/ops/unary-op.ts":
/*!***************************************************!*\
  !*** ./lib/onnxjs/backends/webgl/ops/unary-op.ts ***!
  \***************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.tanh = exports.tan = exports.sqrt = exports.sin = exports.sigmoid = exports.relu = exports.not = exports.neg = exports.log = exports.parseLeakyReluAttributes = exports.leakyRelu = exports.identity = exports.floor = exports.exp = exports.parseEluAttributes = exports.elu = exports.cos = exports.ceil = exports.clipV11 = exports.parseClipAttributes = exports.clip = exports.atan = exports.asin = exports.acos = exports.abs = exports.glslTanh = exports.glslTan = exports.glslSqrt = exports.glslSigmoid = exports.glslRelu = exports.glslSin = exports.glslNot = exports.glslNeg = exports.glslLog = exports.glslLeakyRelu = exports.glslIdentity = exports.glslClip = exports.glslFloor = exports.glslExp = exports.glslElu = exports.glslCos = exports.glslCeil = exports.glslAtan = exports.glslAsin = exports.glslAcos = exports.glslAbs = void 0;
const attribute_with_cache_key_1 = __webpack_require__(/*! ../../../attribute-with-cache-key */ "./lib/onnxjs/attribute-with-cache-key.ts");
const util_1 = __webpack_require__(/*! ../../../util */ "./lib/onnxjs/util.ts");
const glsl_definitions_1 = __webpack_require__(/*! ../glsl-definitions */ "./lib/onnxjs/backends/webgl/glsl-definitions.ts");
const glsl_source_1 = __webpack_require__(/*! ../glsl-source */ "./lib/onnxjs/backends/webgl/glsl-source.ts");
const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
function glslAbs() {
    return glslBuiltinUnary('abs');
}
exports.glslAbs = glslAbs;
function glslAcos() {
    return glslBuiltinUnary('acos');
}
exports.glslAcos = glslAcos;
function glslAsin() {
    return glslBuiltinUnary('asin');
}
exports.glslAsin = glslAsin;
function glslAtan() {
    return glslBuiltinUnary('atan');
}
exports.glslAtan = glslAtan;
function glslCeil() {
    return glslBuiltinUnary('ceil');
}
exports.glslCeil = glslCeil;
function glslCos() {
    return glslBuiltinUnary('cos');
}
exports.glslCos = glslCos;
function glslElu(alpha) {
    const name = 'elu';
    const body = `
  const float alpha = float(${alpha});

  float ${name}_(float a) {
    return a >= 0.0 ? a: (exp(a) - 1.0) * alpha;
  }
  vec4 ${name}_(vec4 v) {
    return vec4(${name}_(v.x), ${name}_(v.y), ${name}_(v.z), ${name}_(v.w));
  }
  `;
    return { body, name, type: glsl_definitions_1.FunctionType.ValueBased };
}
exports.glslElu = glslElu;
function glslExp() {
    return glslBuiltinUnary('exp');
}
exports.glslExp = glslExp;
function glslFloor() {
    return glslBuiltinUnary('floor');
}
exports.glslFloor = glslFloor;
function glslClip(min, max) {
    const name = 'clip';
    const body = `
  const float min = float(${min});
  const float max = float(${max});

  float ${name}_(float a) {
    return clamp(a, min, max);
  }
  vec4 ${name}_(vec4 v) {
    return clamp(v, min, max);
  }
  `;
    return { body, name, type: glsl_definitions_1.FunctionType.ValueBased };
}
exports.glslClip = glslClip;
function glslIdentity() {
    const name = 'indentity';
    const body = `
  float ${name}_(float a) {
    return a;
  }
  vec4 ${name}_(vec4 v) {
    return v;
  }
  `;
    return { body, name, type: glsl_definitions_1.FunctionType.ValueBased };
}
exports.glslIdentity = glslIdentity;
function glslLeakyRelu(alpha) {
    const name = 'leakyRelu';
    const body = `
  const float alpha = float(${alpha});

  float ${name}_(float a) {
    return a < 0.0 ? a * alpha : a;
  }
  vec4 ${name}_(vec4 v) {
    return vec4(${name}_(v.x), ${name}_(v.y), ${name}_(v.z), ${name}_(v.w));
  }
  `;
    return { body, name, type: glsl_definitions_1.FunctionType.ValueBased };
}
exports.glslLeakyRelu = glslLeakyRelu;
function glslLog() {
    return glslBuiltinUnary('log');
}
exports.glslLog = glslLog;
function glslNeg() {
    const name = 'neg';
    const body = `
  float ${name}_(float a) {
    return -a;
  }
  vec4 ${name}_(vec4 v) {
    return -v;
  }
  `;
    return { body, name, type: glsl_definitions_1.FunctionType.ValueBased };
}
exports.glslNeg = glslNeg;
function glslNot() {
    const name = 'not';
    const body = `
  float ${name}_(float a) {
    return float( ! bool(a) );
  }
  bool ${name}_(bool a) {
    return !a;
  }
  vec4 ${name}_(vec4 v) {
    return vec4(!bool(v.x), !bool(v.y), !bool(v.z), !bool(v.w));
  }
  bvec4 ${name}_(bvec4 v) {
    return bvec4(!v.x, !v.y, !v.z, !v.w);
  }
  `;
    return { body, name, type: glsl_definitions_1.FunctionType.ValueBased };
}
exports.glslNot = glslNot;
function glslSin() {
    return glslBuiltinUnary('sin');
}
exports.glslSin = glslSin;
function glslRelu() {
    const name = 'relu';
    const body = `
  float ${name}_(float a) {
    return max( a, 0.0 );
  }
  vec4 ${name}_(vec4 v) {
    return max( v, 0.0 );
  }
  `;
    return { body, name, type: glsl_definitions_1.FunctionType.ValueBased };
}
exports.glslRelu = glslRelu;
function glslSigmoid() {
    const name = 'sigmoid';
    const body = `
  float ${name}_(float a) {
    return 1.0 / (1.0 + exp(-a));
  }
  vec4 ${name}_(vec4 v) {
    return 1.0 / (1.0 + exp(-v));
  }
  `;
    return { body, name, type: glsl_definitions_1.FunctionType.ValueBased };
}
exports.glslSigmoid = glslSigmoid;
function glslSqrt() {
    return glslBuiltinUnary('sqrt');
}
exports.glslSqrt = glslSqrt;
function glslTan() {
    return glslBuiltinUnary('tan');
}
exports.glslTan = glslTan;
function glslTanh() {
    const name = 'tanh';
    const body = `
  float ${name}_(float a) {
    a = clamp(a, -10., 10.);
    a = exp(2.*a);
    return (a - 1.) / (a + 1.);
  }
  vec4 ${name}_(vec4 v) {
    v = clamp(v, -10., 10.);
    v = exp(2.*v);
    return (v - 1.) / (v + 1.);
  }
  `;
    return { body, name, type: glsl_definitions_1.FunctionType.ValueBased };
}
exports.glslTanh = glslTanh;
function glslBuiltinUnary(name) {
    const body = `
  float ${name}_(float a) {
    return ${name}(a);
  }
  vec4 ${name}_(vec4 v) {
    return ${name}(v);
  }
  `;
    return { body, name, type: glsl_definitions_1.FunctionType.ValueBased };
}
/////
/////
/////
const createElementwiseProgramInfo = (handler, metadata, input, glslFunc) => {
    const textureType = handler.session.pack ? types_1.TextureType.packed : types_1.TextureType.unpacked;
    const glsl = (0, glsl_source_1.getGlsl)(handler.session.backend.glContext.version);
    return Object.assign(Object.assign({}, metadata), { output: { dims: input.dims, type: input.type, textureType }, shaderSource: `
     ${glslFunc.body}
     void main() {
       vec4 v = ${glsl.texture2D}(A, TexCoords);
       v = ${glslFunc.name}_(v);
       ${glsl.output} = v;
     }
     `, hasMain: true });
};
const createElementwiseProgramInfoLoader = (handler, input, glslFunc, cacheKey) => {
    const textureType = handler.session.pack ? types_1.TextureType.packed : types_1.TextureType.unpacked;
    const metadata = { name: glslFunc.name, inputTypes: [textureType], inputNames: ['A'], cacheHint: cacheKey };
    return Object.assign(Object.assign({}, metadata), { get: () => createElementwiseProgramInfo(handler, metadata, input, glslFunc) });
};
const abs = (handler, inputs) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslAbs()), inputs)];
exports.abs = abs;
const acos = (handler, inputs) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslAcos()), inputs)];
exports.acos = acos;
const asin = (handler, inputs) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslAsin()), inputs)];
exports.asin = asin;
const atan = (handler, inputs) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslAtan()), inputs)];
exports.atan = atan;
const clip = (handler, inputs, attributes) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslClip(attributes.min, attributes.max), attributes.cacheKey), inputs)];
exports.clip = clip;
const parseClipAttributes = (node) => (0, attribute_with_cache_key_1.createAttributeWithCacheKey)({ min: node.attributes.getFloat('min', util_1.MIN_CLIP), max: node.attributes.getFloat('max', util_1.MAX_CLIP) });
exports.parseClipAttributes = parseClipAttributes;
const clipV11 = (handler, inputs) => {
    const attributes = generateClipAttributesFromInputs(handler, inputs);
    return (0, exports.clip)(handler, [inputs[0]], attributes);
};
exports.clipV11 = clipV11;
const generateClipAttributesFromInputs = (handler, inputs) => {
    if (inputs.length >= 3 &&
        (!handler.session.isInitializer(inputs[1].dataId) || !handler.session.isInitializer(inputs[2].dataId))) {
        throw new Error('dynamic clip attributes are not allowed');
    }
    const min = (inputs.length >= 3) ? inputs[1].numberData[0] : util_1.MIN_CLIP;
    const max = (inputs.length >= 3) ? inputs[2].numberData[0] : util_1.MAX_CLIP;
    return (0, attribute_with_cache_key_1.createAttributeWithCacheKey)({ min, max });
};
const ceil = (handler, inputs) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslCeil()), inputs)];
exports.ceil = ceil;
const cos = (handler, inputs) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslCos()), inputs)];
exports.cos = cos;
const elu = (handler, inputs, attributes) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslElu(attributes.alpha), attributes.cacheKey), inputs)];
exports.elu = elu;
const parseEluAttributes = (node) => (0, attribute_with_cache_key_1.createAttributeWithCacheKey)({ alpha: node.attributes.getFloat('alpha', 1.0) });
exports.parseEluAttributes = parseEluAttributes;
const exp = (handler, inputs) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslExp()), inputs)];
exports.exp = exp;
const floor = (handler, inputs) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslFloor()), inputs)];
exports.floor = floor;
const identity = (handler, inputs) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslIdentity()), inputs)];
exports.identity = identity;
const leakyRelu = (handler, inputs, attributes) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslLeakyRelu(attributes.alpha), attributes.cacheKey), inputs)];
exports.leakyRelu = leakyRelu;
const parseLeakyReluAttributes = (node) => (0, attribute_with_cache_key_1.createAttributeWithCacheKey)({ alpha: node.attributes.getFloat('alpha', 0.01) });
exports.parseLeakyReluAttributes = parseLeakyReluAttributes;
const log = (handler, inputs) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslLog()), inputs)];
exports.log = log;
const neg = (handler, inputs) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslNeg()), inputs)];
exports.neg = neg;
const not = (handler, inputs) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslNot()), inputs)];
exports.not = not;
const relu = (handler, inputs) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslRelu()), inputs)];
exports.relu = relu;
const sigmoid = (handler, inputs) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslSigmoid()), inputs)];
exports.sigmoid = sigmoid;
const sin = (handler, inputs) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslSin()), inputs)];
exports.sin = sin;
const sqrt = (handler, inputs) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslSqrt()), inputs)];
exports.sqrt = sqrt;
const tan = (handler, inputs) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslTan()), inputs)];
exports.tan = tan;
const tanh = (handler, inputs) => [handler.run(createElementwiseProgramInfoLoader(handler, inputs[0], glslTanh()), inputs)];
exports.tanh = tanh;


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/ops/unpack.ts":
/*!*************************************************!*\
  !*** ./lib/onnxjs/backends/webgl/ops/unpack.ts ***!
  \*************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.createUnpackProgramInfoLoader = exports.createUnpackProgramInfo = void 0;
const glsl_source_1 = __webpack_require__(/*! ../glsl-source */ "./lib/onnxjs/backends/webgl/glsl-source.ts");
const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
const utils_1 = __webpack_require__(/*! ../utils */ "./lib/onnxjs/backends/webgl/utils.ts");
const packing_utils_1 = __webpack_require__(/*! ./packing-utils */ "./lib/onnxjs/backends/webgl/ops/packing-utils.ts");
const unpackProgramMetadata = {
    name: 'unpack',
    inputNames: ['A'],
    inputTypes: [types_1.TextureType.packed]
};
const createUnpackProgramInfo = (handler, input) => {
    const rank = input.dims.length;
    const channels = (0, packing_utils_1.getChannels)('rc', rank);
    const innerDims = channels.slice(-2);
    const coordsDataType = (0, utils_1.getCoordsDataType)(rank);
    const unpackChannel = (0, packing_utils_1.unpackFromChannel)();
    const isScalar = (input.dims.length === 0);
    const sourceCoords = isScalar ? '' : getSourceCoords(rank, channels);
    const coords = rank <= 1 ? 'rc' : `vec2(${innerDims.join(',')})`;
    const glsl = (0, glsl_source_1.getGlsl)(handler.session.backend.glContext.version);
    const shaderSource = `
    ${unpackChannel}
    void main() {
      ${coordsDataType} rc = getOutputCoords();

       // Sample the texture with the coords to get the rgba channel value.
       vec4 packedInput = getA(${sourceCoords});

       ${glsl.output} = vec4(getChannel(packedInput, ${coords}), 0, 0, 0);
     }
   `;
    return Object.assign(Object.assign({}, unpackProgramMetadata), { hasMain: true, output: { dims: input.dims, type: input.type, textureType: types_1.TextureType.unpacked }, shaderSource });
};
exports.createUnpackProgramInfo = createUnpackProgramInfo;
const createUnpackProgramInfoLoader = (handler, input) => (Object.assign(Object.assign({}, unpackProgramMetadata), { get: () => (0, exports.createUnpackProgramInfo)(handler, input) }));
exports.createUnpackProgramInfoLoader = createUnpackProgramInfoLoader;
function getSourceCoords(rank, dims) {
    if (rank === 1) {
        return 'rc';
    }
    let coords = '';
    for (let i = 0; i < rank; i++) {
        coords += dims[i];
        if (i < rank - 1) {
            coords += ',';
        }
    }
    return coords;
}


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/ops/unsqueeze.ts":
/*!****************************************************!*\
  !*** ./lib/onnxjs/backends/webgl/ops/unsqueeze.ts ***!
  \****************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.parseUnsqueezeAttributes = exports.unsqueezeV13 = exports.unsqueeze = void 0;
const util_1 = __webpack_require__(/*! ../../../util */ "./lib/onnxjs/util.ts");
const unsqueeze = (inferenceHandler, inputs, axes) => {
    validateInputs(inputs);
    const outputShape = util_1.ShapeUtil.unsqueezeShape(inputs[0].dims, axes);
    const output = inferenceHandler.reshapeUnpacked(inputs[0], outputShape);
    return [output];
};
exports.unsqueeze = unsqueeze;
const unsqueezeV13 = (inferenceHandler, inputs) => {
    validateInputsV13(inputs);
    return (0, exports.unsqueeze)(inferenceHandler, [inputs[0]], Array.from(inputs[1].integerData));
};
exports.unsqueezeV13 = unsqueezeV13;
const parseUnsqueezeAttributes = (node) => node.attributes.getInts('axes');
exports.parseUnsqueezeAttributes = parseUnsqueezeAttributes;
const validateInputs = (inputs) => {
    if (!inputs || inputs.length !== 1) {
        throw new Error('Unsqueeze requires 1 input.');
    }
    if (inputs[0].type === 'string') {
        throw new Error('invalid input tensor types.');
    }
};
const validateInputsV13 = (inputs) => {
    if (!inputs || inputs.length !== 2) {
        throw new Error('Unsqueeze requires 2 inputs.');
    }
    if (inputs[1].type !== 'int32') {
        throw new Error('Invalid input type.');
    }
};


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/ops/upsample.ts":
/*!***************************************************!*\
  !*** ./lib/onnxjs/backends/webgl/ops/upsample.ts ***!
  \***************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.scalesValidation = exports.validateInputs = exports.parseUpsampleAttributes = exports.parseUpsampleAttributesV9 = exports.parseUpsampleAttributesV7 = exports.upsample = void 0;
const attribute_with_cache_key_1 = __webpack_require__(/*! ../../../attribute-with-cache-key */ "./lib/onnxjs/attribute-with-cache-key.ts");
const glsl_source_1 = __webpack_require__(/*! ../glsl-source */ "./lib/onnxjs/backends/webgl/glsl-source.ts");
const types_1 = __webpack_require__(/*! ../types */ "./lib/onnxjs/backends/webgl/types.ts");
const upsampleProgramMetadata = {
    name: 'Upsample',
    inputNames: ['X'],
    inputTypes: [types_1.TextureType.unpacked],
};
const upsample = (inferenceHandler, inputs, attributes) => {
    (0, exports.validateInputs)(inputs, attributes);
    const output = inferenceHandler.run(Object.assign(Object.assign({}, upsampleProgramMetadata), { cacheHint: attributes.cacheKey, get: () => createUpsampleProgramInfo(inferenceHandler, inputs, attributes) }), inputs);
    return [output];
};
exports.upsample = upsample;
const parseUpsampleAttributesV7 = (node) => (0, exports.parseUpsampleAttributes)(node, 7);
exports.parseUpsampleAttributesV7 = parseUpsampleAttributesV7;
const parseUpsampleAttributesV9 = (node) => (0, exports.parseUpsampleAttributes)(node, 9);
exports.parseUpsampleAttributesV9 = parseUpsampleAttributesV9;
const parseUpsampleAttributes = (node, opset) => {
    const isResize = (opset >= 10);
    // processing node attributes
    const mode = node.attributes.getString('mode', 'nearest');
    if (mode !== 'nearest' && mode !== 'linear' && (opset < 11 || mode !== 'cubic')) {
        throw new Error(`unrecognized mode: ${mode}`);
    }
    let scales = [];
    if (opset < 9) {
        scales = node.attributes.getFloats('scales');
        (0, exports.scalesValidation)(scales, mode, isResize);
    }
    const extrapolationValue = node.attributes.getFloat('extrapolation_value', 0.0);
    const coordinateTransformMode = opset > 10 ? node.attributes.getString('coordinate_transformation_mode', 'half_pixel') : 'asymmetric';
    if ([
        'asymmetric', 'pytorch_half_pixel', 'tf_half_pixel_for_nn', 'align_corners', 'tf_crop_and_resize', 'half_pixel'
    ].indexOf(coordinateTransformMode) === -1) {
        throw new Error(`coordinate_transform_mode '${coordinateTransformMode}' is not supported`);
    }
    const needRoiInput = (coordinateTransformMode === 'tf_crop_and_resize');
    const useExtrapolation = needRoiInput;
    const nearestMode = (mode === 'nearest' && opset >= 11) ? node.attributes.getString('nearest_mode', 'round_prefer_floor') : '';
    if (['round_prefer_floor', 'round_prefer_ceil', 'floor', 'ceil', ''].indexOf(nearestMode) === -1) {
        throw new Error(`nearest_mode '${nearestMode}' is not supported`);
    }
    const cubicCoefficientA = node.attributes.getFloat('cubic_coeff_a', -0.75);
    const excludeOutside = node.attributes.getInt('exclude_outside', 0) !== 0;
    if (excludeOutside && mode !== 'cubic') {
        throw new Error('exclude_outside can be set to 1 only when mode is CUBIC.');
    }
    const useNearest2xOptimization = (opset < 11) ? true : (mode === 'nearest' && coordinateTransformMode === 'asymmetric' && nearestMode === 'floor');
    let roiInputIdx = 0;
    let scalesInputIdx = 0;
    let sizesInputIdx = 0;
    if (opset > 10) {
        // handle when roiInput is not given
        if (node.inputs.length > 2) {
            roiInputIdx = 1;
            scalesInputIdx = 2;
            sizesInputIdx = 3;
        }
        else {
            scalesInputIdx = 1;
            sizesInputIdx = 2;
        }
    }
    else if (opset === 9) {
        scalesInputIdx = 1;
    }
    return (0, attribute_with_cache_key_1.createAttributeWithCacheKey)({
        opset,
        isResize,
        mode,
        scales,
        extrapolationValue,
        coordinateTransformMode,
        useExtrapolation,
        needRoiInput,
        nearestMode,
        cubicCoefficientA,
        excludeOutside,
        useNearest2xOptimization,
        roiInputIdx,
        scalesInputIdx,
        sizesInputIdx
    });
};
exports.parseUpsampleAttributes = parseUpsampleAttributes;
const createUpsampleProgramInfo = (inferenceHandler, inputs, attributes) => {
    const glsl = (0, glsl_source_1.getGlsl)(inferenceHandler.session.backend.glContext.version);
    const [inputWidth, inputHeight] = inferenceHandler.calculateTextureWidthAndHeight(inputs[0].dims, types_1.TextureType.unpacked);
    const outputShape = inputs[0].dims.map((dim, i) => Math.floor(dim * attributes.scales[i]));
    const [outputWidth, outputHeight] = inferenceHandler.calculateTextureWidthAndHeight(outputShape, types_1.TextureType.unpacked);
    const dim = outputShape.length;
    const outputPitches = new Array(dim);
    const inputPitches = new Array(dim);
    let precalculatedPitches = `
      int output_pitches[${dim}];
      int input_pitches[${dim}];
      `;
    for (let d = dim - 1; d >= 0; d--) {
        outputPitches[d] = (d === dim - 1) ? 1 : outputPitches[d + 1] * outputShape[d + 1];
        inputPitches[d] = (d === dim - 1) ? 1 : inputPitches[d + 1] * inputs[0].dims[d + 1];
        precalculatedPitches += `
        output_pitches[${d}] = ${outputPitches[d]};
        input_pitches[${d}] = ${inputPitches[d]};
        `;
    }
    const getInputFloatFunction = `
      float getInputFloat(int index) {
        vec2 coords = offsetToCoords(index, ${inputWidth}, ${inputHeight});
        float value = getColorAsFloat(${glsl.texture2D}(X, coords));
        return value;
      }
      `;
    const shaderSource = attributes.mode === 'nearest' ?
        // nearest
        `
    ${getInputFloatFunction}
    float process(int indices[${dim}]) {
      int input_index = 0;
      int output_index = coordsToOffset(TexCoords, ${outputWidth}, ${outputHeight});

      ${precalculatedPitches}

      int d, m;
      for (int dim = 0; dim < ${dim}; ++dim) {
        d = output_index / output_pitches[dim];
        m = output_index - d * output_pitches[dim];
        output_index = m;

        if (scales[dim] != 1 && d > 0) {
          int d2 = d / scales[dim];
          m = d - d2 * scales[dim];
          d = d2;
        }
        input_index += input_pitches[dim] * d;
      }

      return getInputFloat(input_index);
    }` :
        dim === 4 ?
            // bilinear 4D
            `
    ${getInputFloatFunction}
    float process(int indices[4]) {
      int input_index = 0;
      int output_index = coordsToOffset(TexCoords, ${outputWidth}, ${outputHeight});

      ${precalculatedPitches}

      int m;
      int index_of_dim0, index_of_dim1, index_of_dim2, index_of_dim3;
      index_of_dim0 = output_index / output_pitches[0];
      m = output_index - index_of_dim0 * output_pitches[0];
      index_of_dim1 = m / output_pitches[1];
      m = m - index_of_dim1 * output_pitches[1];
      index_of_dim2 = m / output_pitches[2];
      m = m - index_of_dim2 * output_pitches[2];
      index_of_dim3 = m;

      int index_of_input_dim2, index_of_input_dim3, x_offset, y_offset;
      index_of_input_dim2 = index_of_dim2 / scales[2];
      y_offset = index_of_dim2 - index_of_input_dim2 * scales[2];
      index_of_input_dim3 = index_of_dim3 / scales[3];
      x_offset = index_of_dim3 - index_of_input_dim3 * scales[3];

      input_index = index_of_dim0 * input_pitches[0] +
            index_of_dim1 * input_pitches[1] +
            index_of_input_dim2 * input_pitches[2] +
            index_of_input_dim3;

      float x00 = getInputFloat(input_index);
      float x10, x01, x11;

      bool end_of_dim2 = false;
      if (index_of_input_dim2 == (${inputs[0].dims[2]} - 1)) {
        // It's the end in dimension 2
        x01 = x00;
        end_of_dim2 = true;
      } else {
        x01 = getInputFloat(input_index + input_pitches[2]);
      }

      if (index_of_input_dim3 == (input_pitches[2] - 1)) {
        // It's the end in dimension 3
        x10 = x00;
        x11 = x01;
      }
      else {
        x10 = getInputFloat(input_index + 1);
        x11 = end_of_dim2 ? x10 : getInputFloat(input_index + input_pitches[2] + 1);
      }

      float y0 = x00 + float(y_offset) * (x01 - x00) / float(scales[2]);
      float y1 = x10 + float(y_offset) * (x11 - x10) / float(scales[2]);
      return y0 + float(x_offset) * (y1 - y0) / float(scales[3]);
    }` :
            // bilinear 2D
            `
    ${getInputFloatFunction}
    float process(int indices[2]) {
      int input_index = 0;
      int output_index = coordsToOffset(TexCoords, ${outputWidth}, ${outputHeight});

      ${precalculatedPitches}

      int m;
      int index_of_dim0, index_of_dim1;
      index_of_dim0 = output_index / output_pitches[0];
      m = output_index - index_of_dim0 * output_pitches[0];
      index_of_dim1 = m;

      int index_of_input_dim0, index_of_input_dim1, x_offset, y_offset;
      index_of_input_dim0 = index_of_dim0 / scales[0];
      y_offset = index_of_dim0 - index_of_input_dim0 * scales[0];
      index_of_input_dim1 = index_of_dim1 / scales[1];
      x_offset = index_of_dim1 - index_of_input_dim1 * scales[1];

      input_index = index_of_input_dim0 * input_pitches[0] + index_of_input_dim1;

      float x00 = getInputFloat(input_index);
      float x10, x01, x11;

      bool end_of_dim0 = false;
      if (index_of_input_dim0 == (${inputs[0].dims[0]} - 1)) {
        // It's the end in dimension 0
        x01 = x00;
        end_of_dim0 = true;
      } else {
        x01 = getInputFloat(input_index + input_pitches[0]);
      }

      if (index_of_input_dim1 == (input_pitches[0] - 1)) {
        // It's the end in dimension 1
        x10 = x00;
        x11 = x01;
      }
      else {
        x10 = getInputFloat(input_index + 1);
        x11 = end_of_dim0 ? x10 : getInputFloat(input_index + input_pitches[0] + 1);
      }

      float y0 = x00 + float(y_offset) * (x01 - x00) / float(scales[0]);
      float y1 = x10 + float(y_offset) * (x11 - x10) / float(scales[0]);
      return y0 + float(x_offset) * (y1 - y0) / float(scales[1]);
    }`;
    return Object.assign(Object.assign({}, upsampleProgramMetadata), { output: { dims: outputShape, type: inputs[0].type, textureType: types_1.TextureType.unpacked }, shaderSource, variables: [{
                name: 'scales',
                type: 'int',
                arrayLength: attributes.scales.length,
                data: attributes.scales.map(x => Math.ceil(x))
            }] });
};
const validateInputs = (inputs, attribute) => {
    if (!inputs || (attribute.opset < 9 && inputs.length !== 1) ||
        (attribute.opset >= 9 && attribute.opset < 11 && inputs.length !== 2) ||
        (attribute.opset >= 11 && inputs.length < 2)) {
        throw new Error('invalid inputs.');
    }
    if (attribute.scales.length > 0 && inputs[0].dims.length !== attribute.scales.length) {
        throw new Error('Invalid input shape.');
    }
    if (inputs[0].type === 'string') {
        throw new Error('Invalid input tensor types.');
    }
};
exports.validateInputs = validateInputs;
const scalesValidation = (scales, mode, isResize) => {
    if (!isResize) {
        for (const scale of scales) {
            if (scale < 1) {
                throw new Error('Scale value should be greater than or equal to 1.');
            }
        }
    }
    else {
        for (const scale of scales) {
            if (scale <= 0) {
                throw new Error('Scale value should be greater than 0.');
            }
        }
    }
    if (mode === 'linear' || mode === 'cubic') {
        if (scales.length !== 2 && (scales.length !== 4 || scales[0] !== 1 || scales[1] !== 1)) {
            throw new Error(`'Linear' mode and 'Cubic' mode only support 2-D inputs ('Bilinear', 'Bicubic') \
        or 4-D inputs with the corresponding outermost 2 scale values being 1 \
        in the ${isResize ? 'Resize' : 'Upsample'} opeartor.`);
        }
    }
};
exports.scalesValidation = scalesValidation;


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/program-manager.ts":
/*!******************************************************!*\
  !*** ./lib/onnxjs/backends/webgl/program-manager.ts ***!
  \******************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ProgramManager = void 0;
const onnxruntime_common_1 = __webpack_require__(/*! onnxruntime-common */ "../common/dist/lib/index.js");
const instrument_1 = __webpack_require__(/*! ../../instrument */ "./lib/onnxjs/instrument.ts");
const glsl_preprocessor_1 = __webpack_require__(/*! ./glsl-preprocessor */ "./lib/onnxjs/backends/webgl/glsl-preprocessor.ts");
const glsl_source_1 = __webpack_require__(/*! ./glsl-source */ "./lib/onnxjs/backends/webgl/glsl-source.ts");
/**
 * ProgramManager is the main class behind running computations
 * It builds ProgramInfo's into Artifacts
 * It compiles given ProgramInfo's into WebGL Prorams (cached as Artifacts)
 * Uses the artifact to run the computation by calling Draw on
 * the WebGL drawing buffer
 * ProgramManager automatically maps (binds) input variables to their
 * corresponding Location's in the binary program
 */
class ProgramManager {
    constructor(profiler, glContext, textureLayoutStrategy) {
        this.profiler = profiler;
        this.glContext = glContext;
        this.textureLayoutStrategy = textureLayoutStrategy;
        this.repo = new Map();
        this.attributesBound = false;
    }
    getArtifact(key) {
        return this.repo.get(key);
    }
    setArtifact(key, artifact) {
        this.repo.set(key, artifact);
    }
    run(buildArtifact, inputs, output) {
        var _a;
        this.profiler.event('op', `ProgramManager.run ${(_a = buildArtifact.programInfo.name) !== null && _a !== void 0 ? _a : 'unknown kernel'}`, () => {
            var _a;
            const gl = this.glContext.gl;
            const program = buildArtifact.program;
            gl.useProgram(program);
            try {
                this.bindOutput(output);
                if (!this.attributesBound) {
                    this.bindAttributes(buildArtifact.attribLocations);
                }
                this.bindUniforms(buildArtifact.uniformLocations, (_a = buildArtifact.programInfo.variables) !== null && _a !== void 0 ? _a : [], inputs);
            }
            catch (err) {
                instrument_1.Logger.error('ProgramManager', buildArtifact.programInfo.shaderSource);
                throw err;
            }
            this.profiler.event('backend', 'GlContext.draw()', () => {
                this.glContext.draw();
            });
        }, this.glContext);
    }
    dispose() {
        if (this.vertexShader) {
            this.glContext.deleteShader(this.vertexShader);
        }
        this.repo.forEach(a => this.glContext.deleteProgram(a.program));
    }
    build(programInfo, inputTextureLayouts, outputTextureLayout) {
        return this.profiler.event('backend', 'ProgramManager.build', () => {
            const preprocessor = new glsl_preprocessor_1.GlslPreprocessor(this.glContext, programInfo, inputTextureLayouts, outputTextureLayout);
            const fragScript = preprocessor.preprocess();
            const program = this.compile(fragScript);
            const artifact = {
                programInfo,
                program,
                uniformLocations: this.getUniformLocations(program, preprocessor.context.programInfo.inputNames, preprocessor.context.programInfo.variables),
                attribLocations: this.getAttribLocations(program)
            };
            return artifact;
        });
    }
    compile(fragShaderScript) {
        if (!this.vertexShader) {
            instrument_1.Logger.verbose('ProrgramManager', 'Compiling and caching Vertex shader for the first time');
            const vertexShaderScript = (0, glsl_source_1.getVertexShaderSource)(this.glContext.version);
            this.vertexShader = this.glContext.compileShader(vertexShaderScript, this.glContext.gl.VERTEX_SHADER);
        }
        if (onnxruntime_common_1.env.debug) {
            instrument_1.Logger.verbose('ProrgramManager', `FragShader:
${fragShaderScript}
`);
        }
        const fragShader = this.glContext.compileShader(fragShaderScript, this.glContext.gl.FRAGMENT_SHADER);
        const program = this.glContext.createProgram(this.vertexShader, fragShader);
        this.glContext.deleteShader(fragShader);
        return program;
    }
    bindOutput(td) {
        const width = td.width;
        const height = td.height;
        instrument_1.Logger.verbose('ProrgramManager', `Binding output texture to Framebuffer: w/h=${width}/${height}, shape=${td.shape}, type=${td.tensor.type}`);
        this.glContext.attachFramebuffer(td.texture, width, height);
    }
    bindAttributes(attribLocations) {
        const positionHandle = attribLocations.position;
        const textureCoordHandle = attribLocations.textureCoord;
        this.glContext.setVertexAttributes(positionHandle, textureCoordHandle);
        this.attributesBound = true;
    }
    bindUniforms(uniformLocations, variables, textures) {
        var _a;
        const gl = this.glContext.gl;
        let texturePosition = 0;
        for (const { name, type, location, arrayLength } of uniformLocations) {
            const value = (_a = variables.find(v => v.name === name)) === null || _a === void 0 ? void 0 : _a.data;
            if (type !== 'sampler2D' && !value) {
                throw new Error(`variable '${name}' does not have data defined in program info`);
            }
            switch (type) {
                case 'sampler2D':
                    this.bindTexture(textures[texturePosition], location, texturePosition);
                    texturePosition++;
                    break;
                case 'float':
                    if (arrayLength) {
                        gl.uniform1fv(location, value);
                    }
                    else {
                        gl.uniform1f(location, value);
                    }
                    break;
                case 'int':
                    if (arrayLength) {
                        gl.uniform1iv(location, value);
                    }
                    else {
                        gl.uniform1i(location, value);
                    }
                    break;
                default:
                    throw new Error(`Uniform not implemented: ${type}`);
            }
        }
    }
    bindTexture(td, uniformHandle, position) {
        this.glContext.bindTextureToUniform(td.texture, position, uniformHandle);
    }
    getAttribLocations(program) {
        return {
            position: this.getAttribLocation(program, 'position'),
            textureCoord: this.getAttribLocation(program, 'textureCoord')
        };
    }
    getUniformLocations(program, samplers, variables) {
        const uniformLocations = [];
        if (samplers) {
            for (const sampler of samplers) {
                uniformLocations.push({ name: sampler, type: 'sampler2D', location: this.getUniformLocation(program, sampler) });
            }
        }
        if (variables) {
            for (const variable of variables) {
                uniformLocations.push(Object.assign(Object.assign({}, variable), { location: this.getUniformLocation(program, variable.name) }));
            }
        }
        return uniformLocations;
    }
    getUniformLocation(program, name) {
        const gl = this.glContext.gl;
        const reference = gl.getUniformLocation(program, name);
        if (reference === null) {
            throw new Error(`Uniform ${name} not found.`);
        }
        return reference;
    }
    getAttribLocation(program, name) {
        const gl = this.glContext.gl;
        const attributeLocation = gl.getAttribLocation(program, name);
        return attributeLocation;
    }
}
exports.ProgramManager = ProgramManager;


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/session-handler.ts":
/*!******************************************************!*\
  !*** ./lib/onnxjs/backends/webgl/session-handler.ts ***!
  \******************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.WebGLSessionHandler = void 0;
const instrument_1 = __webpack_require__(/*! ../../instrument */ "./lib/onnxjs/instrument.ts");
const opset_1 = __webpack_require__(/*! ../../opset */ "./lib/onnxjs/opset.ts");
const inference_handler_1 = __webpack_require__(/*! ./inference-handler */ "./lib/onnxjs/backends/webgl/inference-handler.ts");
const op_resolve_rules_1 = __webpack_require__(/*! ./op-resolve-rules */ "./lib/onnxjs/backends/webgl/op-resolve-rules.ts");
const program_manager_1 = __webpack_require__(/*! ./program-manager */ "./lib/onnxjs/backends/webgl/program-manager.ts");
const texture_layout_strategy_1 = __webpack_require__(/*! ./texture-layout-strategy */ "./lib/onnxjs/backends/webgl/texture-layout-strategy.ts");
const texture_manager_1 = __webpack_require__(/*! ./texture-manager */ "./lib/onnxjs/backends/webgl/texture-manager.ts");
class WebGLSessionHandler {
    constructor(backend, context) {
        this.backend = backend;
        this.context = context;
        this.layoutStrategy = new texture_layout_strategy_1.PreferLogicalStrategy(backend.glContext.maxTextureSize);
        this.programManager = new program_manager_1.ProgramManager(this.context.profiler, backend.glContext, this.layoutStrategy);
        this.textureManager = new texture_manager_1.TextureManager(backend.glContext, this.layoutStrategy, this.context.profiler, { reuseTextures: backend.textureCacheMode === 'full' });
        this.packedTextureDataCache = new Map();
        this.unpackedTextureDataCache = new Map();
        this.pack = backend.pack;
        this.pack2unpackMap = new Map();
        this.unpack2packMap = new Map();
    }
    createInferenceHandler() {
        return new inference_handler_1.WebGLInferenceHandler(this);
    }
    onGraphInitialized(graph) {
        const initializers = graph.getValues().filter(v => v.from === -1 && v.tensor).map(v => v.tensor.dataId);
        this.initializers = new Set(initializers);
    }
    isInitializer(tensorId) {
        return this.initializers ? this.initializers.has(tensorId) : false;
    }
    addInitializer(tensorId) {
        this.initializers.add(tensorId);
    }
    getTextureData(tensorId, isPacked) {
        if (isPacked) {
            return this.packedTextureDataCache.get(tensorId);
        }
        else {
            return this.unpackedTextureDataCache.get(tensorId);
        }
    }
    setTextureData(tensorId, textureData, isPacked = false) {
        instrument_1.Logger.verbose('WebGLSessionHandler', 'Storing Texture data in cache');
        if (isPacked) {
            this.packedTextureDataCache.set(tensorId, textureData);
        }
        else {
            this.unpackedTextureDataCache.set(tensorId, textureData);
        }
    }
    dispose() {
        this.programManager.dispose();
        this.textureManager.clearActiveTextures();
        this.packedTextureDataCache.forEach(td => this.textureManager.releaseTexture(td, true));
        this.packedTextureDataCache = new Map();
        this.unpackedTextureDataCache.forEach(td => this.textureManager.releaseTexture(td, true));
        this.unpackedTextureDataCache = new Map();
    }
    resolve(node, opsets, graph) {
        const op = (0, opset_1.resolveOperator)(node, opsets, op_resolve_rules_1.WEBGL_OP_RESOLVE_RULES);
        return { impl: op.opImpl, context: op.opInit ? op.opInit(node, graph) : node };
    }
}
exports.WebGLSessionHandler = WebGLSessionHandler;


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/texture-data-encoder.ts":
/*!***********************************************************!*\
  !*** ./lib/onnxjs/backends/webgl/texture-data-encoder.ts ***!
  \***********************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Uint8DataEncoder = exports.RGBAFloatDataEncoder = exports.RedFloat32DataEncoder = void 0;
const instrument_1 = __webpack_require__(/*! ../../instrument */ "./lib/onnxjs/instrument.ts");
/**
 * WebGL2 data encoder
 * Uses R32F as the format for texlet
 */
class RedFloat32DataEncoder {
    constructor(gl, channels = 1) {
        if (channels === 1) {
            this.internalFormat = gl.R32F;
            this.format = gl.RED;
            this.textureType = gl.FLOAT;
            this.channelSize = channels;
        }
        else if (channels === 4) {
            this.internalFormat = gl.RGBA32F;
            this.format = gl.RGBA;
            this.textureType = gl.FLOAT;
            this.channelSize = channels;
        }
        else {
            throw new Error(`Invalid number of channels: ${channels}`);
        }
    }
    encode(src, textureSize) {
        let result;
        let source;
        if (src.constructor !== Float32Array) {
            instrument_1.Logger.warning('Encoder', 'data was not of type Float32; creating new Float32Array');
            source = new Float32Array(src);
        }
        if (textureSize * this.channelSize > src.length) {
            instrument_1.Logger.warning('Encoder', 'Source data too small. Allocating larger array');
            source = src;
            result = this.allocate(textureSize * this.channelSize);
            source.forEach((v, i) => result[i] = v);
        }
        else {
            source = src;
            result = source;
        }
        return result;
    }
    allocate(size) {
        return new Float32Array(size * 4);
    }
    decode(buffer, dataSize) {
        if (this.channelSize === 1) {
            const filteredData = buffer.filter((value, index) => index % 4 === 0).subarray(0, dataSize);
            return filteredData;
        }
        return buffer.subarray(0, dataSize);
    }
}
exports.RedFloat32DataEncoder = RedFloat32DataEncoder;
/**
 * Data encoder for WebGL 1 with support for floating point texture
 */
class RGBAFloatDataEncoder {
    constructor(gl, channels = 1, textureType) {
        if (channels !== 1 && channels !== 4) {
            throw new Error(`Invalid number of channels: ${channels}`);
        }
        this.internalFormat = gl.RGBA;
        this.format = gl.RGBA;
        this.channelSize = channels;
        this.textureType = textureType || gl.FLOAT;
    }
    encode(src, textureSize) {
        let dest = src;
        if (this.channelSize === 1) {
            instrument_1.Logger.verbose('Encoder', 'Exploding into a larger array');
            dest = this.allocate(textureSize);
            src.forEach((v, i) => dest[i * 4] = v);
        }
        return dest;
    }
    allocate(size) {
        return new Float32Array(size * 4);
    }
    decode(buffer, dataSize) {
        if (this.channelSize === 1) {
            const filteredData = buffer.filter((value, index) => index % 4 === 0).subarray(0, dataSize);
            return filteredData;
        }
        return buffer.subarray(0, dataSize);
    }
}
exports.RGBAFloatDataEncoder = RGBAFloatDataEncoder;
class Uint8DataEncoder {
    constructor(gl, channels = 1) {
        this.channelSize = 4;
        if (channels === 1) {
            this.internalFormat = gl.ALPHA;
            this.format = gl.ALPHA; // not tested
            this.textureType = gl.UNSIGNED_BYTE;
            this.channelSize = channels;
        }
        else if (channels === 4) {
            this.internalFormat = gl.RGBA;
            this.format = gl.RGBA;
            this.textureType = gl.UNSIGNED_BYTE;
            this.channelSize = channels;
        }
        else {
            throw new Error(`Invalid number of channels: ${channels}`);
        }
    }
    encode(src, _textureSize) {
        return new Uint8Array(src.buffer, src.byteOffset, src.byteLength);
    }
    allocate(size) {
        return new Uint8Array(size * this.channelSize);
    }
    decode(buffer, dataSize) {
        if (buffer instanceof Uint8Array) {
            return buffer.subarray(0, dataSize);
        }
        throw new Error(`Invalid array type: ${buffer.constructor}`);
    }
}
exports.Uint8DataEncoder = Uint8DataEncoder;


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/texture-layout-strategy.ts":
/*!**************************************************************!*\
  !*** ./lib/onnxjs/backends/webgl/texture-layout-strategy.ts ***!
  \**************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getBatchDim = exports.sizeToSquarishShape = exports.getRowsCols = exports.sizeFromShape = exports.isInt = exports.parseAxisParam = exports.squeezeShape = exports.PreferLogicalStrategy = exports.AlwaysKeepOriginalSizeStrategy = void 0;
const instrument_1 = __webpack_require__(/*! ../../instrument */ "./lib/onnxjs/instrument.ts");
const util_1 = __webpack_require__(/*! ../../util */ "./lib/onnxjs/util.ts");
/**
 * This strategy try to find the minimal max(W,H) that fulfills (W * H == totalSize)
 */
class AlwaysKeepOriginalSizeStrategy {
    constructor(maxTextureSize) {
        this.maxTextureSize = maxTextureSize;
    }
    computeTextureWH(shape, prefs) {
        // scalar tensor
        if (shape.length === 0) {
            return [1, 1];
        }
        const maxTextureSize = this.maxTextureSize;
        if (prefs && prefs.breakAxis !== undefined) {
            // check to see if dims fit
            const wsize = prefs.breakAxis >= shape.length ? 1 : shape.slice(prefs.breakAxis).reduce((a, b) => a * b);
            const hsize = prefs.breakAxis <= 0 ? 1 : shape.slice(0, prefs.breakAxis).reduce((a, b) => a * b);
            if (wsize > maxTextureSize || hsize > maxTextureSize) {
                // ignore preferences
                // continue with default layout
                instrument_1.Logger.verbose('TextureLayout', `Given width/height preferences were unattainable: shape:${shape}, breakAxis:${prefs.breakAxis}`);
            }
            else {
                return [wsize, hsize];
            }
        }
        const totalSize = shape.reduce((a, b) => a * b);
        let width = Math.floor(Math.sqrt(totalSize));
        for (; width < maxTextureSize && width < totalSize; width++) {
            if (totalSize % width === 0) {
                break;
            }
        }
        if (width >= maxTextureSize || totalSize % width !== 0) {
            throw new Error(`The given dimensions are outside this GPU's boundaries: ${shape}`);
        }
        return [width, totalSize / width];
    }
}
exports.AlwaysKeepOriginalSizeStrategy = AlwaysKeepOriginalSizeStrategy;
class PreferLogicalStrategy {
    constructor(maxTextureSize) {
        this.maxTextureSize = maxTextureSize;
    }
    computeTextureWH(shape, prefs) {
        const wh = this.computeTexture(shape, prefs);
        if (prefs && prefs.isPacked) {
            wh[0] /= 2;
            wh[1] /= 2;
        }
        if (prefs && prefs.reverseWH) {
            return [wh[1], wh[0]];
        }
        return wh;
    }
    computeTexture(shape, prefs) {
        const isPacked = prefs && prefs.isPacked;
        // scalar tensor
        if (shape.length === 0) {
            return isPacked ? [2, 2] : [1, 1];
        }
        let maxTextureSize = this.maxTextureSize;
        if (prefs && prefs.breakAxis !== undefined) {
            // check to see if dims fit
            const wsize = prefs.breakAxis >= shape.length ? 1 : shape.slice(prefs.breakAxis).reduce((a, b) => a * b);
            const hsize = prefs.breakAxis <= 0 ? 1 : shape.slice(0, prefs.breakAxis).reduce((a, b) => a * b);
            if (wsize > maxTextureSize || hsize > maxTextureSize) {
                // ignore preferences
                // continue with default layout
                instrument_1.Logger.verbose('TextureLayout', `Given width/height preferences were unattainable: shape:${shape}, breakAxis:${prefs.breakAxis}`);
            }
            else {
                return [wsize, hsize];
            }
        }
        let logShape = shape.slice(0);
        if (isPacked) {
            maxTextureSize = maxTextureSize * 2;
            // This logic ensures we accurately count the number of packed texels needed
            // to accommodate the tensor. We can only pack values in the same texel if
            // they are from adjacent pairs of rows/cols within the same batch. So if a
            // tensor has 3 rows, we pretend it has 4 rows in order to account for the
            // fact that the texels containing the third row are half empty.
            logShape = logShape.map((d, i) => i >= logShape.length - 2 ? (logShape[i] % 2 === 0 ? logShape[i] : logShape[i] + 1) : logShape[i]);
            // Packed texture height is at least 2 (the channel height of a single
            // texel).
            if (logShape.length === 1) {
                logShape = [2, logShape[0]];
            }
        }
        // If logical shape is 2, we don't squeeze, since we want to match physical.
        if (logShape.length !== 2) {
            const squeezeResult = squeezeShape(logShape);
            logShape = squeezeResult.newShape;
        }
        const size = sizeFromShape(logShape);
        if (logShape.length <= 1 && size <= maxTextureSize) {
            return [1, size];
        }
        else if (logShape.length === 2 && logShape[0] <= maxTextureSize && logShape[1] <= maxTextureSize) {
            return logShape;
        }
        else if (logShape.length === 3 && logShape[0] * logShape[1] <= maxTextureSize && logShape[2] <= maxTextureSize) {
            return [logShape[0] * logShape[1], logShape[2]];
        }
        else if (logShape.length === 3 && logShape[0] <= maxTextureSize && logShape[1] * logShape[2] <= maxTextureSize) {
            return [logShape[0], logShape[1] * logShape[2]];
        }
        else if (logShape.length === 4 && logShape[0] * logShape[1] * logShape[2] <= maxTextureSize &&
            logShape[3] <= maxTextureSize) {
            return [logShape[0] * logShape[1] * logShape[2], logShape[3]];
        }
        else if (logShape.length === 4 && logShape[0] <= maxTextureSize &&
            logShape[1] * logShape[2] * logShape[3] <= maxTextureSize) {
            return [logShape[0], logShape[1] * logShape[2] * logShape[3]];
        }
        else {
            if (isPacked) {
                // For packed textures size equals the number of channels required to
                // accommodate the texture data. However in order to squarify such that
                // inner dimensions stay even, we rewrite size to equal the number of
                // texels. Then in the return statement we rehydrate the squarified
                // dimensions to channel units.
                return sizeToSquarishShape(size / 4).map(d => d * 2);
            }
            return sizeToSquarishShape(size);
        }
    }
}
exports.PreferLogicalStrategy = PreferLogicalStrategy;
function squeezeShape(shape, axis) {
    const newShape = [];
    const keptDims = [];
    const isEmptyArray = axis != null && Array.isArray(axis) && axis.length === 0;
    const axes = (axis == null || isEmptyArray) ? null : parseAxisParam(axis, shape).sort();
    let j = 0;
    for (let i = 0; i < shape.length; ++i) {
        if (axes != null) {
            if (axes[j] === i && shape[i] !== 1) {
                throw new Error(`Can't squeeze axis ${i} since its dim '${shape[i]}' is not 1`);
            }
            if ((axes[j] == null || axes[j] > i) && shape[i] === 1) {
                newShape.push(shape[i]);
                keptDims.push(i);
            }
            if (axes[j] <= i) {
                j++;
            }
        }
        if (shape[i] !== 1) {
            newShape.push(shape[i]);
            keptDims.push(i);
        }
    }
    return { newShape, keptDims };
}
exports.squeezeShape = squeezeShape;
function parseAxisParam(axis, shape) {
    const rank = shape.length;
    // Normalize input
    axis = axis == null ? shape.map((s, i) => i) : [].concat(axis);
    // Check for valid range
    (0, util_1.assert)(axis.every(ax => ax >= -rank && ax < rank), () => `All values in axis param must be in range [-${rank}, ${rank}) but ` +
        `got axis ${axis}`);
    // Check for only integers
    (0, util_1.assert)(axis.every(isInt), () => 'All values in axis param must be integers but ' +
        `got axis ${axis}`);
    // Handle negative axis.
    return axis.map(a => a < 0 ? rank + a : a);
}
exports.parseAxisParam = parseAxisParam;
function isInt(a) {
    return a % 1 === 0;
}
exports.isInt = isInt;
function sizeFromShape(shape) {
    if (shape.length === 0) {
        // Scalar.
        return 1;
    }
    let size = shape[0];
    for (let i = 1; i < shape.length; i++) {
        size *= shape[i];
    }
    return size;
}
exports.sizeFromShape = sizeFromShape;
function getRowsCols(shape) {
    if (shape.length === 0) {
        throw Error('Cannot get rows and columns of an empty shape array.');
    }
    return [shape.length > 1 ? shape[shape.length - 2] : 1, shape[shape.length - 1]];
}
exports.getRowsCols = getRowsCols;
function sizeToSquarishShape(size) {
    const width = Math.ceil(Math.sqrt(size));
    return [width, Math.ceil(size / width)];
}
exports.sizeToSquarishShape = sizeToSquarishShape;
function getBatchDim(shape, dimsToSkip = 2) {
    return sizeFromShape(shape.slice(0, shape.length - dimsToSkip));
}
exports.getBatchDim = getBatchDim;


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/texture-layout.ts":
/*!*****************************************************!*\
  !*** ./lib/onnxjs/backends/webgl/texture-layout.ts ***!
  \*****************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.createTextureLayoutFromShape = exports.calculateTextureWidthAndHeight = exports.createTextureLayoutFromTextureType = void 0;
const util_1 = __webpack_require__(/*! ../../util */ "./lib/onnxjs/util.ts");
const types_1 = __webpack_require__(/*! ./types */ "./lib/onnxjs/backends/webgl/types.ts");
const createTextureLayoutFromTextureType = (textureLayoutStrategy, shape, textureType) => {
    const channel = (textureType === types_1.TextureType.unpacked || textureType === types_1.TextureType.unpackedReversed) ? 1 : 4;
    const isPacked = textureType === types_1.TextureType.packed;
    const reverseWH = (textureType === types_1.TextureType.unpackedReversed || textureType === types_1.TextureType.packed);
    const breakAxis = textureType === types_1.TextureType.packedLastDimension ? shape.length - 1 : undefined;
    const unpackedShape = textureType === types_1.TextureType.packedLastDimension ?
        shape.map((d, i) => i === shape.length - 1 ? d * 4 : d) :
        undefined;
    return (0, exports.createTextureLayoutFromShape)(textureLayoutStrategy, shape, channel, unpackedShape, { isPacked, reverseWH, breakAxis });
};
exports.createTextureLayoutFromTextureType = createTextureLayoutFromTextureType;
const calculateTextureWidthAndHeight = (textureLayoutStrategy, shape, textureType) => {
    const layout = (0, exports.createTextureLayoutFromTextureType)(textureLayoutStrategy, shape, textureType);
    return [layout.width, layout.height];
};
exports.calculateTextureWidthAndHeight = calculateTextureWidthAndHeight;
/**
 * Create a TextureLayout object from shape.
 */
const createTextureLayoutFromShape = (textureLayoutStrategy, shape, channels = 1, unpackedShape, prefs) => {
    const isPacked = !!(prefs && prefs.isPacked);
    const [width, height] = textureLayoutStrategy.computeTextureWH(isPacked ? unpackedShape || shape : shape, prefs);
    const rank = shape.length;
    let inferredDims = shape.slice(0);
    if (rank === 0) {
        inferredDims = [1];
    }
    if (channels === 1) {
        // unpackedShape will take `shape` and not `inferredDims` so as to create a scalar Tensor if need be
        unpackedShape = shape;
    }
    else if (isPacked) {
        if (channels !== 4) {
            throw new Error('a packed texture must be 4-channel');
        }
        unpackedShape = shape;
        if (rank > 0) {
            inferredDims[rank - 1] = Math.ceil(inferredDims[rank - 1] / 2);
        }
        if (rank > 1) {
            inferredDims[rank - 2] = Math.ceil(inferredDims[rank - 2] / 2);
        }
    }
    else if (!unpackedShape) {
        throw new Error('Unpacked shape is needed when using channels > 1');
    }
    return {
        width,
        height,
        channels,
        isPacked,
        shape: inferredDims,
        strides: util_1.ShapeUtil.computeStrides(inferredDims),
        unpackedShape,
        reversedWH: (prefs && prefs.reverseWH)
    };
};
exports.createTextureLayoutFromShape = createTextureLayoutFromShape;


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/texture-manager.ts":
/*!******************************************************!*\
  !*** ./lib/onnxjs/backends/webgl/texture-manager.ts ***!
  \******************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.TextureManager = void 0;
const instrument_1 = __webpack_require__(/*! ../../instrument */ "./lib/onnxjs/instrument.ts");
/**
 * TextureManager is the mainly responsible for caching Textures
 * Textures are cached in 2 levels:
 *   1. the texures which are associated with a dataId (from Tensor)
 *    Caching these is crucial to performance. These are In-use Textures
 *   2. textures which are not in use by any current ProgramInfo/Tensor
 *     These are called Free Textures
 * TextureManager is also used to help creating textures. For this it
 * uses WebGLContext and TextureLayoutStrategy
 */
class TextureManager {
    constructor(glContext, layoutStrategy, profiler, config) {
        this.glContext = glContext;
        this.layoutStrategy = layoutStrategy;
        this.profiler = profiler;
        this.config = config;
        this.pendingRead = new Map();
        if (config.reuseTextures) {
            this.inUseTextures = new Map();
            this.idleTextures = new Map();
            this.textureLookup = new Map();
        }
    }
    createTextureFromLayout(dataType, layout, data, usage) {
        const textureDataType = this.toEncoderType(dataType);
        const encoder = this.glContext.getEncoder(textureDataType, layout.channels || 1, usage);
        if (layout.isPacked && usage === 1 /* Encoder.Usage.UploadOnly */) {
            throw new Error('not implemented');
        }
        const width = layout.width;
        const height = layout.height;
        let key;
        let inUseTextures;
        if (this.config.reuseTextures) {
            key = `${width}x${height}_${encoder.format}_${encoder.internalFormat}_${encoder.textureType}`;
            inUseTextures = this.inUseTextures.get(key);
            if (!inUseTextures) {
                inUseTextures = [];
                this.inUseTextures.set(key, inUseTextures);
            }
            const idleTextures = this.idleTextures.get(key);
            if (idleTextures && idleTextures.length > 0) {
                const texture = idleTextures.pop();
                inUseTextures.push(texture);
                if (usage === 1 /* Encoder.Usage.UploadOnly */) {
                    this.glContext.updateTexture(texture, width, height, encoder, this.toTextureData(dataType, data));
                }
                return texture;
            }
        }
        instrument_1.Logger.verbose('TextureManager', `Creating new texture of size ${layout.width}x${layout.height}`);
        const texture = this.glContext.allocateTexture(width, height, encoder, this.toTextureData(dataType, data));
        if (this.config.reuseTextures) {
            inUseTextures.push(texture);
            this.textureLookup.set(texture, key);
        }
        return texture;
    }
    readTexture(td, dataType, channels) {
        if (!channels) {
            channels = 1;
        }
        return this.profiler.event('backend', 'TextureManager.readTexture', () => {
            const dataSize = td.shape.reduce((a, b) => a * b) * channels;
            const data = this.glContext.readTexture(td.texture, td.width, td.height, dataSize, this.toEncoderType(dataType), channels);
            return this.toTensorData(dataType, data);
        });
    }
    async readTextureAsync(td, dataType, channels) {
        const dataId = td.tensor.dataId;
        if (!channels) {
            channels = 1;
        }
        if (this.pendingRead.has(dataId)) {
            const subscribers = this.pendingRead.get(dataId);
            return new Promise(resolve => subscribers === null || subscribers === void 0 ? void 0 : subscribers.push(resolve));
        }
        return this.profiler.event('backend', 'TextureManager.readTextureAsync', async () => {
            this.pendingRead.set(dataId, []);
            const dataSize = td.shape.reduce((a, b) => a * b) * channels;
            // add a fence waiting for the data to be ready
            await this.glContext.createAndWaitForFence();
            const data = this.glContext.readTexture(td.texture, td.width, td.height, dataSize, this.toEncoderType(dataType), channels);
            const tensorData = this.toTensorData(dataType, data);
            const subscribers = this.pendingRead.get(dataId);
            this.pendingRead.delete(dataId);
            subscribers === null || subscribers === void 0 ? void 0 : subscribers.forEach(resolve => resolve(tensorData));
            return tensorData;
        });
    }
    readUint8TextureAsFloat(td) {
        return this.profiler.event('backend', 'TextureManager.readUint8TextureAsFloat', () => {
            const dataSize = td.shape.reduce((a, b) => a * b);
            const data = this.glContext.readTexture(td.texture, td.width, td.height, dataSize * 4, 'byte', 4);
            return new Float32Array(data.buffer, data.byteOffset, dataSize);
        });
    }
    releaseTexture(textureData, deleteTexture) {
        let key;
        if (this.config.reuseTextures) {
            key = this.textureLookup.get(textureData.texture);
            if (key) {
                if (deleteTexture) {
                    this.textureLookup.delete(key);
                }
                const inUseTextures = this.inUseTextures.get(key);
                if (inUseTextures) {
                    const index = inUseTextures.indexOf(textureData.texture);
                    if (index !== -1) {
                        inUseTextures.splice(index, 1);
                        let idleTextures = this.idleTextures.get(key);
                        if (!idleTextures) {
                            idleTextures = [];
                            this.idleTextures.set(key, idleTextures);
                        }
                        idleTextures.push(textureData.texture);
                    }
                }
            }
        }
        if (!key || deleteTexture) {
            instrument_1.Logger.verbose('TextureManager', `Deleting texture of size ${textureData.width}x${textureData.height}`);
            this.glContext.deleteTexture(textureData.texture);
        }
    }
    toTensorData(dataType, data) {
        switch (dataType) {
            case 'int16':
                return data instanceof Int16Array ? data : Int16Array.from(data);
            case 'int32':
                return data instanceof Int32Array ? data : Int32Array.from(data);
            case 'int8':
                return data instanceof Int8Array ? data : Int8Array.from(data);
            case 'uint16':
                return data instanceof Uint16Array ? data : Uint16Array.from(data);
            case 'uint32':
                return data instanceof Uint32Array ? data : Uint32Array.from(data);
            case 'uint8':
            case 'bool':
                return data instanceof Uint8Array ? data : Uint8Array.from(data);
            case 'float32':
                return data instanceof Float32Array ? data : Float32Array.from(data);
            case 'float64':
                return data instanceof Float64Array ? data : Float64Array.from(data);
            default:
                throw new Error(`TensorData type ${dataType} is not supported`);
        }
    }
    toTextureData(dataType, data) {
        if (!data) {
            return undefined;
        }
        return (data instanceof Float32Array) ? data : new Float32Array(data);
        /*
        switch (dataType) {
          case 'int16':
          case 'int32':
          case 'uint16':
          case 'uint32':
            return (data.constructor === Uint32Array) ? data as Uint32Array : new Uint32Array(data);
          case 'int8':
          case 'uint8':
          case 'bool':
            return (data.constructor === Uint8Array) ? data as Uint8Array : new Uint8Array(data);
          case 'float32':
          case 'float64':
            return (data.constructor === Float32Array) ? data as Float32Array : new Float32Array(data);
          default:
            throw new Error(`TensorData type ${dataType} is not supported`);
        }
        */
    }
    toEncoderType(_dataType) {
        return 'float';
        // switch (dataType) {
        //   case 'int16':
        //   case 'int32':
        //   case 'uint16':
        //   case 'uint32':
        //     return 'int';
        //   case 'uint8':
        //   case 'bool':
        //     return 'byte';
        //   case 'float32':
        //   case 'float64':
        //     return 'float';
        //   default:
        //     throw new Error(`TensorData type ${dataType} is not supported`);
        // }
    }
    clearActiveTextures() {
        this.glContext.clearActiveTextures();
    }
}
exports.TextureManager = TextureManager;


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/types.ts":
/*!********************************************!*\
  !*** ./lib/onnxjs/backends/webgl/types.ts ***!
  \********************************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.TextureType = void 0;
var TextureType;
(function (TextureType) {
    TextureType[TextureType["unpacked"] = 0] = "unpacked";
    TextureType[TextureType["unpackedReversed"] = 1] = "unpackedReversed";
    TextureType[TextureType["packed"] = 2] = "packed";
    TextureType[TextureType["downloadUint8AsFloat"] = 3] = "downloadUint8AsFloat";
    TextureType[TextureType["packedLastDimension"] = 4] = "packedLastDimension"; // <-- ONLY used in old ONNX.js Conv implementation for input W (deprecated)
})(TextureType = exports.TextureType || (exports.TextureType = {}));


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/utils.ts":
/*!********************************************!*\
  !*** ./lib/onnxjs/backends/webgl/utils.ts ***!
  \********************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getGlChannels = exports.getCoordsDataType = exports.getSqueezedParams = exports.squeezeInputShape = exports.generateShaderFuncNameFromInputSamplerNameAtOutCoords = exports.generateShaderFuncNameFromInputSamplerName = exports.repeatedTry = exports.getPackedShape = void 0;
const util_1 = __webpack_require__(/*! ../../util */ "./lib/onnxjs/util.ts");
/**
 * Given a non RGBA shape calculate the R version
 * It is assumed that the dimensions are multiples of given channels
 * NOTE: it is always the last dim that gets packed.
 * @param unpackedShape original shape to create a packed version from
 */
function getPackedShape(unpackedShape) {
    const len = unpackedShape.length;
    return unpackedShape.slice(0, len - 1).concat(unpackedShape[len - 1] / 4);
}
exports.getPackedShape = getPackedShape;
async function repeatedTry(checkFn, delayFn = (_counter) => 0, maxCounter) {
    return new Promise((resolve, reject) => {
        let tryCount = 0;
        const tryFn = () => {
            if (checkFn()) {
                resolve();
                return;
            }
            tryCount++;
            const nextBackoff = delayFn(tryCount);
            if (maxCounter != null && tryCount >= maxCounter) {
                reject();
                return;
            }
            setTimeout(tryFn, nextBackoff);
        };
        tryFn();
    });
}
exports.repeatedTry = repeatedTry;
/**
 * Generates the function name from an input sampler name.
 * @param samplerName Name of the sampler.
 */
function generateShaderFuncNameFromInputSamplerName(samplerName) {
    (0, util_1.assert)(typeof samplerName !== 'undefined' && samplerName.length !== 0, () => 'empty string found for sampler name');
    return 'get' + samplerName.charAt(0).toUpperCase() + samplerName.slice(1);
}
exports.generateShaderFuncNameFromInputSamplerName = generateShaderFuncNameFromInputSamplerName;
/**
 * Generates the function name from an input sampler name at output coordinates.
 * @param samplerName Name of the sampler.
 */
function generateShaderFuncNameFromInputSamplerNameAtOutCoords(samplerName) {
    (0, util_1.assert)(typeof samplerName !== 'undefined' && samplerName.length !== 0, () => 'empty string found for sampler name');
    return 'get' + samplerName.charAt(0).toUpperCase() + samplerName.slice(1) + 'AtOutCoords';
}
exports.generateShaderFuncNameFromInputSamplerNameAtOutCoords = generateShaderFuncNameFromInputSamplerNameAtOutCoords;
/** Returns a new input shape (a copy) that has a squeezed logical shape. */
function squeezeInputShape(inputShape, squeezedShape) {
    // Deep copy.
    let newInputShape = JSON.parse(JSON.stringify(inputShape));
    newInputShape = squeezedShape;
    return newInputShape;
}
exports.squeezeInputShape = squeezeInputShape;
/** Returns a list of squeezed parameters for shader functions */
function getSqueezedParams(params, keptDims) {
    return keptDims.map(d => params[d]).join(', ');
}
exports.getSqueezedParams = getSqueezedParams;
/** Returns the data type for different ranks. */
function getCoordsDataType(rank) {
    if (rank <= 1) {
        return 'int';
    }
    else if (rank === 2) {
        return 'ivec2';
    }
    else if (rank === 3) {
        return 'ivec3';
    }
    else if (rank === 4) {
        return 'ivec4';
    }
    else if (rank === 5) {
        return 'ivec5';
    }
    else if (rank === 6) {
        return 'ivec6';
    }
    else {
        throw Error(`GPU for rank ${rank} is not yet supported`);
    }
}
exports.getCoordsDataType = getCoordsDataType;
function getGlChannels(rank = 6) {
    return ['x', 'y', 'z', 'w', 'u', 'v'].slice(0, rank);
}
exports.getGlChannels = getGlChannels;


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/webgl-context-factory.ts":
/*!************************************************************!*\
  !*** ./lib/onnxjs/backends/webgl/webgl-context-factory.ts ***!
  \************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.createNewWebGLContext = exports.createWebGLContext = void 0;
const instrument_1 = __webpack_require__(/*! ../../instrument */ "./lib/onnxjs/instrument.ts");
const webgl_context_1 = __webpack_require__(/*! ./webgl-context */ "./lib/onnxjs/backends/webgl/webgl-context.ts");
const cache = {};
/**
 * This factory function creates proper WebGLRenderingContext based on
 * the current browsers capabilities
 * The order is from higher/most recent versions to most basic
 */
function createWebGLContext(contextId) {
    let context;
    if ((!contextId || contextId === 'webgl2') && 'webgl2' in cache) {
        context = cache.webgl2;
    }
    else if ((!contextId || contextId === 'webgl') && 'webgl' in cache) {
        context = cache.webgl;
    }
    context = context || createNewWebGLContext(contextId);
    contextId = contextId || context.version === 1 ? 'webgl' : 'webgl2';
    const gl = context.gl;
    cache[contextId] = context;
    if (gl.isContextLost()) {
        delete cache[contextId];
        return createWebGLContext(contextId);
    }
    gl.disable(gl.DEPTH_TEST);
    gl.disable(gl.STENCIL_TEST);
    gl.disable(gl.BLEND);
    gl.disable(gl.DITHER);
    gl.disable(gl.POLYGON_OFFSET_FILL);
    gl.disable(gl.SAMPLE_COVERAGE);
    gl.enable(gl.SCISSOR_TEST);
    gl.enable(gl.CULL_FACE);
    gl.cullFace(gl.BACK);
    return context;
}
exports.createWebGLContext = createWebGLContext;
function createNewWebGLContext(contextId) {
    const canvas = createCanvas();
    const contextAttributes = {
        alpha: false,
        depth: false,
        antialias: false,
        stencil: false,
        preserveDrawingBuffer: false,
        premultipliedAlpha: false,
        failIfMajorPerformanceCaveat: false
    };
    let gl;
    const ca = contextAttributes;
    if (!contextId || contextId === 'webgl2') {
        gl = canvas.getContext('webgl2', ca);
        if (gl) {
            try {
                return new webgl_context_1.WebGLContext(gl, 2);
            }
            catch (err) {
                instrument_1.Logger.warning('GlContextFactory', `failed to create WebGLContext using contextId 'webgl2'. Error: ${err}`);
            }
        }
    }
    if (!contextId || contextId === 'webgl') {
        gl = canvas.getContext('webgl', ca) || canvas.getContext('experimental-webgl', ca);
        if (gl) {
            try {
                return new webgl_context_1.WebGLContext(gl, 1);
            }
            catch (err) {
                instrument_1.Logger.warning('GlContextFactory', `failed to create WebGLContext using contextId 'webgl' or 'experimental-webgl'. Error: ${err}`);
            }
        }
    }
    throw new Error('WebGL is not supported');
}
exports.createNewWebGLContext = createNewWebGLContext;
function createCanvas() {
    if (typeof document === 'undefined') {
        if (typeof OffscreenCanvas === 'undefined') {
            throw new TypeError('failed to create canvas: OffscreenCanvas is not supported');
        }
        return new OffscreenCanvas(1, 1);
    }
    const canvas = document.createElement('canvas');
    canvas.width = 1;
    canvas.height = 1;
    return canvas;
}


/***/ }),

/***/ "./lib/onnxjs/backends/webgl/webgl-context.ts":
/*!****************************************************!*\
  !*** ./lib/onnxjs/backends/webgl/webgl-context.ts ***!
  \****************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.WebGLContext = exports.linearSearchLastTrue = void 0;
const onnxruntime_common_1 = __webpack_require__(/*! onnxruntime-common */ "../common/dist/lib/index.js");
const DataEncoders = __importStar(__webpack_require__(/*! ./texture-data-encoder */ "./lib/onnxjs/backends/webgl/texture-data-encoder.ts"));
const utils_1 = __webpack_require__(/*! ./utils */ "./lib/onnxjs/backends/webgl/utils.ts");
function linearSearchLastTrue(arr) {
    let i = 0;
    for (; i < arr.length; ++i) {
        const isDone = arr[i]();
        if (!isDone) {
            break;
        }
    }
    return i - 1;
}
exports.linearSearchLastTrue = linearSearchLastTrue;
/**
 * Abstraction and wrapper around WebGLRenderingContext and its operations
 */
class WebGLContext {
    constructor(gl, version) {
        this.frameBufferBound = false;
        this.itemsToPoll = [];
        this.gl = gl;
        this.version = version;
        this.getExtensions();
        this.vertexbuffer = this.createVertexbuffer();
        this.framebuffer = this.createFramebuffer();
        this.queryVitalParameters();
    }
    allocateTexture(width, height, encoder, data) {
        const gl = this.gl;
        // create the texture
        const texture = gl.createTexture();
        // bind the texture so the following methods effect this texture.
        gl.bindTexture(gl.TEXTURE_2D, texture);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
        const buffer = data ? encoder.encode(data, width * height) : null;
        gl.texImage2D(gl.TEXTURE_2D, 0, // Level of detail.
        encoder.internalFormat, width, height, 0, // Always 0 in OpenGL ES.
        encoder.format, encoder.textureType, buffer);
        this.checkError();
        return texture;
    }
    updateTexture(texture, width, height, encoder, data) {
        const gl = this.gl;
        gl.bindTexture(gl.TEXTURE_2D, texture);
        const buffer = encoder.encode(data, width * height);
        gl.texSubImage2D(gl.TEXTURE_2D, 0, // level
        0, // xoffset
        0, // yoffset
        width, height, encoder.format, encoder.textureType, buffer);
        this.checkError();
    }
    attachFramebuffer(texture, width, height) {
        const gl = this.gl;
        // Make it the target for framebuffer operations - including rendering.
        gl.bindTexture(gl.TEXTURE_2D, texture);
        gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer);
        gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0); // 0, we aren't using MIPMAPs
        this.checkError();
        gl.viewport(0, 0, width, height);
        gl.scissor(0, 0, width, height);
    }
    readTexture(texture, width, height, dataSize, dataType, channels) {
        const gl = this.gl;
        if (!channels) {
            channels = 1;
        }
        if (!this.frameBufferBound) {
            this.attachFramebuffer(texture, width, height);
        }
        const encoder = this.getEncoder(dataType, channels);
        const buffer = encoder.allocate(width * height);
        // bind texture to framebuffer
        gl.bindTexture(gl.TEXTURE_2D, texture);
        gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0); // 0, we aren't using MIPMAPs
        // TODO: Check if framebuffer is ready
        gl.readPixels(0, 0, width, height, gl.RGBA, encoder.textureType, buffer);
        this.checkError();
        // unbind FB
        return encoder.decode(buffer, dataSize);
    }
    isFramebufferReady() {
        // TODO: Implement logic to check if the framebuffer is ready
        return true;
    }
    getActiveTexture() {
        const gl = this.gl;
        const n = gl.getParameter(this.gl.ACTIVE_TEXTURE);
        return `TEXTURE${(n - gl.TEXTURE0)}`;
    }
    getTextureBinding() {
        return this.gl.getParameter(this.gl.TEXTURE_BINDING_2D);
    }
    getFramebufferBinding() {
        return this.gl.getParameter(this.gl.FRAMEBUFFER_BINDING);
    }
    setVertexAttributes(positionHandle, textureCoordHandle) {
        const gl = this.gl;
        gl.vertexAttribPointer(positionHandle, 3, gl.FLOAT, false, 20, 0);
        gl.enableVertexAttribArray(positionHandle);
        if (textureCoordHandle !== -1) {
            gl.vertexAttribPointer(textureCoordHandle, 2, gl.FLOAT, false, 20, 12);
            gl.enableVertexAttribArray(textureCoordHandle);
        }
        this.checkError();
    }
    createProgram(vertexShader, fragShader) {
        const gl = this.gl;
        const program = gl.createProgram();
        // the program consists of our shaders
        gl.attachShader(program, vertexShader);
        gl.attachShader(program, fragShader);
        gl.linkProgram(program);
        return program;
    }
    compileShader(shaderSource, shaderType) {
        const gl = this.gl;
        const shader = gl.createShader(shaderType);
        if (!shader) {
            throw new Error(`createShader() returned null with type ${shaderType}`);
        }
        gl.shaderSource(shader, shaderSource);
        gl.compileShader(shader);
        if (gl.getShaderParameter(shader, gl.COMPILE_STATUS) === false) {
            throw new Error(`Failed to compile shader: ${gl.getShaderInfoLog(shader)}
Shader source:
${shaderSource}`);
        }
        return shader;
    }
    deleteShader(shader) {
        this.gl.deleteShader(shader);
    }
    bindTextureToUniform(texture, position, uniformHandle) {
        const gl = this.gl;
        gl.activeTexture(gl.TEXTURE0 + position);
        this.checkError();
        gl.bindTexture(gl.TEXTURE_2D, texture);
        this.checkError();
        gl.uniform1i(uniformHandle, position);
        this.checkError();
    }
    draw() {
        this.gl.drawArrays(this.gl.TRIANGLE_STRIP, 0, 4);
        this.checkError();
    }
    checkError() {
        if (onnxruntime_common_1.env.debug) {
            const gl = this.gl;
            const error = gl.getError();
            let label = '';
            switch (error) {
                case (gl.NO_ERROR):
                    return;
                case (gl.INVALID_ENUM):
                    label = 'INVALID_ENUM';
                    break;
                case (gl.INVALID_VALUE):
                    label = 'INVALID_VALUE';
                    break;
                case (gl.INVALID_OPERATION):
                    label = 'INVALID_OPERATION';
                    break;
                case (gl.INVALID_FRAMEBUFFER_OPERATION):
                    label = 'INVALID_FRAMEBUFFER_OPERATION';
                    break;
                case (gl.OUT_OF_MEMORY):
                    label = 'OUT_OF_MEMORY';
                    break;
                case (gl.CONTEXT_LOST_WEBGL):
                    label = 'CONTEXT_LOST_WEBGL';
                    break;
                default:
                    label = `Unknown WebGL Error: ${error.toString(16)}`;
            }
            throw new Error(label);
        }
    }
    deleteTexture(texture) {
        this.gl.deleteTexture(texture);
    }
    deleteProgram(program) {
        this.gl.deleteProgram(program);
    }
    getEncoder(dataType, channels, usage = 0 /* Encoder.Usage.Default */) {
        if (this.version === 2) {
            return new DataEncoders.RedFloat32DataEncoder(this.gl, channels);
        }
        switch (dataType) {
            case 'float':
                if (usage === 1 /* Encoder.Usage.UploadOnly */ || this.isRenderFloat32Supported) {
                    return new DataEncoders.RGBAFloatDataEncoder(this.gl, channels);
                }
                else {
                    return new DataEncoders.RGBAFloatDataEncoder(this.gl, channels, this.textureHalfFloatExtension.HALF_FLOAT_OES);
                }
            case 'int':
                throw new Error('not implemented');
            case 'byte':
                return new DataEncoders.Uint8DataEncoder(this.gl, channels);
            default:
                throw new Error(`Invalid dataType: ${dataType}`);
        }
    }
    clearActiveTextures() {
        const gl = this.gl;
        for (let unit = 0; unit < this.maxTextureImageUnits; ++unit) {
            gl.activeTexture(gl.TEXTURE0 + unit);
            gl.bindTexture(gl.TEXTURE_2D, null);
        }
    }
    dispose() {
        if (this.disposed) {
            return;
        }
        const gl = this.gl;
        gl.bindFramebuffer(gl.FRAMEBUFFER, null);
        gl.deleteFramebuffer(this.framebuffer);
        gl.bindBuffer(gl.ARRAY_BUFFER, null);
        gl.deleteBuffer(this.vertexbuffer);
        gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
        gl.finish();
        this.disposed = true;
    }
    createDefaultGeometry() {
        // Sets of x,y,z(=0),s,t coordinates.
        return new Float32Array([
            -1.0, 1.0, 0.0, 0.0, 1.0,
            -1.0, -1.0, 0.0, 0.0, 0.0,
            1.0, 1.0, 0.0, 1.0, 1.0,
            1.0, -1.0, 0.0, 1.0, 0.0 // lower right
        ]);
    }
    createVertexbuffer() {
        const gl = this.gl;
        const buffer = gl.createBuffer();
        if (!buffer) {
            throw new Error('createBuffer() returned null');
        }
        const geometry = this.createDefaultGeometry();
        gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
        gl.bufferData(gl.ARRAY_BUFFER, geometry, gl.STATIC_DRAW);
        this.checkError();
        return buffer;
    }
    createFramebuffer() {
        const fb = this.gl.createFramebuffer();
        if (!fb) {
            throw new Error('createFramebuffer returned null');
        }
        return fb;
    }
    queryVitalParameters() {
        const gl = this.gl;
        this.isFloatTextureAttachableToFrameBuffer = this.checkFloatTextureAttachableToFrameBuffer();
        this.isRenderFloat32Supported = this.checkRenderFloat32();
        this.isFloat32DownloadSupported = this.checkFloat32Download();
        if (this.version === 1 && !this.textureHalfFloatExtension && !this.isRenderFloat32Supported) {
            throw new Error('both float32 and float16 TextureType are not supported');
        }
        this.isBlendSupported = !this.isRenderFloat32Supported || this.checkFloat32Blend();
        // this.maxCombinedTextureImageUnits = gl.getParameter(gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
        this.maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
        this.maxTextureImageUnits = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS);
        // this.maxCubeMapTextureSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE);
        // this.shadingLanguageVersion = gl.getParameter(gl.SHADING_LANGUAGE_VERSION);
        // this.webglVendor = gl.getParameter(gl.VENDOR);
        // this.webglVersion = gl.getParameter(gl.VERSION);
        if (this.version === 2) {
            // this.max3DTextureSize = gl.getParameter(WebGL2RenderingContext.MAX_3D_TEXTURE_SIZE);
            // this.maxArrayTextureLayers = gl.getParameter(WebGL2RenderingContext.MAX_ARRAY_TEXTURE_LAYERS);
            // this.maxColorAttachments = gl.getParameter(WebGL2RenderingContext.MAX_COLOR_ATTACHMENTS);
            // this.maxDrawBuffers = gl.getParameter(WebGL2RenderingContext.MAX_DRAW_BUFFERS);
        }
    }
    getExtensions() {
        if (this.version === 2) {
            this.colorBufferFloatExtension = this.gl.getExtension('EXT_color_buffer_float');
            this.disjointTimerQueryWebgl2Extension = this.gl.getExtension('EXT_disjoint_timer_query_webgl2');
        }
        else {
            this.textureFloatExtension = this.gl.getExtension('OES_texture_float');
            this.textureHalfFloatExtension = this.gl.getExtension('OES_texture_half_float');
        }
    }
    checkFloatTextureAttachableToFrameBuffer() {
        // test whether Float32 texture is supported:
        // STEP.1 create a float texture
        const gl = this.gl;
        const texture = gl.createTexture();
        gl.bindTexture(gl.TEXTURE_2D, texture);
        // eslint-disable-next-line @typescript-eslint/naming-convention
        const internalFormat = this.version === 2 ? gl.RGBA32F : gl.RGBA;
        gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, 1, 1, 0, gl.RGBA, gl.FLOAT, null);
        // STEP.2 bind a frame buffer
        const frameBuffer = gl.createFramebuffer();
        gl.bindFramebuffer(gl.FRAMEBUFFER, frameBuffer);
        // STEP.3 attach texture to framebuffer
        gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
        // STEP.4 test whether framebuffer is complete
        const isComplete = gl.checkFramebufferStatus(gl.FRAMEBUFFER) === gl.FRAMEBUFFER_COMPLETE;
        gl.bindTexture(gl.TEXTURE_2D, null);
        gl.bindFramebuffer(gl.FRAMEBUFFER, null);
        gl.deleteTexture(texture);
        gl.deleteFramebuffer(frameBuffer);
        return isComplete;
    }
    checkRenderFloat32() {
        if (this.version === 2) {
            if (!this.colorBufferFloatExtension) {
                return false;
            }
        }
        else {
            if (!this.textureFloatExtension) {
                return false;
            }
        }
        return this.isFloatTextureAttachableToFrameBuffer;
    }
    checkFloat32Download() {
        if (this.version === 2) {
            if (!this.colorBufferFloatExtension) {
                return false;
            }
        }
        else {
            if (!this.textureFloatExtension) {
                return false;
            }
            if (!this.gl.getExtension('WEBGL_color_buffer_float')) {
                return false;
            }
        }
        return this.isFloatTextureAttachableToFrameBuffer;
    }
    /**
     * Check whether GL_BLEND is supported
     */
    checkFloat32Blend() {
        // it looks like currently (2019-05-08) there is no easy way to detect whether BLEND is supported
        // https://github.com/microsoft/onnxjs/issues/145
        const gl = this.gl;
        let texture;
        let frameBuffer;
        let vertexShader;
        let fragmentShader;
        let program;
        try {
            texture = gl.createTexture();
            frameBuffer = gl.createFramebuffer();
            gl.bindTexture(gl.TEXTURE_2D, texture);
            // eslint-disable-next-line @typescript-eslint/naming-convention
            const internalFormat = this.version === 2 ? gl.RGBA32F : gl.RGBA;
            gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, 1, 1, 0, gl.RGBA, gl.FLOAT, null);
            gl.bindFramebuffer(gl.FRAMEBUFFER, frameBuffer);
            gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
            gl.enable(gl.BLEND);
            vertexShader = gl.createShader(gl.VERTEX_SHADER);
            if (!vertexShader) {
                return false;
            }
            gl.shaderSource(vertexShader, 'void main(){}');
            gl.compileShader(vertexShader);
            fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
            if (!fragmentShader) {
                return false;
            }
            gl.shaderSource(fragmentShader, 'precision highp float;void main(){gl_FragColor=vec4(0.5);}');
            gl.compileShader(fragmentShader);
            program = gl.createProgram();
            if (!program) {
                return false;
            }
            gl.attachShader(program, vertexShader);
            gl.attachShader(program, fragmentShader);
            gl.linkProgram(program);
            gl.useProgram(program);
            gl.drawArrays(gl.POINTS, 0, 1);
            return gl.getError() === gl.NO_ERROR;
        }
        finally {
            gl.disable(gl.BLEND);
            if (program) {
                gl.deleteProgram(program);
            }
            if (vertexShader) {
                gl.deleteShader(vertexShader);
            }
            if (fragmentShader) {
                gl.deleteShader(fragmentShader);
            }
            if (frameBuffer) {
                gl.bindFramebuffer(gl.FRAMEBUFFER, null);
                gl.deleteFramebuffer(frameBuffer);
            }
            if (texture) {
                gl.bindTexture(gl.TEXTURE_2D, null);
                gl.deleteTexture(texture);
            }
        }
    }
    beginTimer() {
        if (this.version === 2 && this.disjointTimerQueryWebgl2Extension) {
            const gl2 = this.gl;
            const ext = this.disjointTimerQueryWebgl2Extension;
            const query = gl2.createQuery();
            gl2.beginQuery(ext.TIME_ELAPSED_EXT, query);
            return query;
        }
        else {
            // TODO: add webgl 1 handling.
            throw new Error('WebGL1 profiling currently not supported.');
        }
    }
    endTimer() {
        if (this.version === 2 && this.disjointTimerQueryWebgl2Extension) {
            const gl2 = this.gl;
            const ext = this.disjointTimerQueryWebgl2Extension;
            gl2.endQuery(ext.TIME_ELAPSED_EXT);
            return;
        }
        else {
            // TODO: add webgl 1 handling.
            throw new Error('WebGL1 profiling currently not supported');
        }
    }
    isTimerResultAvailable(query) {
        let available = false, disjoint = false;
        if (this.version === 2 && this.disjointTimerQueryWebgl2Extension) {
            const gl2 = this.gl;
            const ext = this.disjointTimerQueryWebgl2Extension;
            available = gl2.getQueryParameter(query, gl2.QUERY_RESULT_AVAILABLE);
            disjoint = gl2.getParameter(ext.GPU_DISJOINT_EXT);
        }
        else {
            // TODO: add webgl 1 handling.
            throw new Error('WebGL1 profiling currently not supported');
        }
        return available && !disjoint;
    }
    getTimerResult(query) {
        let timeElapsed = 0;
        if (this.version === 2) {
            const gl2 = this.gl;
            timeElapsed = gl2.getQueryParameter(query, gl2.QUERY_RESULT);
            gl2.deleteQuery(query);
        }
        else {
            // TODO: add webgl 1 handling.
            throw new Error('WebGL1 profiling currently not supported');
        }
        // return miliseconds
        return timeElapsed / 1000000;
    }
    async waitForQueryAndGetTime(query) {
        await (0, utils_1.repeatedTry)(() => this.isTimerResultAvailable(query));
        return this.getTimerResult(query);
    }
    async createAndWaitForFence() {
        const fenceContext = this.createFence(this.gl);
        return this.pollFence(fenceContext);
    }
    createFence(gl) {
        let isFencePassed;
        const gl2 = gl;
        const query = gl2.fenceSync(gl2.SYNC_GPU_COMMANDS_COMPLETE, 0);
        gl.flush();
        if (query === null) {
            isFencePassed = () => true;
        }
        else {
            isFencePassed = () => {
                const status = gl2.clientWaitSync(query, 0, 0);
                return status === gl2.ALREADY_SIGNALED || status === gl2.CONDITION_SATISFIED;
            };
        }
        return { query, isFencePassed };
    }
    async pollFence(fenceContext) {
        return new Promise(resolve => {
            void this.addItemToPoll(() => fenceContext.isFencePassed(), () => resolve());
        });
    }
    pollItems() {
        // Find the last query that has finished.
        const index = linearSearchLastTrue(this.itemsToPoll.map(x => x.isDoneFn));
        for (let i = 0; i <= index; ++i) {
            const { resolveFn } = this.itemsToPoll[i];
            resolveFn();
        }
        this.itemsToPoll = this.itemsToPoll.slice(index + 1);
    }
    async addItemToPoll(isDoneFn, resolveFn) {
        this.itemsToPoll.push({ isDoneFn, resolveFn });
        if (this.itemsToPoll.length > 1) {
            // We already have a running loop that polls.
            return;
        }
        // Start a new loop that polls.
        await (0, utils_1.repeatedTry)(() => {
            this.pollItems();
            // End the loop if no more items to poll.
            return this.itemsToPoll.length === 0;
        });
    }
}
exports.WebGLContext = WebGLContext;


/***/ }),

/***/ "./lib/onnxjs/execution-plan.ts":
/*!**************************************!*\
  !*** ./lib/onnxjs/execution-plan.ts ***!
  \**************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ExecutionPlan = void 0;
const instrument_1 = __webpack_require__(/*! ./instrument */ "./lib/onnxjs/instrument.ts");
class KernelOp {
    constructor(op, node) {
        this.op = op;
        this.node = node;
    }
}
class ExecutionPlan {
    constructor(graph, ops, profiler) {
        this.graph = graph;
        this.profiler = profiler;
        this.initialize(ops);
    }
    initialize(ops) {
        this.profiler.event('session', 'ExecutionPlan.initialize', () => {
            const graphNodes = this.graph.getNodes();
            if (graphNodes.length !== ops.length) {
                throw new Error('The size of nodes and OPs do not match.');
            }
            this._ops = ops.map((op, i) => new KernelOp(op, graphNodes[i]));
            this.reset();
            // look for starter node(s)
            this._starter = [];
            this._ops.forEach((op, i) => {
                let resolved = true;
                for (const input of op.node.inputs) {
                    if (!this._values[input] // not an initialized input
                        && this.graph.getInputIndices().indexOf(input) === -1 // not model input
                    ) {
                        resolved = false;
                        break;
                    }
                }
                if (resolved) {
                    this._starter.push(i);
                }
            });
        });
    }
    reset() {
        this._values = this.graph.getValues().map(i => i.tensor);
    }
    async execute(sessionHandler, modelInputs) {
        return this.profiler.event('session', 'ExecutionPlan.execute', async () => {
            // reset mediem result
            this.reset();
            // create inference handler
            const inferenceHandler = sessionHandler.createInferenceHandler();
            // populate inputs value
            const graphInputs = this.graph.getInputIndices();
            if (modelInputs.length !== graphInputs.length) {
                throw new Error(`number of input tensors don't match the number of inputs to the model: actual: ${modelInputs.length} expected: ${graphInputs.length}`);
            }
            modelInputs.forEach((input, i) => {
                const index = graphInputs[i];
                this._values[index] = input;
            });
            // prepare running sequence
            const sequence = this._starter.slice(0);
            // execution iterations
            const graphValues = this.graph.getValues();
            const graphNodes = this.graph.getNodes();
            let rear = 0;
            while (rear < sequence.length) {
                const thisOpIndex = sequence[rear++];
                const thisOp = this._ops[thisOpIndex];
                // check input
                const inputList = thisOp.node.inputs.map(i => this._values[i]);
                if (inputList.indexOf(undefined) !== -1) {
                    throw new Error(`unresolved input detected: op: ${thisOp.node}`);
                }
                // run
                const inputTensors = inputList;
                instrument_1.Logger.verbose('ExecPlan', `Runing op:${thisOp.node.name} (${inputTensors.map((t, i) => `'${thisOp.node.inputs[i]}': ${t.type}[${t.dims.join(',')}]`).join(', ')})`);
                const outputList = await this.profiler.event('node', thisOp.node.name, async () => thisOp.op.impl(inferenceHandler, inputTensors, thisOp.op.context));
                // check output
                if (outputList.length !== thisOp.node.outputs.length) {
                    throw new Error('the size of output does not match model definition.');
                }
                // fill value
                outputList.forEach((output, i) => {
                    const j = thisOp.node.outputs[i];
                    if (this._values[j]) {
                        throw new Error(`output [${j}] already has value: op:${thisOp.node.name}`);
                    }
                    this._values[j] = output;
                });
                // resolve downstream nodes
                const downstreamNodes = new Set();
                outputList.forEach((output, i) => {
                    const j = thisOp.node.outputs[i];
                    for (const currentDownstreamNodeIndex of graphValues[j].to) {
                        const currentDownstreamNode = graphNodes[currentDownstreamNodeIndex];
                        let resolved = true;
                        for (const k of currentDownstreamNode.inputs) {
                            if (!this._values[k]) {
                                resolved = false;
                                break;
                            }
                        }
                        if (resolved) {
                            downstreamNodes.add(currentDownstreamNodeIndex);
                        }
                    }
                });
                sequence.push(...downstreamNodes);
            }
            const output = [];
            for (let i = 0; i < this.graph.getOutputIndices().length; i++) {
                const outputIndex = this.graph.getOutputIndices()[i];
                const outputTensor = this._values[outputIndex];
                if (outputTensor === undefined) {
                    throw new Error(`required output [${outputIndex}] does not have value`);
                }
                if (outputIndex === 0) {
                    await outputTensor.getData();
                }
                else {
                    // eslint-disable-next-line no-unused-expressions
                    outputTensor.data;
                }
                output.push(outputTensor);
            }
            instrument_1.Logger.verbose('ExecPlan', 'disposing of inferenceHandler');
            inferenceHandler.dispose();
            return output;
        });
    }
}
exports.ExecutionPlan = ExecutionPlan;


/***/ }),

/***/ "./lib/onnxjs/graph.ts":
/*!*****************************!*\
  !*** ./lib/onnxjs/graph.ts ***!
  \*****************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Graph = void 0;
const onnx_proto_1 = __webpack_require__(/*! onnx-proto */ "./node_modules/onnx-proto/dist/onnx.js");
const attribute_1 = __webpack_require__(/*! ./attribute */ "./lib/onnxjs/attribute.ts");
const ort_generated_1 = __webpack_require__(/*! ./ort-schema/ort-generated */ "./lib/onnxjs/ort-schema/ort-generated.ts");
const tensor_1 = __webpack_require__(/*! ./tensor */ "./lib/onnxjs/tensor.ts");
const util_1 = __webpack_require__(/*! ./util */ "./lib/onnxjs/util.ts");
var ortFbs = ort_generated_1.onnxruntime.experimental.fbs;
// eslint-disable-next-line @typescript-eslint/naming-convention, @typescript-eslint/no-redeclare
exports.Graph = {
    /**
     * construct a graph from a graph protobuf type
     */
    from: (graphProto, initializer) => new GraphImpl(graphProto, initializer),
};
class Value {
    constructor(valueInfo) {
        this._from = undefined;
        this._to = [];
        this.tensor = undefined;
        this.type = undefined;
        if (valueInfo) {
            this.type = util_1.ProtoUtil.tensorValueTypeFromProto(valueInfo.type.tensorType);
        }
    }
    get from() {
        return this._from;
    }
    get to() {
        return this._to;
    }
}
class Node {
    constructor(_nodeProto, name) {
        if (_nodeProto instanceof onnx_proto_1.onnx.NodeProto) {
            this.name = _nodeProto.name;
            this.opType = _nodeProto.opType;
            this.attributes = new attribute_1.Attribute(_nodeProto.attribute);
        }
        else if (_nodeProto instanceof ortFbs.Node) {
            this.name = name !== null && name !== void 0 ? name : _nodeProto.name();
            this.opType = _nodeProto.opType();
            this.attributes = new attribute_1.Attribute(util_1.ProtoUtil.tensorAttributesFromORTFormat(_nodeProto));
        }
        this.inputs = [];
        this.outputs = [];
        this.executeNode = true;
    }
}
class GraphImpl {
    constructor(graph, graphInitializer) {
        if (!graph) {
            throw new TypeError('graph is empty');
        }
        // build the graph - will throw exceptions if something fatal is detected
        this.buildGraph(graph);
        // execute any transformation logic for the graph (if applicable)
        this.transformGraph(graphInitializer);
        // check for cycles and other inconsistencies - will throw exceptions if something fatal is detected
        this.checkIsAcyclic();
    }
    getInputIndices() {
        return this._allInputIndices;
    }
    getInputNames() {
        return this._allInputNames;
    }
    getOutputIndices() {
        return this._allOutputIndices;
    }
    getOutputNames() {
        return this._allOutputNames;
    }
    getValues() {
        return this._allData;
    }
    getNodes() {
        return this._nodes;
    }
    buildGraph(graph) {
        // build the graph - will throw exceptions if something fatal is detected
        if (graph instanceof onnx_proto_1.onnx.GraphProto) {
            this.buildGraphFromOnnxFormat(graph);
        }
        else if (graph instanceof ortFbs.Graph) {
            this.buildGraphFromOrtFormat(graph);
        }
        else {
            throw new TypeError('Graph type is not supported.');
        }
    }
    buildGraphFromOnnxFormat(graph) {
        const dataIndices = new Map();
        this._allData = [];
        this._allInputIndices = [];
        this._allInputNames = [];
        this._allOutputIndices = [];
        this._allOutputNames = [];
        this._nodes = [];
        const nodesIndices = new Map();
        // scan all inputs
        if (!graph.input) {
            throw new Error('missing information in graph: input');
        }
        const inputValueNames = [];
        for (const i of graph.input) {
            if (dataIndices.has(i.name)) {
                throw new Error(`duplicated input name: ${i.name}`);
            }
            const currentIndex = this._allData.push(new Value(i)) - 1;
            dataIndices.set(i.name, currentIndex);
            inputValueNames.push(i.name);
        }
        // scan all initializers
        if (!graph.initializer) {
            throw new Error('missing information in graph: initializer');
        }
        for (const i of graph.initializer) {
            let index = dataIndices.get(i.name);
            if (index === undefined) {
                const value = new Value();
                value.type = {
                    shape: { dims: util_1.ProtoUtil.tensorDimsFromProto(i.dims) },
                    tensorType: util_1.ProtoUtil.tensorDataTypeFromProto(i.dataType)
                };
                index = this._allData.push(value) - 1;
                dataIndices.set(i.name, index);
            }
            this._allData[index]._from = -1;
            this._allData[index].tensor = tensor_1.Tensor.fromProto(i);
        }
        // filter out input indices
        for (let i = 0; i < this._allData.length; i++) {
            if (!this._allData[i].tensor) {
                this._allInputIndices.push(i);
                this._allInputNames.push(inputValueNames[i]);
            }
        }
        // scan all outputs
        if (!graph.output) {
            throw new Error('missing information in graph: output');
        }
        for (const i of graph.output) {
            if (dataIndices.has(i.name)) {
                throw new Error(`duplicated output name: ${i.name}`);
            }
            const currentIndex = this._allData.push(new Value(i)) - 1;
            dataIndices.set(i.name, currentIndex);
            this._allOutputIndices.push(currentIndex);
            this._allOutputNames.push(i.name);
        }
        // scan all nodes
        if (!graph.node) {
            throw new Error('missing information in graph: node');
        }
        for (const nodeProto of graph.node) {
            if (!nodeProto.name) {
                // assign a name to the node if it doesn't have one
                for (let pick = 0;; pick++) {
                    const name = `unnamed_${nodeProto.opType}_${pick}`;
                    if (!nodesIndices.has(name)) {
                        nodeProto.name = name;
                        break;
                    }
                }
            }
            if (nodesIndices.has(nodeProto.name)) {
                throw new Error(`duplicated node name: ${nodeProto.name}`);
            }
            const currentIndex = this._nodes.push(new Node(nodeProto)) - 1;
            nodesIndices.set(nodeProto.name, currentIndex);
        }
        // scan node's outputs
        for (let i = 0; i < this._nodes.length; i++) {
            const node = this._nodes[i];
            const nodeProto = graph.node[i];
            if (!nodeProto.output) {
                throw new Error(`missing output for node: ${nodeProto.name}`);
            }
            for (const output of nodeProto.output) {
                let dataIndex = dataIndices.get(output);
                if (typeof dataIndex === 'undefined') {
                    dataIndex = this._allData.push(new Value()) - 1;
                    dataIndices.set(output, dataIndex);
                }
                node.outputs.push(dataIndex);
                if (this._allData[dataIndex]._from !== undefined) {
                    throw new Error(`multiple nodes output to one data value: ${dataIndex}`);
                }
                this._allData[dataIndex]._from = i;
                // for the 'Constant' operator, just create a new edge in the graph corresponding to the 'output' of the
                // operator and ignore the node from the graph
                if (nodeProto.opType === 'Constant') {
                    if (!nodeProto.attribute || nodeProto.attribute.length !== 1 || !nodeProto.attribute[0].t) {
                        throw new Error('missing attributes or missing tensor value in attributes for this Constant operator');
                    }
                    if (!nodeProto.output || nodeProto.output.length !== 1) {
                        throw new Error('missing output or incorrect number of outputs for this Constant operator');
                    }
                    node.outputs.pop();
                    node.executeNode = false;
                    this._allData[dataIndex]._from = -1;
                    this._allData[dataIndex].tensor = tensor_1.Tensor.fromProto(nodeProto.attribute[0].t);
                }
            }
        }
        // scan node's inputs
        for (let i = 0; i < this._nodes.length; i++) {
            const node = this._nodes[i];
            const nodeProto = graph.node[i];
            if (!nodeProto.input) {
                throw new Error(`missing input for node: ${nodeProto.name}`);
            }
            for (const input of nodeProto.input) {
                const dataIndex = dataIndices.get(input);
                if (typeof dataIndex === 'undefined') {
                    // handle exception when opset > 9 and roi not given
                    if (input === '' && nodeProto.input.length === 3 && nodeProto.opType === 'Resize') {
                        continue;
                    }
                    throw new Error(`unrecognized input '${input}' for node: ${nodeProto.name}`);
                }
                node.inputs.push(dataIndex);
                this._allData[dataIndex]._to.push(i);
            }
        }
        return true;
    }
    buildGraphFromOrtFormat(graph) {
        var _a, _b, _c;
        const dataIndices = new Map();
        this._allData = [];
        this._allInputIndices = [];
        this._allInputNames = [];
        this._allOutputIndices = [];
        this._allOutputNames = [];
        this._nodes = [];
        const nodesIndices = new Map();
        // scan all inputs
        const inputValueNames = [];
        for (let i = 0; i < graph.inputsLength(); i++) {
            const inputName = graph.inputs(i);
            if (dataIndices.has(inputName)) {
                throw new Error(`duplicated input name: ${inputName}`);
            }
            // Find the input typeInfo from nodeargs
            for (let j = 0; j < graph.nodeArgsLength(); j++) {
                if (((_a = graph.nodeArgs(j)) === null || _a === void 0 ? void 0 : _a.name()) === inputName) {
                    const value = new Value();
                    const valueType = (_c = (_b = graph.nodeArgs(j)) === null || _b === void 0 ? void 0 : _b.type()) === null || _c === void 0 ? void 0 : _c.valueType();
                    if (valueType !== ortFbs.TypeInfoValue.tensor_type) {
                        throw new Error('Unexpected value type for the nodeArg.');
                    }
                    const valueInfo = graph.nodeArgs(j).type().value(new ortFbs.TensorTypeAndShape());
                    const type = util_1.ProtoUtil.tensorDataTypeFromProto(valueInfo.elemType());
                    const shape = valueInfo.shape();
                    const dims = [];
                    for (let k = 0; k < shape.dimLength(); k++) {
                        dims.push(util_1.LongUtil.longToNumber(shape.dim(k).value().dimValue()));
                    }
                    value.type = { shape: { dims }, tensorType: type };
                    const currentIndex = this._allData.push(value) - 1;
                    dataIndices.set(inputName, currentIndex);
                    inputValueNames.push(inputName);
                }
            }
        }
        // check initializers
        for (let i = 0; i < graph.initializersLength(); i++) {
            const initializer = graph.initializers(i);
            let index = dataIndices.get(initializer.name());
            if (index === undefined) {
                const value = new Value();
                const dims = util_1.ProtoUtil.tensorDimsFromORTFormat(initializer);
                const type = util_1.ProtoUtil.tensorDataTypeFromProto(initializer.dataType());
                value.type = { shape: { dims }, tensorType: type };
                index = this._allData.push(value) - 1;
                dataIndices.set(initializer.name(), index);
            }
            this._allData[index]._from = -1;
            this._allData[index].tensor = tensor_1.Tensor.fromOrtTensor(initializer);
        }
        // filter out input indices
        for (let i = 0; i < this._allData.length; i++) {
            if (!this._allData[i].tensor) {
                this._allInputIndices.push(i);
                this._allInputNames.push(inputValueNames[i]);
            }
        }
        // scan all outputs
        for (let i = 0; i < graph.outputsLength(); i++) {
            const outputName = graph.outputs(i);
            if (dataIndices.has(outputName)) {
                throw new Error(`duplicated output name: ${outputName}`);
            }
            const currentIndex = this._allData.push(new Value()) - 1;
            dataIndices.set(outputName, currentIndex);
            this._allOutputIndices.push(currentIndex);
            this._allOutputNames.push(outputName);
        }
        // scan all nodes
        if (!graph.nodes) {
            throw new Error('missing information in graph: node');
        }
        for (let i = 0; i < graph.nodesLength(); i++) {
            const nodeProto = graph.nodes(i);
            let name = nodeProto.name();
            if (!name) {
                // assign a name to the node if it doesn't have one
                for (let pick = 0;; pick++) {
                    name = `unnamed_${nodeProto.opType()}_${pick}`;
                    if (!nodesIndices.has(name)) {
                        // an unique name is found. break.
                        break;
                    }
                }
            }
            if (nodesIndices.has(name)) {
                throw new Error(`duplicated node name: ${name}`);
            }
            const currentIndex = this._nodes.push(new Node(nodeProto, name)) - 1;
            nodesIndices.set(name, currentIndex);
        }
        // scan node's outputs
        for (let i = 0; i < this._nodes.length; i++) {
            const node = this._nodes[i];
            const nodeProto = graph.nodes(i);
            if (nodeProto == null) {
                throw new Error(`No node exists at index ${i}`);
            }
            if ((nodeProto === null || nodeProto === void 0 ? void 0 : nodeProto.outputsLength()) === 0) {
                throw new Error(`missing output for node: ${nodeProto.name}`);
            }
            for (let j = 0; j < (nodeProto === null || nodeProto === void 0 ? void 0 : nodeProto.outputsLength()); j++) {
                const output = nodeProto === null || nodeProto === void 0 ? void 0 : nodeProto.outputs(j);
                let dataIndex = dataIndices.get(output);
                if (typeof dataIndex === 'undefined') {
                    dataIndex = this._allData.push(new Value()) - 1;
                    dataIndices.set(output, dataIndex);
                }
                node.outputs.push(dataIndex);
                if (this._allData[dataIndex]._from !== undefined) {
                    throw new Error(`multiple nodes output to one data value: ${dataIndex}`);
                }
                this._allData[dataIndex]._from = i;
                // for the 'Constant' operator, just create a new edge in the graph corresponding to the 'output' of the
                // operator and ignore the node from the graph
                if (nodeProto.opType() === 'Constant') {
                    if (nodeProto.attributesLength() !== 1 || !nodeProto.attributes(0).t()) {
                        throw new Error('missing attributes or missing tensor value in attributes for this Constant operator');
                    }
                    if (nodeProto.outputsLength() !== 1) {
                        throw new Error('missing output or incorrect number of outputs for this Constant operator');
                    }
                    node.outputs.pop();
                    node.executeNode = false;
                    this._allData[dataIndex]._from = -1;
                    this._allData[dataIndex].tensor = tensor_1.Tensor.fromOrtTensor(nodeProto.attributes(0).t());
                }
            }
        }
        // scan node's inputs
        for (let i = 0; i < this._nodes.length; i++) {
            const node = this._nodes[i];
            const nodeProto = graph.nodes(i);
            if (nodeProto.inputsLength() === 0) {
                throw new Error(`missing input for node: ${nodeProto.name}`);
            }
            for (let j = 0; j < nodeProto.inputsLength(); j++) {
                const input = nodeProto.inputs(j);
                const dataIndex = dataIndices.get(input);
                if (typeof dataIndex === 'undefined') {
                    throw new Error(`unrecognized input '${input}' for node: ${nodeProto.name()}`);
                }
                node.inputs.push(dataIndex);
                this._allData[dataIndex]._to.push(i);
            }
        }
    }
    checkIsAcyclic() {
        // go through the graph and check for cycles or other fatal inconsistencies
        const starters = new Set();
        this._allInputIndices.forEach(i => {
            const data = this._allData[i];
            data._to.forEach(j => {
                starters.add(j);
            });
        });
        // Iterative DFS to check for cycles
        const nodesStack = Array.from(starters);
        const nodesState = new Array(this._nodes.length).fill('white');
        while (nodesStack.length > 0) {
            const nodeIndex = nodesStack.pop();
            // this node has now been processed completely. Mark this node 'black' to denote this.
            if (nodesState[nodeIndex] === 'gray') {
                nodesState[nodeIndex] = 'black';
            }
            else {
                // this node is under processing stage. mark this node 'gray' to denote this.
                nodesStack.push(nodeIndex);
                nodesState[nodeIndex] = 'gray';
                this._nodes[nodeIndex].outputs.forEach((outgoingEdgeIndex) => {
                    const data = this._allData[outgoingEdgeIndex];
                    if (typeof data.tensor !== 'undefined') {
                        throw new Error('node outputs should not be initialized');
                    }
                    if (data._from !== nodeIndex) {
                        throw new Error('from property of the Value object doesn\'t match index of Node being processed');
                    }
                    data._to.forEach((downstreamNodeIndex) => {
                        // back edge found - cyclic
                        if (nodesState[downstreamNodeIndex] === 'gray') {
                            throw new Error('model graph is cyclic');
                        }
                        // tree edge found - continue processing by adding it to stack
                        else if (nodesState[downstreamNodeIndex] === 'white') {
                            nodesStack.push(downstreamNodeIndex);
                        }
                    });
                });
            }
        }
    }
    transformGraph(graphInitializer) {
        // apply common transform
        this.removeAllIdentityNodes();
        this.removeAllDropoutNodes();
        this.fuseConvActivationNodes();
        // apply initializer specific transform
        if (graphInitializer) {
            graphInitializer.transformGraph(this);
        }
        // finalize graph
        this.finalizeGraph();
    }
    /**
     * finalize the graph.
     *
     * this function should be called after all the transformation completed.
     * this function removes all unnecessary nodes and values from the graph
     */
    finalizeGraph() {
        let offset = 0;
        // delete all nodes that are not being executed
        for (let i = 0; i < this._nodes.length; i++) {
            if (!this._nodes[i].executeNode) {
                // delete this node and shift all subsequent nodes up
                offset++;
                // delete all output values
                this._nodes[i].outputs.forEach(ind => {
                    this._allData[ind]._from = -2;
                });
                this._nodes.splice(i, 1);
                i--;
                continue;
            }
            if (offset > 0) {
                // update the value table
                this._nodes[i].inputs.forEach(value => {
                    const ind = this._allData[value]._to.indexOf(i + offset);
                    if (ind !== -1) {
                        this._allData[value]._to[ind] = i;
                    }
                });
                this._nodes[i].outputs.forEach(value => {
                    if (this._allData[value]._from && this._allData[value]._from === i + offset) {
                        this._allData[value]._from = i;
                    }
                });
            }
        }
        offset = 0;
        // delete all values that are not being referenced
        for (let i = 0; i < this._allData.length; i++) {
            // if current value is neither linked to next node, nor an output value, remove it.
            if (this._allData[i].from === -2 && this._allOutputIndices.indexOf(i + offset) === -1) {
                offset++;
                this._allData.splice(i, 1);
                i--;
                continue;
            }
            if (offset > 0) {
                let ind = -1;
                // if current value is neither an input value nor an initializer, find the node it's
                // coming from and update the corresponding node output
                if (this._allData[i].from !== undefined && this._allData[i].from !== -1) {
                    ind = this._nodes[this._allData[i].from].outputs.indexOf(i + offset);
                    if (ind !== -1) {
                        this._nodes[this._allData[i].from].outputs[ind] = i;
                    }
                }
                else {
                    // if current value is an input value, update its reference in inputIndices
                    ind = this._allInputIndices.indexOf(i + offset);
                    if (ind !== -1) {
                        this._allInputIndices[ind] = i;
                    }
                }
                // find the node that the current value is linking to and update its input reference
                this._allData[i].to.forEach(node => {
                    ind = this._nodes[node].inputs.indexOf(i + offset);
                    if (ind !== -1) {
                        this._nodes[node].inputs[ind] = i;
                    }
                });
                if (this._allData[i].to.length === 0) {
                    // if current value is a graph output, update its reference in outputIndices
                    ind = this._allOutputIndices.indexOf(i + offset);
                    if (ind !== -1) {
                        this._allOutputIndices[ind] = i;
                    }
                }
            }
        }
    }
    /**
     * Delete the specifed node. Assume the node has one incoming input and the first output connected to other nodes.
     * An input validation must be done before calling this function.
     * @param nodeIndex The index of node to be deleted
     */
    deleteNode(nodeIndex) {
        const node = this._nodes[nodeIndex];
        if (node.outputs.length > 1) {
            for (let i = 1; i < node.outputs.length; i++) {
                if (this._allData[node.outputs[i]].to.length > 0) {
                    throw new Error('Node deletion with more than one output connected to other nodes is not supported. ');
                }
            }
        }
        // this node wil not be executed
        node.executeNode = false;
        const inputValueIndex = node.inputs[0];
        const outputValueIndex = node.outputs[0];
        const nodesConsumingOutput = this._allData[outputValueIndex].to;
        // remove this node from the to property of the input Value
        const delIndex = this._allData[inputValueIndex].to.indexOf(nodeIndex);
        // should not happen
        if (delIndex === -1) {
            throw new Error('The Value object doesn\'t have the current Node in it\'s \'to\' property ');
        }
        this._allData[inputValueIndex].to.splice(delIndex, 1);
        // clear node indices consuming this output Value
        this._allData[outputValueIndex]._to = [];
        // if the output of this node is a graph output, adjust the index appropriately
        const index = this._allOutputIndices.indexOf(outputValueIndex);
        if (index !== -1) {
            this._allOutputIndices[index] = inputValueIndex;
        }
        // override the inputs for nodes consuming this node's output with the input to this node
        if (nodesConsumingOutput && nodesConsumingOutput.length > 0) {
            for (const nodeIndex of nodesConsumingOutput) {
                const replaceIndex = this._nodes[nodeIndex].inputs.indexOf(outputValueIndex);
                // should not happen
                if (replaceIndex === -1) {
                    throw new Error('The Node object doesn\'t have the output Value in it\'s \'inputs\' property ');
                }
                this._nodes[nodeIndex].inputs[replaceIndex] = inputValueIndex;
                this._allData[inputValueIndex].to.push(nodeIndex);
            }
        }
    }
    removeAllDropoutNodes() {
        let nodeIndex = 0;
        for (const node of this._nodes) {
            // weed out 'Dropout' nodes so that no time is wasted in execution
            if (node.opType === 'Dropout') {
                // the node should have exactly 1 input and 1 or 2 outputs
                if (node.inputs.length !== 1) {
                    throw new Error('Dropout nodes should only contain one input. ');
                }
                if (node.outputs.length !== 1 && node.outputs.length !== 2) {
                    throw new Error('Dropout nodes should contain either 1 or 2 output(s)');
                }
                // the second output should not be referenced by any other node
                if (node.outputs.length === 2 && this._allData[node.outputs[1]]._to.length !== 0) {
                    throw new Error('Dropout nodes\'s second output should not be referenced by other nodes');
                }
                this.deleteNode(nodeIndex);
            }
            nodeIndex++;
        }
    }
    removeAllIdentityNodes() {
        let nodeIndex = 0;
        for (const node of this._nodes) {
            // weed out 'Identity' nodes so that no time is wasted in execution
            if (node.opType === 'Identity') {
                this.deleteNode(nodeIndex);
            }
            nodeIndex++;
        }
    }
    isActivation(n) {
        switch (n.opType) {
            // TODO: add other activation methods
            case 'Relu':
            case 'Sigmoid':
            case 'Clip':
                return true;
            default:
                return false;
        }
    }
    fuseConvActivationNodes() {
        for (const node of this._nodes) {
            if (node.opType === 'Conv') {
                const next = this._allData[node.outputs[0]]._to;
                if (next.length === 1 && this.isActivation(this._nodes[next[0]])) {
                    const child = this._nodes[next[0]];
                    if (child.opType === 'Clip') {
                        if (child.inputs.length === 1) {
                            try {
                                node.attributes.set('activation_params', 'floats', [child.attributes.getFloat('min'), child.attributes.getFloat('max')]);
                            }
                            catch (e) {
                                node.attributes.set('activation_params', 'floats', [util_1.MIN_CLIP, util_1.MAX_CLIP]);
                            }
                        }
                        else if (child.inputs.length >= 3 && this._allData[child.inputs[1]].tensor !== undefined &&
                            this._allData[child.inputs[2]].tensor !== undefined) {
                            node.attributes.set('activation_params', 'floats', [
                                this._allData[child.inputs[1]].tensor.floatData[0], this._allData[child.inputs[2]].tensor.floatData[0]
                            ]);
                        }
                        else {
                            // Skip fusion with clip node since clip min and clip max are not coming from initializer
                            continue;
                        }
                    }
                    node.attributes.set('activation', 'string', (child.opType));
                    this.deleteNode(next[0]);
                }
            }
        }
    }
}


/***/ }),

/***/ "./lib/onnxjs/instrument.ts":
/*!**********************************!*\
  !*** ./lib/onnxjs/instrument.ts ***!
  \**********************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.now = exports.Profiler = exports.Logger = void 0;
class NoOpLoggerProvider {
    log(_severity, _content, _category) {
        // do nothing
    }
}
class ConsoleLoggerProvider {
    log(severity, content, category) {
        // eslint-disable-next-line no-console
        console.log(`${this.color(severity)} ${category ? '\x1b[35m' + category + '\x1b[0m ' : ''}${content}`);
    }
    color(severity) {
        switch (severity) {
            case 'verbose':
                return '\x1b[34;40mv\x1b[0m';
            case 'info':
                return '\x1b[32mi\x1b[0m';
            case 'warning':
                return '\x1b[30;43mw\x1b[0m';
            case 'error':
                return '\x1b[31;40me\x1b[0m';
            case 'fatal':
                return '\x1b[101mf\x1b[0m';
            default:
                throw new Error(`unsupported severity: ${severity}`);
        }
    }
}
const SEVERITY_VALUE = {
    verbose: 1000,
    info: 2000,
    warning: 4000,
    error: 5000,
    fatal: 6000
};
const LOGGER_PROVIDER_MAP = {
    ['none']: new NoOpLoggerProvider(),
    ['console']: new ConsoleLoggerProvider()
};
const LOGGER_DEFAULT_CONFIG = {
    provider: 'console',
    minimalSeverity: 'warning',
    logDateTime: true,
    logSourceLocation: false
};
let LOGGER_CONFIG_MAP = { ['']: LOGGER_DEFAULT_CONFIG };
function log(arg0, arg1, arg2, arg3) {
    if (arg1 === undefined) {
        // log(category: string): Logger.CategorizedLogger;
        return createCategorizedLogger(arg0);
    }
    else if (arg2 === undefined) {
        // log(severity, content);
        logInternal(arg0, arg1, 1);
    }
    else if (typeof arg2 === 'number' && arg3 === undefined) {
        // log(severity, content, stack)
        logInternal(arg0, arg1, arg2);
    }
    else if (typeof arg2 === 'string' && arg3 === undefined) {
        // log(severity, category, content)
        logInternal(arg0, arg2, 1, arg1);
    }
    else if (typeof arg2 === 'string' && typeof arg3 === 'number') {
        // log(severity, category, content, stack)
        logInternal(arg0, arg2, arg3, arg1);
    }
    else {
        throw new TypeError('input is valid');
    }
}
function createCategorizedLogger(category) {
    return {
        verbose: log.verbose.bind(null, category),
        info: log.info.bind(null, category),
        warning: log.warning.bind(null, category),
        error: log.error.bind(null, category),
        fatal: log.fatal.bind(null, category)
    };
}
// NOTE: argument 'category' is put the last parameter beacause typescript
// doesn't allow optional argument put in front of required argument. This
// order is different from a usual logging API.
function logInternal(severity, content, stack, category) {
    const config = LOGGER_CONFIG_MAP[category || ''] || LOGGER_CONFIG_MAP[''];
    if (SEVERITY_VALUE[severity] < SEVERITY_VALUE[config.minimalSeverity]) {
        return;
    }
    if (config.logDateTime) {
        content = `${new Date().toISOString()}|${content}`;
    }
    if (config.logSourceLocation) {
        // TODO: calculate source location from 'stack'
    }
    LOGGER_PROVIDER_MAP[config.provider].log(severity, content, category);
}
// eslint-disable-next-line @typescript-eslint/no-namespace
(function (log) {
    function verbose(arg0, arg1) {
        log('verbose', arg0, arg1);
    }
    log.verbose = verbose;
    function info(arg0, arg1) {
        log('info', arg0, arg1);
    }
    log.info = info;
    function warning(arg0, arg1) {
        log('warning', arg0, arg1);
    }
    log.warning = warning;
    function error(arg0, arg1) {
        log('error', arg0, arg1);
    }
    log.error = error;
    function fatal(arg0, arg1) {
        log('fatal', arg0, arg1);
    }
    log.fatal = fatal;
    function reset(config) {
        LOGGER_CONFIG_MAP = {};
        set('', config || {});
    }
    log.reset = reset;
    function set(category, config) {
        if (category === '*') {
            reset(config);
        }
        else {
            const previousConfig = LOGGER_CONFIG_MAP[category] || LOGGER_DEFAULT_CONFIG;
            LOGGER_CONFIG_MAP[category] = {
                provider: config.provider || previousConfig.provider,
                minimalSeverity: config.minimalSeverity || previousConfig.minimalSeverity,
                logDateTime: (config.logDateTime === undefined) ? previousConfig.logDateTime : config.logDateTime,
                logSourceLocation: (config.logSourceLocation === undefined) ? previousConfig.logSourceLocation :
                    config.logSourceLocation
            };
        }
        // TODO: we want to support wildcard or regex?
    }
    log.set = set;
    function setWithEnv(env) {
        const config = {};
        if (env.logLevel) {
            config.minimalSeverity = env.logLevel;
        }
        set('', config);
    }
    log.setWithEnv = setWithEnv;
})(log || (log = {}));
// eslint-disable-next-line @typescript-eslint/no-redeclare, @typescript-eslint/naming-convention
exports.Logger = log;
// TODO
// class WebGLEvent implements Profiler.Event {}
class Event {
    constructor(category, name, startTime, endCallback, timer, ctx) {
        this.category = category;
        this.name = name;
        this.startTime = startTime;
        this.endCallback = endCallback;
        this.timer = timer;
        this.ctx = ctx;
    }
    end() {
        return this.endCallback(this);
    }
    async checkTimer() {
        if (this.ctx === undefined || this.timer === undefined) {
            throw new Error('No webgl timer found');
        }
        else {
            this.ctx.endTimer();
            return this.ctx.waitForQueryAndGetTime(this.timer);
        }
    }
}
class EventRecord {
    constructor(category, name, startTime, endTime) {
        this.category = category;
        this.name = name;
        this.startTime = startTime;
        this.endTime = endTime;
    }
}
class Profiler {
    static create(config) {
        if (config === undefined) {
            return new this();
        }
        return new this(config.maxNumberEvents, config.flushBatchSize, config.flushIntervalInMilliseconds);
    }
    constructor(maxNumberEvents, flushBatchSize, flushIntervalInMilliseconds) {
        this._started = false;
        this._flushPointer = 0;
        this._started = false;
        this._maxNumberEvents = maxNumberEvents === undefined ? 10000 : maxNumberEvents;
        this._flushBatchSize = flushBatchSize === undefined ? 10 : flushBatchSize;
        this._flushIntervalInMilliseconds = flushIntervalInMilliseconds === undefined ? 5000 : flushIntervalInMilliseconds;
    }
    // start profiling
    start() {
        this._started = true;
        this._timingEvents = [];
        this._flushTime = (0, exports.now)();
        this._flushPointer = 0;
    }
    // stop profiling
    stop() {
        this._started = false;
        for (; this._flushPointer < this._timingEvents.length; this._flushPointer++) {
            this.logOneEvent(this._timingEvents[this._flushPointer]);
        }
    }
    event(category, name, func, ctx) {
        const event = this._started ? this.begin(category, name, ctx) : undefined;
        let isPromise = false;
        const res = func();
        // we consider a then-able object is a promise
        if (res && typeof res.then === 'function') {
            isPromise = true;
            return new Promise((resolve, reject) => {
                res
                    .then(async (value) => {
                    if (event) {
                        await event.end();
                    }
                    resolve(value);
                }, async (reason) => {
                    if (event) {
                        await event.end();
                    }
                    reject(reason);
                });
            });
        }
        if (!isPromise && event) {
            const eventRes = event.end();
            if (eventRes && typeof eventRes.then === 'function') {
                return new Promise((resolve, reject) => {
                    (eventRes).then(() => {
                        resolve(res);
                    }, (reason) => {
                        reject(reason);
                    });
                });
            }
        }
        return res;
    }
    // begin an event
    begin(category, name, ctx) {
        if (!this._started) {
            throw new Error('profiler is not started yet');
        }
        if (ctx === undefined) {
            const startTime = (0, exports.now)();
            this.flush(startTime);
            return new Event(category, name, startTime, e => this.endSync(e));
        }
        else {
            const timer = ctx.beginTimer();
            return new Event(category, name, 0, async (e) => this.end(e), timer, ctx);
        }
    }
    // end the specific event
    async end(event) {
        const endTime = await event.checkTimer();
        if (this._timingEvents.length < this._maxNumberEvents) {
            this._timingEvents.push(new EventRecord(event.category, event.name, event.startTime, endTime));
            this.flush(endTime);
        }
    }
    endSync(event) {
        const endTime = (0, exports.now)();
        if (this._timingEvents.length < this._maxNumberEvents) {
            this._timingEvents.push(new EventRecord(event.category, event.name, event.startTime, endTime));
            this.flush(endTime);
        }
    }
    logOneEvent(event) {
        exports.Logger.verbose(`Profiler.${event.category}`, `${(event.endTime - event.startTime).toFixed(2)}ms on event '${event.name}' at ${event.endTime.toFixed(2)}`);
    }
    flush(currentTime) {
        if (this._timingEvents.length - this._flushPointer >= this._flushBatchSize ||
            currentTime - this._flushTime >= this._flushIntervalInMilliseconds) {
            // should flush when either batch size accumlated or interval elepsed
            for (const previousPointer = this._flushPointer; this._flushPointer < previousPointer + this._flushBatchSize &&
                this._flushPointer < this._timingEvents.length; this._flushPointer++) {
                this.logOneEvent(this._timingEvents[this._flushPointer]);
            }
            this._flushTime = (0, exports.now)();
        }
    }
    get started() {
        return this._started;
    }
}
exports.Profiler = Profiler;
/**
 * returns a number to represent the current timestamp in a resolution as high as possible.
 */
exports.now = (typeof performance !== 'undefined' && performance.now) ? () => performance.now() : Date.now;


/***/ }),

/***/ "./lib/onnxjs/model.ts":
/*!*****************************!*\
  !*** ./lib/onnxjs/model.ts ***!
  \*****************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Model = void 0;
const flatbuffers_1 = __webpack_require__(/*! flatbuffers */ "./node_modules/flatbuffers/js/flatbuffers.mjs");
const onnx_proto_1 = __webpack_require__(/*! onnx-proto */ "./node_modules/onnx-proto/dist/onnx.js");
const graph_1 = __webpack_require__(/*! ./graph */ "./lib/onnxjs/graph.ts");
const ort_generated_1 = __webpack_require__(/*! ./ort-schema/ort-generated */ "./lib/onnxjs/ort-schema/ort-generated.ts");
const util_1 = __webpack_require__(/*! ./util */ "./lib/onnxjs/util.ts");
var ortFbs = ort_generated_1.onnxruntime.experimental.fbs;
class Model {
    // empty model
    constructor() { }
    load(buf, graphInitializer, isOrtFormat) {
        if (!isOrtFormat) {
            // isOrtFormat === false || isOrtFormat === undefined
            try {
                this.loadFromOnnxFormat(buf, graphInitializer);
                return;
            }
            catch (e) {
                if (isOrtFormat !== undefined) {
                    throw e;
                }
            }
        }
        this.loadFromOrtFormat(buf, graphInitializer);
    }
    loadFromOnnxFormat(buf, graphInitializer) {
        const modelProto = onnx_proto_1.onnx.ModelProto.decode(buf);
        const irVersion = util_1.LongUtil.longToNumber(modelProto.irVersion);
        if (irVersion < 3) {
            throw new Error('only support ONNX model with IR_VERSION>=3');
        }
        this._opsets =
            modelProto.opsetImport.map(i => ({ domain: i.domain, version: util_1.LongUtil.longToNumber(i.version) }));
        this._graph = graph_1.Graph.from(modelProto.graph, graphInitializer);
    }
    loadFromOrtFormat(buf, graphInitializer) {
        const fb = new flatbuffers_1.flatbuffers.ByteBuffer(buf);
        const ortModel = ortFbs.InferenceSession.getRootAsInferenceSession(fb).model();
        const irVersion = util_1.LongUtil.longToNumber(ortModel.irVersion());
        if (irVersion < 3) {
            throw new Error('only support ONNX model with IR_VERSION>=3');
        }
        this._opsets = [];
        for (let i = 0; i < ortModel.opsetImportLength(); i++) {
            const opsetId = ortModel.opsetImport(i);
            this._opsets.push({ domain: opsetId === null || opsetId === void 0 ? void 0 : opsetId.domain(), version: util_1.LongUtil.longToNumber(opsetId.version()) });
        }
        this._graph = graph_1.Graph.from(ortModel.graph(), graphInitializer);
    }
    get graph() {
        return this._graph;
    }
    get opsets() {
        return this._opsets;
    }
}
exports.Model = Model;


/***/ }),

/***/ "./lib/onnxjs/operators.ts":
/*!*********************************!*\
  !*** ./lib/onnxjs/operators.ts ***!
  \*********************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.FLOAT_TYPES = exports.INT_TYPES = exports.NUMBER_TYPES = void 0;
exports.NUMBER_TYPES = ['float32', 'float64', 'int32', 'int16', 'int8', 'uint16', 'uint32', 'uint8'];
exports.INT_TYPES = ['int32', 'int16', 'int8', 'uint16', 'uint32', 'uint8'];
exports.FLOAT_TYPES = ['float32', 'float64'];


/***/ }),

/***/ "./lib/onnxjs/opset.ts":
/*!*****************************!*\
  !*** ./lib/onnxjs/opset.ts ***!
  \*****************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.resolveOperator = void 0;
function resolveOperator(node, opsets, rules) {
    for (const rule of rules) {
        const opType = rule[0];
        const domain = rule[1];
        const versionSelector = rule[2];
        const opImpl = rule[3];
        const opInit = rule[4];
        if (node.opType === opType) { // operator type matches
            for (const opset of opsets) {
                // opset '' and 'ai.onnx' are considered the same.
                if (opset.domain === domain || (opset.domain === 'ai.onnx' && domain === '')) { // opset domain found
                    if (matchSelector(opset.version, versionSelector)) {
                        return { opImpl, opInit };
                    }
                }
            }
        }
    }
    throw new TypeError(`cannot resolve operator '${node.opType}' with opsets: ${opsets.map(set => `${set.domain || 'ai.onnx'} v${set.version}`).join(', ')}`);
}
exports.resolveOperator = resolveOperator;
function matchSelector(version, selector) {
    if (selector.endsWith('+')) {
        // minimum version match ('7+' expects version>=7)
        const rangeStart = Number.parseInt(selector.substring(0, selector.length - 1), 10);
        return !isNaN(rangeStart) && rangeStart <= version;
    }
    else if (selector.split('-').length === 2) {
        // range match ('6-8' expects 6<=version<=8)
        const pair = selector.split('-');
        const rangeStart = Number.parseInt(pair[0], 10);
        const rangeEnd = Number.parseInt(pair[1], 10);
        return !isNaN(rangeStart) && !isNaN(rangeEnd) && rangeStart <= version && version <= rangeEnd;
    }
    else {
        // exact match ('7' expects version===7)
        return Number.parseInt(selector, 10) === version;
    }
}


/***/ }),

/***/ "./lib/onnxjs/ort-schema/ort-generated.ts":
/*!************************************************!*\
  !*** ./lib/onnxjs/ort-schema/ort-generated.ts ***!
  \************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// automatically generated by the FlatBuffers compiler, do not modify
/* eslint-disable */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.onnxruntime = void 0;
const flatbuffers_1 = __webpack_require__(/*! flatbuffers */ "./node_modules/flatbuffers/js/flatbuffers.mjs");
/**
 * @enum {number}
 */
var onnxruntime;
(function (onnxruntime) {
    var experimental;
    (function (experimental) {
        var fbs;
        (function (fbs) {
            let AttributeType;
            (function (AttributeType) {
                AttributeType[AttributeType["UNDEFINED"] = 0] = "UNDEFINED";
                AttributeType[AttributeType["FLOAT"] = 1] = "FLOAT";
                AttributeType[AttributeType["INT"] = 2] = "INT";
                AttributeType[AttributeType["STRING"] = 3] = "STRING";
                AttributeType[AttributeType["TENSOR"] = 4] = "TENSOR";
                AttributeType[AttributeType["GRAPH"] = 5] = "GRAPH";
                AttributeType[AttributeType["FLOATS"] = 6] = "FLOATS";
                AttributeType[AttributeType["INTS"] = 7] = "INTS";
                AttributeType[AttributeType["STRINGS"] = 8] = "STRINGS";
                AttributeType[AttributeType["TENSORS"] = 9] = "TENSORS";
                AttributeType[AttributeType["GRAPHS"] = 10] = "GRAPHS";
                AttributeType[AttributeType["SPARSE_TENSOR"] = 11] = "SPARSE_TENSOR";
                AttributeType[AttributeType["SPARSE_TENSORS"] = 12] = "SPARSE_TENSORS";
            })(AttributeType = fbs.AttributeType || (fbs.AttributeType = {}));
        })(fbs = experimental.fbs || (experimental.fbs = {}));
    })(experimental = onnxruntime.experimental || (onnxruntime.experimental = {}));
})(onnxruntime = exports.onnxruntime || (exports.onnxruntime = {}));
/**
 * @enum {number}
 */
(function (onnxruntime) {
    var experimental;
    (function (experimental) {
        var fbs;
        (function (fbs) {
            let DimensionValueType;
            (function (DimensionValueType) {
                DimensionValueType[DimensionValueType["UNKNOWN"] = 0] = "UNKNOWN";
                DimensionValueType[DimensionValueType["VALUE"] = 1] = "VALUE";
                DimensionValueType[DimensionValueType["PARAM"] = 2] = "PARAM";
            })(DimensionValueType = fbs.DimensionValueType || (fbs.DimensionValueType = {}));
        })(fbs = experimental.fbs || (experimental.fbs = {}));
    })(experimental = onnxruntime.experimental || (onnxruntime.experimental = {}));
})(onnxruntime = exports.onnxruntime || (exports.onnxruntime = {}));
/**
 * @enum {number}
 */
(function (onnxruntime) {
    var experimental;
    (function (experimental) {
        var fbs;
        (function (fbs) {
            let TensorDataType;
            (function (TensorDataType) {
                TensorDataType[TensorDataType["UNDEFINED"] = 0] = "UNDEFINED";
                TensorDataType[TensorDataType["FLOAT"] = 1] = "FLOAT";
                TensorDataType[TensorDataType["UINT8"] = 2] = "UINT8";
                TensorDataType[TensorDataType["INT8"] = 3] = "INT8";
                TensorDataType[TensorDataType["UINT16"] = 4] = "UINT16";
                TensorDataType[TensorDataType["INT16"] = 5] = "INT16";
                TensorDataType[TensorDataType["INT32"] = 6] = "INT32";
                TensorDataType[TensorDataType["INT64"] = 7] = "INT64";
                TensorDataType[TensorDataType["STRING"] = 8] = "STRING";
                TensorDataType[TensorDataType["BOOL"] = 9] = "BOOL";
                TensorDataType[TensorDataType["FLOAT16"] = 10] = "FLOAT16";
                TensorDataType[TensorDataType["DOUBLE"] = 11] = "DOUBLE";
                TensorDataType[TensorDataType["UINT32"] = 12] = "UINT32";
                TensorDataType[TensorDataType["UINT64"] = 13] = "UINT64";
                TensorDataType[TensorDataType["COMPLEX64"] = 14] = "COMPLEX64";
                TensorDataType[TensorDataType["COMPLEX128"] = 15] = "COMPLEX128";
                TensorDataType[TensorDataType["BFLOAT16"] = 16] = "BFLOAT16";
            })(TensorDataType = fbs.TensorDataType || (fbs.TensorDataType = {}));
        })(fbs = experimental.fbs || (experimental.fbs = {}));
    })(experimental = onnxruntime.experimental || (onnxruntime.experimental = {}));
})(onnxruntime = exports.onnxruntime || (exports.onnxruntime = {}));
/**
 * @enum {number}
 */
(function (onnxruntime) {
    var experimental;
    (function (experimental) {
        var fbs;
        (function (fbs) {
            let NodeType;
            (function (NodeType) {
                NodeType[NodeType["Primitive"] = 0] = "Primitive";
                NodeType[NodeType["Fused"] = 1] = "Fused";
            })(NodeType = fbs.NodeType || (fbs.NodeType = {}));
        })(fbs = experimental.fbs || (experimental.fbs = {}));
    })(experimental = onnxruntime.experimental || (onnxruntime.experimental = {}));
})(onnxruntime = exports.onnxruntime || (exports.onnxruntime = {}));
/**
 * @enum {number}
 */
(function (onnxruntime) {
    var experimental;
    (function (experimental) {
        var fbs;
        (function (fbs) {
            let TypeInfoValue;
            (function (TypeInfoValue) {
                TypeInfoValue[TypeInfoValue["NONE"] = 0] = "NONE";
                TypeInfoValue[TypeInfoValue["tensor_type"] = 1] = "tensor_type";
                TypeInfoValue[TypeInfoValue["sequence_type"] = 2] = "sequence_type";
                TypeInfoValue[TypeInfoValue["map_type"] = 3] = "map_type";
            })(TypeInfoValue = fbs.TypeInfoValue || (fbs.TypeInfoValue = {}));
        })(fbs = experimental.fbs || (experimental.fbs = {}));
    })(experimental = onnxruntime.experimental || (onnxruntime.experimental = {}));
})(onnxruntime = exports.onnxruntime || (exports.onnxruntime = {}));
/**
 * @constructor
 */
(function (onnxruntime) {
    var experimental;
    (function (experimental) {
        var fbs;
        (function (fbs) {
            class Shape {
                constructor() {
                    this.bb = null;
                    this.bb_pos = 0;
                }
                /**
                 * @param number i
                 * @param flatbuffers.ByteBuffer bb
                 * @returns Shape
                 */
                __init(i, bb) {
                    this.bb_pos = i;
                    this.bb = bb;
                    return this;
                }
                /**
                 * @param flatbuffers.ByteBuffer bb
                 * @param Shape= obj
                 * @returns Shape
                 */
                static getRootAsShape(bb, obj) {
                    return (obj || new Shape()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                }
                /**
                 * @param flatbuffers.ByteBuffer bb
                 * @param Shape= obj
                 * @returns Shape
                 */
                static getSizePrefixedRootAsShape(bb, obj) {
                    bb.setPosition(bb.position() + flatbuffers_1.flatbuffers.SIZE_PREFIX_LENGTH);
                    return (obj || new Shape()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                }
                /**
                 * @param number index
                 * @param onnxruntime.experimental.fbs.Dimension= obj
                 * @returns onnxruntime.experimental.fbs.Dimension
                 */
                dim(index, obj) {
                    let offset = this.bb.__offset(this.bb_pos, 4);
                    return offset ? (obj || new onnxruntime.experimental.fbs.Dimension())
                        .__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) :
                        null;
                }
                /**
                 * @returns number
                 */
                dimLength() {
                    let offset = this.bb.__offset(this.bb_pos, 4);
                    return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
                }
                /**
                 * @param flatbuffers.Builder builder
                 */
                static startShape(builder) {
                    builder.startObject(1);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset dimOffset
                 */
                static addDim(builder, dimOffset) {
                    builder.addFieldOffset(0, dimOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param Array.<flatbuffers.Offset> data
                 * @returns flatbuffers.Offset
                 */
                static createDimVector(builder, data) {
                    builder.startVector(4, data.length, 4);
                    for (let i = data.length - 1; i >= 0; i--) {
                        builder.addOffset(data[i]);
                    }
                    return builder.endVector();
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param number numElems
                 */
                static startDimVector(builder, numElems) {
                    builder.startVector(4, numElems, 4);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @returns flatbuffers.Offset
                 */
                static endShape(builder) {
                    let offset = builder.endObject();
                    return offset;
                }
                static createShape(builder, dimOffset) {
                    Shape.startShape(builder);
                    Shape.addDim(builder, dimOffset);
                    return Shape.endShape(builder);
                }
            }
            fbs.Shape = Shape;
        })(fbs = experimental.fbs || (experimental.fbs = {}));
    })(experimental = onnxruntime.experimental || (onnxruntime.experimental = {}));
})(onnxruntime = exports.onnxruntime || (exports.onnxruntime = {}));
/**
 * @constructor
 */
(function (onnxruntime) {
    var experimental;
    (function (experimental) {
        var fbs;
        (function (fbs) {
            class Dimension {
                constructor() {
                    this.bb = null;
                    this.bb_pos = 0;
                }
                /**
                 * @param number i
                 * @param flatbuffers.ByteBuffer bb
                 * @returns Dimension
                 */
                __init(i, bb) {
                    this.bb_pos = i;
                    this.bb = bb;
                    return this;
                }
                /**
                 * @param flatbuffers.ByteBuffer bb
                 * @param Dimension= obj
                 * @returns Dimension
                 */
                static getRootAsDimension(bb, obj) {
                    return (obj || new Dimension()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                }
                /**
                 * @param flatbuffers.ByteBuffer bb
                 * @param Dimension= obj
                 * @returns Dimension
                 */
                static getSizePrefixedRootAsDimension(bb, obj) {
                    bb.setPosition(bb.position() + flatbuffers_1.flatbuffers.SIZE_PREFIX_LENGTH);
                    return (obj || new Dimension()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                }
                /**
                 * @param onnxruntime.experimental.fbs.DimensionValue= obj
                 * @returns onnxruntime.experimental.fbs.DimensionValue|null
                 */
                value(obj) {
                    let offset = this.bb.__offset(this.bb_pos, 4);
                    return offset ? (obj || new onnxruntime.experimental.fbs.DimensionValue())
                        .__init(this.bb.__indirect(this.bb_pos + offset), this.bb) :
                        null;
                }
                denotation(optionalEncoding) {
                    let offset = this.bb.__offset(this.bb_pos, 6);
                    return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
                }
                /**
                 * @param flatbuffers.Builder builder
                 */
                static startDimension(builder) {
                    builder.startObject(2);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset valueOffset
                 */
                static addValue(builder, valueOffset) {
                    builder.addFieldOffset(0, valueOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset denotationOffset
                 */
                static addDenotation(builder, denotationOffset) {
                    builder.addFieldOffset(1, denotationOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @returns flatbuffers.Offset
                 */
                static endDimension(builder) {
                    let offset = builder.endObject();
                    return offset;
                }
                static createDimension(builder, valueOffset, denotationOffset) {
                    Dimension.startDimension(builder);
                    Dimension.addValue(builder, valueOffset);
                    Dimension.addDenotation(builder, denotationOffset);
                    return Dimension.endDimension(builder);
                }
            }
            fbs.Dimension = Dimension;
        })(fbs = experimental.fbs || (experimental.fbs = {}));
    })(experimental = onnxruntime.experimental || (onnxruntime.experimental = {}));
})(onnxruntime = exports.onnxruntime || (exports.onnxruntime = {}));
/**
 * @constructor
 */
(function (onnxruntime) {
    var experimental;
    (function (experimental) {
        var fbs;
        (function (fbs) {
            class DimensionValue {
                constructor() {
                    this.bb = null;
                    this.bb_pos = 0;
                }
                /**
                 * @param number i
                 * @param flatbuffers.ByteBuffer bb
                 * @returns DimensionValue
                 */
                __init(i, bb) {
                    this.bb_pos = i;
                    this.bb = bb;
                    return this;
                }
                /**
                 * @param flatbuffers.ByteBuffer bb
                 * @param DimensionValue= obj
                 * @returns DimensionValue
                 */
                static getRootAsDimensionValue(bb, obj) {
                    return (obj || new DimensionValue()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                }
                /**
                 * @param flatbuffers.ByteBuffer bb
                 * @param DimensionValue= obj
                 * @returns DimensionValue
                 */
                static getSizePrefixedRootAsDimensionValue(bb, obj) {
                    bb.setPosition(bb.position() + flatbuffers_1.flatbuffers.SIZE_PREFIX_LENGTH);
                    return (obj || new DimensionValue()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                }
                /**
                 * @returns onnxruntime.experimental.fbs.DimensionValueType
                 */
                dimType() {
                    let offset = this.bb.__offset(this.bb_pos, 4);
                    return offset ? /**  */ (this.bb.readInt8(this.bb_pos + offset)) :
                        onnxruntime.experimental.fbs.DimensionValueType.UNKNOWN;
                }
                /**
                 * @returns flatbuffers.Long
                 */
                dimValue() {
                    let offset = this.bb.__offset(this.bb_pos, 6);
                    return offset ? this.bb.readInt64(this.bb_pos + offset) : this.bb.createLong(0, 0);
                }
                dimParam(optionalEncoding) {
                    let offset = this.bb.__offset(this.bb_pos, 8);
                    return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
                }
                /**
                 * @param flatbuffers.Builder builder
                 */
                static startDimensionValue(builder) {
                    builder.startObject(3);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param onnxruntime.experimental.fbs.DimensionValueType dimType
                 */
                static addDimType(builder, dimType) {
                    builder.addFieldInt8(0, dimType, onnxruntime.experimental.fbs.DimensionValueType.UNKNOWN);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Long dimValue
                 */
                static addDimValue(builder, dimValue) {
                    builder.addFieldInt64(1, dimValue, builder.createLong(0, 0));
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset dimParamOffset
                 */
                static addDimParam(builder, dimParamOffset) {
                    builder.addFieldOffset(2, dimParamOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @returns flatbuffers.Offset
                 */
                static endDimensionValue(builder) {
                    let offset = builder.endObject();
                    return offset;
                }
                static createDimensionValue(builder, dimType, dimValue, dimParamOffset) {
                    DimensionValue.startDimensionValue(builder);
                    DimensionValue.addDimType(builder, dimType);
                    DimensionValue.addDimValue(builder, dimValue);
                    DimensionValue.addDimParam(builder, dimParamOffset);
                    return DimensionValue.endDimensionValue(builder);
                }
            }
            fbs.DimensionValue = DimensionValue;
        })(fbs = experimental.fbs || (experimental.fbs = {}));
    })(experimental = onnxruntime.experimental || (onnxruntime.experimental = {}));
})(onnxruntime = exports.onnxruntime || (exports.onnxruntime = {}));
/**
 * @constructor
 */
(function (onnxruntime) {
    var experimental;
    (function (experimental) {
        var fbs;
        (function (fbs) {
            class TensorTypeAndShape {
                constructor() {
                    this.bb = null;
                    this.bb_pos = 0;
                }
                /**
                 * @param number i
                 * @param flatbuffers.ByteBuffer bb
                 * @returns TensorTypeAndShape
                 */
                __init(i, bb) {
                    this.bb_pos = i;
                    this.bb = bb;
                    return this;
                }
                /**
                 * @param flatbuffers.ByteBuffer bb
                 * @param TensorTypeAndShape= obj
                 * @returns TensorTypeAndShape
                 */
                static getRootAsTensorTypeAndShape(bb, obj) {
                    return (obj || new TensorTypeAndShape()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                }
                /**
                 * @param flatbuffers.ByteBuffer bb
                 * @param TensorTypeAndShape= obj
                 * @returns TensorTypeAndShape
                 */
                static getSizePrefixedRootAsTensorTypeAndShape(bb, obj) {
                    bb.setPosition(bb.position() + flatbuffers_1.flatbuffers.SIZE_PREFIX_LENGTH);
                    return (obj || new TensorTypeAndShape()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                }
                /**
                 * @returns onnxruntime.experimental.fbs.TensorDataType
                 */
                elemType() {
                    let offset = this.bb.__offset(this.bb_pos, 4);
                    return offset ? /**  */ (this.bb.readInt32(this.bb_pos + offset)) :
                        onnxruntime.experimental.fbs.TensorDataType.UNDEFINED;
                }
                /**
                 * @param onnxruntime.experimental.fbs.Shape= obj
                 * @returns onnxruntime.experimental.fbs.Shape|null
                 */
                shape(obj) {
                    let offset = this.bb.__offset(this.bb_pos, 6);
                    return offset ? (obj || new onnxruntime.experimental.fbs.Shape())
                        .__init(this.bb.__indirect(this.bb_pos + offset), this.bb) :
                        null;
                }
                /**
                 * @param flatbuffers.Builder builder
                 */
                static startTensorTypeAndShape(builder) {
                    builder.startObject(2);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param onnxruntime.experimental.fbs.TensorDataType elemType
                 */
                static addElemType(builder, elemType) {
                    builder.addFieldInt32(0, elemType, onnxruntime.experimental.fbs.TensorDataType.UNDEFINED);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset shapeOffset
                 */
                static addShape(builder, shapeOffset) {
                    builder.addFieldOffset(1, shapeOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @returns flatbuffers.Offset
                 */
                static endTensorTypeAndShape(builder) {
                    let offset = builder.endObject();
                    return offset;
                }
                static createTensorTypeAndShape(builder, elemType, shapeOffset) {
                    TensorTypeAndShape.startTensorTypeAndShape(builder);
                    TensorTypeAndShape.addElemType(builder, elemType);
                    TensorTypeAndShape.addShape(builder, shapeOffset);
                    return TensorTypeAndShape.endTensorTypeAndShape(builder);
                }
            }
            fbs.TensorTypeAndShape = TensorTypeAndShape;
        })(fbs = experimental.fbs || (experimental.fbs = {}));
    })(experimental = onnxruntime.experimental || (onnxruntime.experimental = {}));
})(onnxruntime = exports.onnxruntime || (exports.onnxruntime = {}));
/**
 * @constructor
 */
(function (onnxruntime) {
    var experimental;
    (function (experimental) {
        var fbs;
        (function (fbs) {
            class MapType {
                constructor() {
                    this.bb = null;
                    this.bb_pos = 0;
                }
                /**
                 * @param number i
                 * @param flatbuffers.ByteBuffer bb
                 * @returns MapType
                 */
                __init(i, bb) {
                    this.bb_pos = i;
                    this.bb = bb;
                    return this;
                }
                /**
                 * @param flatbuffers.ByteBuffer bb
                 * @param MapType= obj
                 * @returns MapType
                 */
                static getRootAsMapType(bb, obj) {
                    return (obj || new MapType()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                }
                /**
                 * @param flatbuffers.ByteBuffer bb
                 * @param MapType= obj
                 * @returns MapType
                 */
                static getSizePrefixedRootAsMapType(bb, obj) {
                    bb.setPosition(bb.position() + flatbuffers_1.flatbuffers.SIZE_PREFIX_LENGTH);
                    return (obj || new MapType()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                }
                /**
                 * @returns onnxruntime.experimental.fbs.TensorDataType
                 */
                keyType() {
                    let offset = this.bb.__offset(this.bb_pos, 4);
                    return offset ? /**  */ (this.bb.readInt32(this.bb_pos + offset)) :
                        onnxruntime.experimental.fbs.TensorDataType.UNDEFINED;
                }
                /**
                 * @param onnxruntime.experimental.fbs.TypeInfo= obj
                 * @returns onnxruntime.experimental.fbs.TypeInfo|null
                 */
                valueType(obj) {
                    let offset = this.bb.__offset(this.bb_pos, 6);
                    return offset ? (obj || new onnxruntime.experimental.fbs.TypeInfo())
                        .__init(this.bb.__indirect(this.bb_pos + offset), this.bb) :
                        null;
                }
                /**
                 * @param flatbuffers.Builder builder
                 */
                static startMapType(builder) {
                    builder.startObject(2);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param onnxruntime.experimental.fbs.TensorDataType keyType
                 */
                static addKeyType(builder, keyType) {
                    builder.addFieldInt32(0, keyType, onnxruntime.experimental.fbs.TensorDataType.UNDEFINED);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset valueTypeOffset
                 */
                static addValueType(builder, valueTypeOffset) {
                    builder.addFieldOffset(1, valueTypeOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @returns flatbuffers.Offset
                 */
                static endMapType(builder) {
                    let offset = builder.endObject();
                    return offset;
                }
                static createMapType(builder, keyType, valueTypeOffset) {
                    MapType.startMapType(builder);
                    MapType.addKeyType(builder, keyType);
                    MapType.addValueType(builder, valueTypeOffset);
                    return MapType.endMapType(builder);
                }
            }
            fbs.MapType = MapType;
        })(fbs = experimental.fbs || (experimental.fbs = {}));
    })(experimental = onnxruntime.experimental || (onnxruntime.experimental = {}));
})(onnxruntime = exports.onnxruntime || (exports.onnxruntime = {}));
/**
 * @constructor
 */
(function (onnxruntime) {
    var experimental;
    (function (experimental) {
        var fbs;
        (function (fbs) {
            class SequenceType {
                constructor() {
                    this.bb = null;
                    this.bb_pos = 0;
                }
                /**
                 * @param number i
                 * @param flatbuffers.ByteBuffer bb
                 * @returns SequenceType
                 */
                __init(i, bb) {
                    this.bb_pos = i;
                    this.bb = bb;
                    return this;
                }
                /**
                 * @param flatbuffers.ByteBuffer bb
                 * @param SequenceType= obj
                 * @returns SequenceType
                 */
                static getRootAsSequenceType(bb, obj) {
                    return (obj || new SequenceType()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                }
                /**
                 * @param flatbuffers.ByteBuffer bb
                 * @param SequenceType= obj
                 * @returns SequenceType
                 */
                static getSizePrefixedRootAsSequenceType(bb, obj) {
                    bb.setPosition(bb.position() + flatbuffers_1.flatbuffers.SIZE_PREFIX_LENGTH);
                    return (obj || new SequenceType()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                }
                /**
                 * @param onnxruntime.experimental.fbs.TypeInfo= obj
                 * @returns onnxruntime.experimental.fbs.TypeInfo|null
                 */
                elemType(obj) {
                    let offset = this.bb.__offset(this.bb_pos, 4);
                    return offset ? (obj || new onnxruntime.experimental.fbs.TypeInfo())
                        .__init(this.bb.__indirect(this.bb_pos + offset), this.bb) :
                        null;
                }
                /**
                 * @param flatbuffers.Builder builder
                 */
                static startSequenceType(builder) {
                    builder.startObject(1);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset elemTypeOffset
                 */
                static addElemType(builder, elemTypeOffset) {
                    builder.addFieldOffset(0, elemTypeOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @returns flatbuffers.Offset
                 */
                static endSequenceType(builder) {
                    let offset = builder.endObject();
                    return offset;
                }
                static createSequenceType(builder, elemTypeOffset) {
                    SequenceType.startSequenceType(builder);
                    SequenceType.addElemType(builder, elemTypeOffset);
                    return SequenceType.endSequenceType(builder);
                }
            }
            fbs.SequenceType = SequenceType;
        })(fbs = experimental.fbs || (experimental.fbs = {}));
    })(experimental = onnxruntime.experimental || (onnxruntime.experimental = {}));
})(onnxruntime = exports.onnxruntime || (exports.onnxruntime = {}));
/**
 * @constructor
 */
(function (onnxruntime) {
    var experimental;
    (function (experimental) {
        var fbs;
        (function (fbs) {
            class EdgeEnd {
                constructor() {
                    this.bb = null;
                    this.bb_pos = 0;
                }
                /**
                 * @param number i
                 * @param flatbuffers.ByteBuffer bb
                 * @returns EdgeEnd
                 */
                __init(i, bb) {
                    this.bb_pos = i;
                    this.bb = bb;
                    return this;
                }
                /**
                 * @returns number
                 */
                nodeIndex() {
                    return this.bb.readUint32(this.bb_pos);
                }
                /**
                 * @returns number
                 */
                srcArgIndex() {
                    return this.bb.readInt32(this.bb_pos + 4);
                }
                /**
                 * @returns number
                 */
                dstArgIndex() {
                    return this.bb.readInt32(this.bb_pos + 8);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param number node_index
                 * @param number src_arg_index
                 * @param number dst_arg_index
                 * @returns flatbuffers.Offset
                 */
                static createEdgeEnd(builder, node_index, src_arg_index, dst_arg_index) {
                    builder.prep(4, 12);
                    builder.writeInt32(dst_arg_index);
                    builder.writeInt32(src_arg_index);
                    builder.writeInt32(node_index);
                    return builder.offset();
                }
            }
            fbs.EdgeEnd = EdgeEnd;
        })(fbs = experimental.fbs || (experimental.fbs = {}));
    })(experimental = onnxruntime.experimental || (onnxruntime.experimental = {}));
})(onnxruntime = exports.onnxruntime || (exports.onnxruntime = {}));
/**
 * @constructor
 */
(function (onnxruntime) {
    var experimental;
    (function (experimental) {
        var fbs;
        (function (fbs) {
            class NodeEdge {
                constructor() {
                    this.bb = null;
                    this.bb_pos = 0;
                }
                /**
                 * @param number i
                 * @param flatbuffers.ByteBuffer bb
                 * @returns NodeEdge
                 */
                __init(i, bb) {
                    this.bb_pos = i;
                    this.bb = bb;
                    return this;
                }
                /**
                 * @param flatbuffers.ByteBuffer bb
                 * @param NodeEdge= obj
                 * @returns NodeEdge
                 */
                static getRootAsNodeEdge(bb, obj) {
                    return (obj || new NodeEdge()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                }
                /**
                 * @param flatbuffers.ByteBuffer bb
                 * @param NodeEdge= obj
                 * @returns NodeEdge
                 */
                static getSizePrefixedRootAsNodeEdge(bb, obj) {
                    bb.setPosition(bb.position() + flatbuffers_1.flatbuffers.SIZE_PREFIX_LENGTH);
                    return (obj || new NodeEdge()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                }
                /**
                 * @returns number
                 */
                nodeIndex() {
                    let offset = this.bb.__offset(this.bb_pos, 4);
                    return offset ? this.bb.readUint32(this.bb_pos + offset) : 0;
                }
                /**
                 * @param number index
                 * @param onnxruntime.experimental.fbs.EdgeEnd= obj
                 * @returns onnxruntime.experimental.fbs.EdgeEnd
                 */
                inputEdges(index, obj) {
                    let offset = this.bb.__offset(this.bb_pos, 6);
                    return offset ? (obj || new onnxruntime.experimental.fbs.EdgeEnd())
                        .__init(this.bb.__vector(this.bb_pos + offset) + index * 12, this.bb) :
                        null;
                }
                /**
                 * @returns number
                 */
                inputEdgesLength() {
                    let offset = this.bb.__offset(this.bb_pos, 6);
                    return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
                }
                /**
                 * @param number index
                 * @param onnxruntime.experimental.fbs.EdgeEnd= obj
                 * @returns onnxruntime.experimental.fbs.EdgeEnd
                 */
                outputEdges(index, obj) {
                    let offset = this.bb.__offset(this.bb_pos, 8);
                    return offset ? (obj || new onnxruntime.experimental.fbs.EdgeEnd())
                        .__init(this.bb.__vector(this.bb_pos + offset) + index * 12, this.bb) :
                        null;
                }
                /**
                 * @returns number
                 */
                outputEdgesLength() {
                    let offset = this.bb.__offset(this.bb_pos, 8);
                    return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
                }
                /**
                 * @param flatbuffers.Builder builder
                 */
                static startNodeEdge(builder) {
                    builder.startObject(3);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param number nodeIndex
                 */
                static addNodeIndex(builder, nodeIndex) {
                    builder.addFieldInt32(0, nodeIndex, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset inputEdgesOffset
                 */
                static addInputEdges(builder, inputEdgesOffset) {
                    builder.addFieldOffset(1, inputEdgesOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param number numElems
                 */
                static startInputEdgesVector(builder, numElems) {
                    builder.startVector(12, numElems, 4);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset outputEdgesOffset
                 */
                static addOutputEdges(builder, outputEdgesOffset) {
                    builder.addFieldOffset(2, outputEdgesOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param number numElems
                 */
                static startOutputEdgesVector(builder, numElems) {
                    builder.startVector(12, numElems, 4);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @returns flatbuffers.Offset
                 */
                static endNodeEdge(builder) {
                    let offset = builder.endObject();
                    return offset;
                }
                static createNodeEdge(builder, nodeIndex, inputEdgesOffset, outputEdgesOffset) {
                    NodeEdge.startNodeEdge(builder);
                    NodeEdge.addNodeIndex(builder, nodeIndex);
                    NodeEdge.addInputEdges(builder, inputEdgesOffset);
                    NodeEdge.addOutputEdges(builder, outputEdgesOffset);
                    return NodeEdge.endNodeEdge(builder);
                }
            }
            fbs.NodeEdge = NodeEdge;
        })(fbs = experimental.fbs || (experimental.fbs = {}));
    })(experimental = onnxruntime.experimental || (onnxruntime.experimental = {}));
})(onnxruntime = exports.onnxruntime || (exports.onnxruntime = {}));
/**
 * @constructor
 */
(function (onnxruntime) {
    var experimental;
    (function (experimental) {
        var fbs;
        (function (fbs) {
            class Node {
                constructor() {
                    this.bb = null;
                    this.bb_pos = 0;
                }
                /**
                 * @param number i
                 * @param flatbuffers.ByteBuffer bb
                 * @returns Node
                 */
                __init(i, bb) {
                    this.bb_pos = i;
                    this.bb = bb;
                    return this;
                }
                /**
                 * @param flatbuffers.ByteBuffer bb
                 * @param Node= obj
                 * @returns Node
                 */
                static getRootAsNode(bb, obj) {
                    return (obj || new Node()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                }
                /**
                 * @param flatbuffers.ByteBuffer bb
                 * @param Node= obj
                 * @returns Node
                 */
                static getSizePrefixedRootAsNode(bb, obj) {
                    bb.setPosition(bb.position() + flatbuffers_1.flatbuffers.SIZE_PREFIX_LENGTH);
                    return (obj || new Node()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                }
                name(optionalEncoding) {
                    let offset = this.bb.__offset(this.bb_pos, 4);
                    return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
                }
                docString(optionalEncoding) {
                    let offset = this.bb.__offset(this.bb_pos, 6);
                    return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
                }
                domain(optionalEncoding) {
                    let offset = this.bb.__offset(this.bb_pos, 8);
                    return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
                }
                /**
                 * @returns number
                 */
                sinceVersion() {
                    let offset = this.bb.__offset(this.bb_pos, 10);
                    return offset ? this.bb.readInt32(this.bb_pos + offset) : 0;
                }
                /**
                 * @returns number
                 */
                index() {
                    let offset = this.bb.__offset(this.bb_pos, 12);
                    return offset ? this.bb.readUint32(this.bb_pos + offset) : 0;
                }
                opType(optionalEncoding) {
                    let offset = this.bb.__offset(this.bb_pos, 14);
                    return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
                }
                /**
                 * @returns onnxruntime.experimental.fbs.NodeType
                 */
                type() {
                    let offset = this.bb.__offset(this.bb_pos, 16);
                    return offset ? /**  */ (this.bb.readInt32(this.bb_pos + offset)) :
                        onnxruntime.experimental.fbs.NodeType.Primitive;
                }
                executionProviderType(optionalEncoding) {
                    let offset = this.bb.__offset(this.bb_pos, 18);
                    return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
                }
                inputs(index, optionalEncoding) {
                    let offset = this.bb.__offset(this.bb_pos, 20);
                    return offset ? this.bb.__string(this.bb.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null;
                }
                /**
                 * @returns number
                 */
                inputsLength() {
                    let offset = this.bb.__offset(this.bb_pos, 20);
                    return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
                }
                outputs(index, optionalEncoding) {
                    let offset = this.bb.__offset(this.bb_pos, 22);
                    return offset ? this.bb.__string(this.bb.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null;
                }
                /**
                 * @returns number
                 */
                outputsLength() {
                    let offset = this.bb.__offset(this.bb_pos, 22);
                    return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
                }
                /**
                 * @param number index
                 * @param onnxruntime.experimental.fbs.Attribute= obj
                 * @returns onnxruntime.experimental.fbs.Attribute
                 */
                attributes(index, obj) {
                    let offset = this.bb.__offset(this.bb_pos, 24);
                    return offset ? (obj || new onnxruntime.experimental.fbs.Attribute())
                        .__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) :
                        null;
                }
                /**
                 * @returns number
                 */
                attributesLength() {
                    let offset = this.bb.__offset(this.bb_pos, 24);
                    return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
                }
                /**
                 * @param number index
                 * @returns number
                 */
                inputArgCounts(index) {
                    let offset = this.bb.__offset(this.bb_pos, 26);
                    return offset ? this.bb.readInt32(this.bb.__vector(this.bb_pos + offset) + index * 4) : 0;
                }
                /**
                 * @returns number
                 */
                inputArgCountsLength() {
                    let offset = this.bb.__offset(this.bb_pos, 26);
                    return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
                }
                /**
                 * @returns Int32Array
                 */
                inputArgCountsArray() {
                    let offset = this.bb.__offset(this.bb_pos, 26);
                    return offset ?
                        new Int32Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) :
                        null;
                }
                implicitInputs(index, optionalEncoding) {
                    let offset = this.bb.__offset(this.bb_pos, 28);
                    return offset ? this.bb.__string(this.bb.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null;
                }
                /**
                 * @returns number
                 */
                implicitInputsLength() {
                    let offset = this.bb.__offset(this.bb_pos, 28);
                    return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
                }
                /**
                 * @param flatbuffers.Builder builder
                 */
                static startNode(builder) {
                    builder.startObject(13);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset nameOffset
                 */
                static addName(builder, nameOffset) {
                    builder.addFieldOffset(0, nameOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset docStringOffset
                 */
                static addDocString(builder, docStringOffset) {
                    builder.addFieldOffset(1, docStringOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset domainOffset
                 */
                static addDomain(builder, domainOffset) {
                    builder.addFieldOffset(2, domainOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param number sinceVersion
                 */
                static addSinceVersion(builder, sinceVersion) {
                    builder.addFieldInt32(3, sinceVersion, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param number index
                 */
                static addIndex(builder, index) {
                    builder.addFieldInt32(4, index, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset opTypeOffset
                 */
                static addOpType(builder, opTypeOffset) {
                    builder.addFieldOffset(5, opTypeOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param onnxruntime.experimental.fbs.NodeType type
                 */
                static addType(builder, type) {
                    builder.addFieldInt32(6, type, onnxruntime.experimental.fbs.NodeType.Primitive);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset executionProviderTypeOffset
                 */
                static addExecutionProviderType(builder, executionProviderTypeOffset) {
                    builder.addFieldOffset(7, executionProviderTypeOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset inputsOffset
                 */
                static addInputs(builder, inputsOffset) {
                    builder.addFieldOffset(8, inputsOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param Array.<flatbuffers.Offset> data
                 * @returns flatbuffers.Offset
                 */
                static createInputsVector(builder, data) {
                    builder.startVector(4, data.length, 4);
                    for (let i = data.length - 1; i >= 0; i--) {
                        builder.addOffset(data[i]);
                    }
                    return builder.endVector();
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param number numElems
                 */
                static startInputsVector(builder, numElems) {
                    builder.startVector(4, numElems, 4);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset outputsOffset
                 */
                static addOutputs(builder, outputsOffset) {
                    builder.addFieldOffset(9, outputsOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param Array.<flatbuffers.Offset> data
                 * @returns flatbuffers.Offset
                 */
                static createOutputsVector(builder, data) {
                    builder.startVector(4, data.length, 4);
                    for (let i = data.length - 1; i >= 0; i--) {
                        builder.addOffset(data[i]);
                    }
                    return builder.endVector();
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param number numElems
                 */
                static startOutputsVector(builder, numElems) {
                    builder.startVector(4, numElems, 4);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset attributesOffset
                 */
                static addAttributes(builder, attributesOffset) {
                    builder.addFieldOffset(10, attributesOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param Array.<flatbuffers.Offset> data
                 * @returns flatbuffers.Offset
                 */
                static createAttributesVector(builder, data) {
                    builder.startVector(4, data.length, 4);
                    for (let i = data.length - 1; i >= 0; i--) {
                        builder.addOffset(data[i]);
                    }
                    return builder.endVector();
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param number numElems
                 */
                static startAttributesVector(builder, numElems) {
                    builder.startVector(4, numElems, 4);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset inputArgCountsOffset
                 */
                static addInputArgCounts(builder, inputArgCountsOffset) {
                    builder.addFieldOffset(11, inputArgCountsOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param Array.<number> data
                 * @returns flatbuffers.Offset
                 */
                static createInputArgCountsVector(builder, data) {
                    builder.startVector(4, data.length, 4);
                    for (let i = data.length - 1; i >= 0; i--) {
                        builder.addInt32(data[i]);
                    }
                    return builder.endVector();
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param number numElems
                 */
                static startInputArgCountsVector(builder, numElems) {
                    builder.startVector(4, numElems, 4);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset implicitInputsOffset
                 */
                static addImplicitInputs(builder, implicitInputsOffset) {
                    builder.addFieldOffset(12, implicitInputsOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param Array.<flatbuffers.Offset> data
                 * @returns flatbuffers.Offset
                 */
                static createImplicitInputsVector(builder, data) {
                    builder.startVector(4, data.length, 4);
                    for (let i = data.length - 1; i >= 0; i--) {
                        builder.addOffset(data[i]);
                    }
                    return builder.endVector();
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param number numElems
                 */
                static startImplicitInputsVector(builder, numElems) {
                    builder.startVector(4, numElems, 4);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @returns flatbuffers.Offset
                 */
                static endNode(builder) {
                    let offset = builder.endObject();
                    return offset;
                }
                static createNode(builder, nameOffset, docStringOffset, domainOffset, sinceVersion, index, opTypeOffset, type, executionProviderTypeOffset, inputsOffset, outputsOffset, attributesOffset, inputArgCountsOffset, implicitInputsOffset) {
                    Node.startNode(builder);
                    Node.addName(builder, nameOffset);
                    Node.addDocString(builder, docStringOffset);
                    Node.addDomain(builder, domainOffset);
                    Node.addSinceVersion(builder, sinceVersion);
                    Node.addIndex(builder, index);
                    Node.addOpType(builder, opTypeOffset);
                    Node.addType(builder, type);
                    Node.addExecutionProviderType(builder, executionProviderTypeOffset);
                    Node.addInputs(builder, inputsOffset);
                    Node.addOutputs(builder, outputsOffset);
                    Node.addAttributes(builder, attributesOffset);
                    Node.addInputArgCounts(builder, inputArgCountsOffset);
                    Node.addImplicitInputs(builder, implicitInputsOffset);
                    return Node.endNode(builder);
                }
            }
            fbs.Node = Node;
        })(fbs = experimental.fbs || (experimental.fbs = {}));
    })(experimental = onnxruntime.experimental || (onnxruntime.experimental = {}));
})(onnxruntime = exports.onnxruntime || (exports.onnxruntime = {}));
/**
 * @constructor
 */
(function (onnxruntime) {
    var experimental;
    (function (experimental) {
        var fbs;
        (function (fbs) {
            class ValueInfo {
                constructor() {
                    this.bb = null;
                    this.bb_pos = 0;
                }
                /**
                 * @param number i
                 * @param flatbuffers.ByteBuffer bb
                 * @returns ValueInfo
                 */
                __init(i, bb) {
                    this.bb_pos = i;
                    this.bb = bb;
                    return this;
                }
                /**
                 * @param flatbuffers.ByteBuffer bb
                 * @param ValueInfo= obj
                 * @returns ValueInfo
                 */
                static getRootAsValueInfo(bb, obj) {
                    return (obj || new ValueInfo()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                }
                /**
                 * @param flatbuffers.ByteBuffer bb
                 * @param ValueInfo= obj
                 * @returns ValueInfo
                 */
                static getSizePrefixedRootAsValueInfo(bb, obj) {
                    bb.setPosition(bb.position() + flatbuffers_1.flatbuffers.SIZE_PREFIX_LENGTH);
                    return (obj || new ValueInfo()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                }
                name(optionalEncoding) {
                    let offset = this.bb.__offset(this.bb_pos, 4);
                    return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
                }
                docString(optionalEncoding) {
                    let offset = this.bb.__offset(this.bb_pos, 6);
                    return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
                }
                /**
                 * @param onnxruntime.experimental.fbs.TypeInfo= obj
                 * @returns onnxruntime.experimental.fbs.TypeInfo|null
                 */
                type(obj) {
                    let offset = this.bb.__offset(this.bb_pos, 8);
                    return offset ? (obj || new onnxruntime.experimental.fbs.TypeInfo())
                        .__init(this.bb.__indirect(this.bb_pos + offset), this.bb) :
                        null;
                }
                /**
                 * @param flatbuffers.Builder builder
                 */
                static startValueInfo(builder) {
                    builder.startObject(3);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset nameOffset
                 */
                static addName(builder, nameOffset) {
                    builder.addFieldOffset(0, nameOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset docStringOffset
                 */
                static addDocString(builder, docStringOffset) {
                    builder.addFieldOffset(1, docStringOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset typeOffset
                 */
                static addType(builder, typeOffset) {
                    builder.addFieldOffset(2, typeOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @returns flatbuffers.Offset
                 */
                static endValueInfo(builder) {
                    let offset = builder.endObject();
                    return offset;
                }
                static createValueInfo(builder, nameOffset, docStringOffset, typeOffset) {
                    ValueInfo.startValueInfo(builder);
                    ValueInfo.addName(builder, nameOffset);
                    ValueInfo.addDocString(builder, docStringOffset);
                    ValueInfo.addType(builder, typeOffset);
                    return ValueInfo.endValueInfo(builder);
                }
            }
            fbs.ValueInfo = ValueInfo;
        })(fbs = experimental.fbs || (experimental.fbs = {}));
    })(experimental = onnxruntime.experimental || (onnxruntime.experimental = {}));
})(onnxruntime = exports.onnxruntime || (exports.onnxruntime = {}));
/**
 * @constructor
 */
(function (onnxruntime) {
    var experimental;
    (function (experimental) {
        var fbs;
        (function (fbs) {
            class TypeInfo {
                constructor() {
                    this.bb = null;
                    this.bb_pos = 0;
                }
                /**
                 * @param number i
                 * @param flatbuffers.ByteBuffer bb
                 * @returns TypeInfo
                 */
                __init(i, bb) {
                    this.bb_pos = i;
                    this.bb = bb;
                    return this;
                }
                /**
                 * @param flatbuffers.ByteBuffer bb
                 * @param TypeInfo= obj
                 * @returns TypeInfo
                 */
                static getRootAsTypeInfo(bb, obj) {
                    return (obj || new TypeInfo()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                }
                /**
                 * @param flatbuffers.ByteBuffer bb
                 * @param TypeInfo= obj
                 * @returns TypeInfo
                 */
                static getSizePrefixedRootAsTypeInfo(bb, obj) {
                    bb.setPosition(bb.position() + flatbuffers_1.flatbuffers.SIZE_PREFIX_LENGTH);
                    return (obj || new TypeInfo()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                }
                denotation(optionalEncoding) {
                    let offset = this.bb.__offset(this.bb_pos, 4);
                    return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
                }
                /**
                 * @returns onnxruntime.experimental.fbs.TypeInfoValue
                 */
                valueType() {
                    let offset = this.bb.__offset(this.bb_pos, 6);
                    return offset ? /**  */ (this.bb.readUint8(this.bb_pos + offset)) :
                        onnxruntime.experimental.fbs.TypeInfoValue.NONE;
                }
                /**
                 * @param flatbuffers.Table obj
                 * @returns ?flatbuffers.Table
                 */
                value(obj) {
                    let offset = this.bb.__offset(this.bb_pos, 8);
                    return offset ? this.bb.__union(obj, this.bb_pos + offset) : null;
                }
                /**
                 * @param flatbuffers.Builder builder
                 */
                static startTypeInfo(builder) {
                    builder.startObject(3);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset denotationOffset
                 */
                static addDenotation(builder, denotationOffset) {
                    builder.addFieldOffset(0, denotationOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param onnxruntime.experimental.fbs.TypeInfoValue valueType
                 */
                static addValueType(builder, valueType) {
                    builder.addFieldInt8(1, valueType, onnxruntime.experimental.fbs.TypeInfoValue.NONE);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset valueOffset
                 */
                static addValue(builder, valueOffset) {
                    builder.addFieldOffset(2, valueOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @returns flatbuffers.Offset
                 */
                static endTypeInfo(builder) {
                    let offset = builder.endObject();
                    return offset;
                }
                static createTypeInfo(builder, denotationOffset, valueType, valueOffset) {
                    TypeInfo.startTypeInfo(builder);
                    TypeInfo.addDenotation(builder, denotationOffset);
                    TypeInfo.addValueType(builder, valueType);
                    TypeInfo.addValue(builder, valueOffset);
                    return TypeInfo.endTypeInfo(builder);
                }
            }
            fbs.TypeInfo = TypeInfo;
        })(fbs = experimental.fbs || (experimental.fbs = {}));
    })(experimental = onnxruntime.experimental || (onnxruntime.experimental = {}));
})(onnxruntime = exports.onnxruntime || (exports.onnxruntime = {}));
/**
 * @constructor
 */
(function (onnxruntime) {
    var experimental;
    (function (experimental) {
        var fbs;
        (function (fbs) {
            class OperatorSetId {
                constructor() {
                    this.bb = null;
                    this.bb_pos = 0;
                }
                /**
                 * @param number i
                 * @param flatbuffers.ByteBuffer bb
                 * @returns OperatorSetId
                 */
                __init(i, bb) {
                    this.bb_pos = i;
                    this.bb = bb;
                    return this;
                }
                /**
                 * @param flatbuffers.ByteBuffer bb
                 * @param OperatorSetId= obj
                 * @returns OperatorSetId
                 */
                static getRootAsOperatorSetId(bb, obj) {
                    return (obj || new OperatorSetId()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                }
                /**
                 * @param flatbuffers.ByteBuffer bb
                 * @param OperatorSetId= obj
                 * @returns OperatorSetId
                 */
                static getSizePrefixedRootAsOperatorSetId(bb, obj) {
                    bb.setPosition(bb.position() + flatbuffers_1.flatbuffers.SIZE_PREFIX_LENGTH);
                    return (obj || new OperatorSetId()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                }
                domain(optionalEncoding) {
                    let offset = this.bb.__offset(this.bb_pos, 4);
                    return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
                }
                /**
                 * @returns flatbuffers.Long
                 */
                version() {
                    let offset = this.bb.__offset(this.bb_pos, 6);
                    return offset ? this.bb.readInt64(this.bb_pos + offset) : this.bb.createLong(0, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 */
                static startOperatorSetId(builder) {
                    builder.startObject(2);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset domainOffset
                 */
                static addDomain(builder, domainOffset) {
                    builder.addFieldOffset(0, domainOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Long version
                 */
                static addVersion(builder, version) {
                    builder.addFieldInt64(1, version, builder.createLong(0, 0));
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @returns flatbuffers.Offset
                 */
                static endOperatorSetId(builder) {
                    let offset = builder.endObject();
                    return offset;
                }
                static createOperatorSetId(builder, domainOffset, version) {
                    OperatorSetId.startOperatorSetId(builder);
                    OperatorSetId.addDomain(builder, domainOffset);
                    OperatorSetId.addVersion(builder, version);
                    return OperatorSetId.endOperatorSetId(builder);
                }
            }
            fbs.OperatorSetId = OperatorSetId;
        })(fbs = experimental.fbs || (experimental.fbs = {}));
    })(experimental = onnxruntime.experimental || (onnxruntime.experimental = {}));
})(onnxruntime = exports.onnxruntime || (exports.onnxruntime = {}));
/**
 * @constructor
 */
(function (onnxruntime) {
    var experimental;
    (function (experimental) {
        var fbs;
        (function (fbs) {
            class Tensor {
                constructor() {
                    this.bb = null;
                    this.bb_pos = 0;
                }
                /**
                 * @param number i
                 * @param flatbuffers.ByteBuffer bb
                 * @returns Tensor
                 */
                __init(i, bb) {
                    this.bb_pos = i;
                    this.bb = bb;
                    return this;
                }
                /**
                 * @param flatbuffers.ByteBuffer bb
                 * @param Tensor= obj
                 * @returns Tensor
                 */
                static getRootAsTensor(bb, obj) {
                    return (obj || new Tensor()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                }
                /**
                 * @param flatbuffers.ByteBuffer bb
                 * @param Tensor= obj
                 * @returns Tensor
                 */
                static getSizePrefixedRootAsTensor(bb, obj) {
                    bb.setPosition(bb.position() + flatbuffers_1.flatbuffers.SIZE_PREFIX_LENGTH);
                    return (obj || new Tensor()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                }
                name(optionalEncoding) {
                    let offset = this.bb.__offset(this.bb_pos, 4);
                    return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
                }
                docString(optionalEncoding) {
                    let offset = this.bb.__offset(this.bb_pos, 6);
                    return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
                }
                /**
                 * @param number index
                 * @returns flatbuffers.Long
                 */
                dims(index) {
                    let offset = this.bb.__offset(this.bb_pos, 8);
                    return offset ? this.bb.readInt64(this.bb.__vector(this.bb_pos + offset) + index * 8) :
                        this.bb.createLong(0, 0);
                }
                /**
                 * @returns number
                 */
                dimsLength() {
                    let offset = this.bb.__offset(this.bb_pos, 8);
                    return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
                }
                /**
                 * @returns onnxruntime.experimental.fbs.TensorDataType
                 */
                dataType() {
                    let offset = this.bb.__offset(this.bb_pos, 10);
                    return offset ? /**  */ (this.bb.readInt32(this.bb_pos + offset)) :
                        onnxruntime.experimental.fbs.TensorDataType.UNDEFINED;
                }
                /**
                 * @param number index
                 * @returns number
                 */
                rawData(index) {
                    let offset = this.bb.__offset(this.bb_pos, 12);
                    return offset ? this.bb.readUint8(this.bb.__vector(this.bb_pos + offset) + index) : 0;
                }
                /**
                 * @returns number
                 */
                rawDataLength() {
                    let offset = this.bb.__offset(this.bb_pos, 12);
                    return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
                }
                /**
                 * @returns Uint8Array
                 */
                rawDataArray() {
                    let offset = this.bb.__offset(this.bb_pos, 12);
                    return offset ?
                        new Uint8Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) :
                        null;
                }
                stringData(index, optionalEncoding) {
                    let offset = this.bb.__offset(this.bb_pos, 14);
                    return offset ? this.bb.__string(this.bb.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null;
                }
                /**
                 * @returns number
                 */
                stringDataLength() {
                    let offset = this.bb.__offset(this.bb_pos, 14);
                    return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
                }
                /**
                 * @param flatbuffers.Builder builder
                 */
                static startTensor(builder) {
                    builder.startObject(6);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset nameOffset
                 */
                static addName(builder, nameOffset) {
                    builder.addFieldOffset(0, nameOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset docStringOffset
                 */
                static addDocString(builder, docStringOffset) {
                    builder.addFieldOffset(1, docStringOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset dimsOffset
                 */
                static addDims(builder, dimsOffset) {
                    builder.addFieldOffset(2, dimsOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param Array.<flatbuffers.Long> data
                 * @returns flatbuffers.Offset
                 */
                static createDimsVector(builder, data) {
                    builder.startVector(8, data.length, 8);
                    for (let i = data.length - 1; i >= 0; i--) {
                        builder.addInt64(data[i]);
                    }
                    return builder.endVector();
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param number numElems
                 */
                static startDimsVector(builder, numElems) {
                    builder.startVector(8, numElems, 8);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param onnxruntime.experimental.fbs.TensorDataType dataType
                 */
                static addDataType(builder, dataType) {
                    builder.addFieldInt32(3, dataType, onnxruntime.experimental.fbs.TensorDataType.UNDEFINED);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset rawDataOffset
                 */
                static addRawData(builder, rawDataOffset) {
                    builder.addFieldOffset(4, rawDataOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param Array.<number> data
                 * @returns flatbuffers.Offset
                 */
                static createRawDataVector(builder, data) {
                    builder.startVector(1, data.length, 1);
                    for (let i = data.length - 1; i >= 0; i--) {
                        builder.addInt8(data[i]);
                    }
                    return builder.endVector();
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param number numElems
                 */
                static startRawDataVector(builder, numElems) {
                    builder.startVector(1, numElems, 1);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset stringDataOffset
                 */
                static addStringData(builder, stringDataOffset) {
                    builder.addFieldOffset(5, stringDataOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param Array.<flatbuffers.Offset> data
                 * @returns flatbuffers.Offset
                 */
                static createStringDataVector(builder, data) {
                    builder.startVector(4, data.length, 4);
                    for (let i = data.length - 1; i >= 0; i--) {
                        builder.addOffset(data[i]);
                    }
                    return builder.endVector();
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param number numElems
                 */
                static startStringDataVector(builder, numElems) {
                    builder.startVector(4, numElems, 4);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @returns flatbuffers.Offset
                 */
                static endTensor(builder) {
                    let offset = builder.endObject();
                    return offset;
                }
                static createTensor(builder, nameOffset, docStringOffset, dimsOffset, dataType, rawDataOffset, stringDataOffset) {
                    Tensor.startTensor(builder);
                    Tensor.addName(builder, nameOffset);
                    Tensor.addDocString(builder, docStringOffset);
                    Tensor.addDims(builder, dimsOffset);
                    Tensor.addDataType(builder, dataType);
                    Tensor.addRawData(builder, rawDataOffset);
                    Tensor.addStringData(builder, stringDataOffset);
                    return Tensor.endTensor(builder);
                }
            }
            fbs.Tensor = Tensor;
        })(fbs = experimental.fbs || (experimental.fbs = {}));
    })(experimental = onnxruntime.experimental || (onnxruntime.experimental = {}));
})(onnxruntime = exports.onnxruntime || (exports.onnxruntime = {}));
/**
 * @constructor
 */
(function (onnxruntime) {
    var experimental;
    (function (experimental) {
        var fbs;
        (function (fbs) {
            class SparseTensor {
                constructor() {
                    this.bb = null;
                    this.bb_pos = 0;
                }
                /**
                 * @param number i
                 * @param flatbuffers.ByteBuffer bb
                 * @returns SparseTensor
                 */
                __init(i, bb) {
                    this.bb_pos = i;
                    this.bb = bb;
                    return this;
                }
                /**
                 * @param flatbuffers.ByteBuffer bb
                 * @param SparseTensor= obj
                 * @returns SparseTensor
                 */
                static getRootAsSparseTensor(bb, obj) {
                    return (obj || new SparseTensor()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                }
                /**
                 * @param flatbuffers.ByteBuffer bb
                 * @param SparseTensor= obj
                 * @returns SparseTensor
                 */
                static getSizePrefixedRootAsSparseTensor(bb, obj) {
                    bb.setPosition(bb.position() + flatbuffers_1.flatbuffers.SIZE_PREFIX_LENGTH);
                    return (obj || new SparseTensor()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                }
                /**
                 * @param onnxruntime.experimental.fbs.Tensor= obj
                 * @returns onnxruntime.experimental.fbs.Tensor|null
                 */
                values(obj) {
                    let offset = this.bb.__offset(this.bb_pos, 4);
                    return offset ? (obj || new onnxruntime.experimental.fbs.Tensor())
                        .__init(this.bb.__indirect(this.bb_pos + offset), this.bb) :
                        null;
                }
                /**
                 * @param onnxruntime.experimental.fbs.Tensor= obj
                 * @returns onnxruntime.experimental.fbs.Tensor|null
                 */
                indices(obj) {
                    let offset = this.bb.__offset(this.bb_pos, 6);
                    return offset ? (obj || new onnxruntime.experimental.fbs.Tensor())
                        .__init(this.bb.__indirect(this.bb_pos + offset), this.bb) :
                        null;
                }
                /**
                 * @param number index
                 * @returns flatbuffers.Long
                 */
                dims(index) {
                    let offset = this.bb.__offset(this.bb_pos, 8);
                    return offset ? this.bb.readInt64(this.bb.__vector(this.bb_pos + offset) + index * 8) :
                        this.bb.createLong(0, 0);
                }
                /**
                 * @returns number
                 */
                dimsLength() {
                    let offset = this.bb.__offset(this.bb_pos, 8);
                    return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
                }
                /**
                 * @param flatbuffers.Builder builder
                 */
                static startSparseTensor(builder) {
                    builder.startObject(3);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset valuesOffset
                 */
                static addValues(builder, valuesOffset) {
                    builder.addFieldOffset(0, valuesOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset indicesOffset
                 */
                static addIndices(builder, indicesOffset) {
                    builder.addFieldOffset(1, indicesOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset dimsOffset
                 */
                static addDims(builder, dimsOffset) {
                    builder.addFieldOffset(2, dimsOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param Array.<flatbuffers.Long> data
                 * @returns flatbuffers.Offset
                 */
                static createDimsVector(builder, data) {
                    builder.startVector(8, data.length, 8);
                    for (let i = data.length - 1; i >= 0; i--) {
                        builder.addInt64(data[i]);
                    }
                    return builder.endVector();
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param number numElems
                 */
                static startDimsVector(builder, numElems) {
                    builder.startVector(8, numElems, 8);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @returns flatbuffers.Offset
                 */
                static endSparseTensor(builder) {
                    let offset = builder.endObject();
                    return offset;
                }
                static createSparseTensor(builder, valuesOffset, indicesOffset, dimsOffset) {
                    SparseTensor.startSparseTensor(builder);
                    SparseTensor.addValues(builder, valuesOffset);
                    SparseTensor.addIndices(builder, indicesOffset);
                    SparseTensor.addDims(builder, dimsOffset);
                    return SparseTensor.endSparseTensor(builder);
                }
            }
            fbs.SparseTensor = SparseTensor;
        })(fbs = experimental.fbs || (experimental.fbs = {}));
    })(experimental = onnxruntime.experimental || (onnxruntime.experimental = {}));
})(onnxruntime = exports.onnxruntime || (exports.onnxruntime = {}));
/**
 * @constructor
 */
(function (onnxruntime) {
    var experimental;
    (function (experimental) {
        var fbs;
        (function (fbs) {
            class Attribute {
                constructor() {
                    this.bb = null;
                    this.bb_pos = 0;
                }
                /**
                 * @param number i
                 * @param flatbuffers.ByteBuffer bb
                 * @returns Attribute
                 */
                __init(i, bb) {
                    this.bb_pos = i;
                    this.bb = bb;
                    return this;
                }
                /**
                 * @param flatbuffers.ByteBuffer bb
                 * @param Attribute= obj
                 * @returns Attribute
                 */
                static getRootAsAttribute(bb, obj) {
                    return (obj || new Attribute()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                }
                /**
                 * @param flatbuffers.ByteBuffer bb
                 * @param Attribute= obj
                 * @returns Attribute
                 */
                static getSizePrefixedRootAsAttribute(bb, obj) {
                    bb.setPosition(bb.position() + flatbuffers_1.flatbuffers.SIZE_PREFIX_LENGTH);
                    return (obj || new Attribute()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                }
                name(optionalEncoding) {
                    let offset = this.bb.__offset(this.bb_pos, 4);
                    return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
                }
                docString(optionalEncoding) {
                    let offset = this.bb.__offset(this.bb_pos, 6);
                    return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
                }
                /**
                 * @returns onnxruntime.experimental.fbs.AttributeType
                 */
                type() {
                    let offset = this.bb.__offset(this.bb_pos, 8);
                    return offset ? /**  */ (this.bb.readInt32(this.bb_pos + offset)) :
                        onnxruntime.experimental.fbs.AttributeType.UNDEFINED;
                }
                /**
                 * @returns number
                 */
                f() {
                    let offset = this.bb.__offset(this.bb_pos, 10);
                    return offset ? this.bb.readFloat32(this.bb_pos + offset) : 0.0;
                }
                /**
                 * @returns flatbuffers.Long
                 */
                i() {
                    let offset = this.bb.__offset(this.bb_pos, 12);
                    return offset ? this.bb.readInt64(this.bb_pos + offset) : this.bb.createLong(0, 0);
                }
                s(optionalEncoding) {
                    let offset = this.bb.__offset(this.bb_pos, 14);
                    return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
                }
                /**
                 * @param onnxruntime.experimental.fbs.Tensor= obj
                 * @returns onnxruntime.experimental.fbs.Tensor|null
                 */
                t(obj) {
                    let offset = this.bb.__offset(this.bb_pos, 16);
                    return offset ? (obj || new onnxruntime.experimental.fbs.Tensor())
                        .__init(this.bb.__indirect(this.bb_pos + offset), this.bb) :
                        null;
                }
                /**
                 * @param onnxruntime.experimental.fbs.Graph= obj
                 * @returns onnxruntime.experimental.fbs.Graph|null
                 */
                g(obj) {
                    let offset = this.bb.__offset(this.bb_pos, 18);
                    return offset ? (obj || new onnxruntime.experimental.fbs.Graph())
                        .__init(this.bb.__indirect(this.bb_pos + offset), this.bb) :
                        null;
                }
                /**
                 * @param number index
                 * @returns number
                 */
                floats(index) {
                    let offset = this.bb.__offset(this.bb_pos, 20);
                    return offset ? this.bb.readFloat32(this.bb.__vector(this.bb_pos + offset) + index * 4) : 0;
                }
                /**
                 * @returns number
                 */
                floatsLength() {
                    let offset = this.bb.__offset(this.bb_pos, 20);
                    return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
                }
                /**
                 * @returns Float32Array
                 */
                floatsArray() {
                    let offset = this.bb.__offset(this.bb_pos, 20);
                    return offset ?
                        new Float32Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) :
                        null;
                }
                /**
                 * @param number index
                 * @returns flatbuffers.Long
                 */
                ints(index) {
                    let offset = this.bb.__offset(this.bb_pos, 22);
                    return offset ? this.bb.readInt64(this.bb.__vector(this.bb_pos + offset) + index * 8) :
                        this.bb.createLong(0, 0);
                }
                /**
                 * @returns number
                 */
                intsLength() {
                    let offset = this.bb.__offset(this.bb_pos, 22);
                    return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
                }
                strings(index, optionalEncoding) {
                    let offset = this.bb.__offset(this.bb_pos, 24);
                    return offset ? this.bb.__string(this.bb.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null;
                }
                /**
                 * @returns number
                 */
                stringsLength() {
                    let offset = this.bb.__offset(this.bb_pos, 24);
                    return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
                }
                /**
                 * @param number index
                 * @param onnxruntime.experimental.fbs.Tensor= obj
                 * @returns onnxruntime.experimental.fbs.Tensor
                 */
                tensors(index, obj) {
                    let offset = this.bb.__offset(this.bb_pos, 26);
                    return offset ? (obj || new onnxruntime.experimental.fbs.Tensor())
                        .__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) :
                        null;
                }
                /**
                 * @returns number
                 */
                tensorsLength() {
                    let offset = this.bb.__offset(this.bb_pos, 26);
                    return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
                }
                /**
                 * @param number index
                 * @param onnxruntime.experimental.fbs.Graph= obj
                 * @returns onnxruntime.experimental.fbs.Graph
                 */
                graphs(index, obj) {
                    let offset = this.bb.__offset(this.bb_pos, 28);
                    return offset ? (obj || new onnxruntime.experimental.fbs.Graph())
                        .__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) :
                        null;
                }
                /**
                 * @returns number
                 */
                graphsLength() {
                    let offset = this.bb.__offset(this.bb_pos, 28);
                    return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
                }
                /**
                 * @param flatbuffers.Builder builder
                 */
                static startAttribute(builder) {
                    builder.startObject(13);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset nameOffset
                 */
                static addName(builder, nameOffset) {
                    builder.addFieldOffset(0, nameOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset docStringOffset
                 */
                static addDocString(builder, docStringOffset) {
                    builder.addFieldOffset(1, docStringOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param onnxruntime.experimental.fbs.AttributeType type
                 */
                static addType(builder, type) {
                    builder.addFieldInt32(2, type, onnxruntime.experimental.fbs.AttributeType.UNDEFINED);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param number f
                 */
                static addF(builder, f) {
                    builder.addFieldFloat32(3, f, 0.0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Long i
                 */
                static addI(builder, i) {
                    builder.addFieldInt64(4, i, builder.createLong(0, 0));
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset sOffset
                 */
                static addS(builder, sOffset) {
                    builder.addFieldOffset(5, sOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset tOffset
                 */
                static addT(builder, tOffset) {
                    builder.addFieldOffset(6, tOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset gOffset
                 */
                static addG(builder, gOffset) {
                    builder.addFieldOffset(7, gOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset floatsOffset
                 */
                static addFloats(builder, floatsOffset) {
                    builder.addFieldOffset(8, floatsOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param Array.<number> data
                 * @returns flatbuffers.Offset
                 */
                static createFloatsVector(builder, data) {
                    builder.startVector(4, data.length, 4);
                    for (let i = data.length - 1; i >= 0; i--) {
                        builder.addFloat32(data[i]);
                    }
                    return builder.endVector();
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param number numElems
                 */
                static startFloatsVector(builder, numElems) {
                    builder.startVector(4, numElems, 4);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset intsOffset
                 */
                static addInts(builder, intsOffset) {
                    builder.addFieldOffset(9, intsOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param Array.<flatbuffers.Long> data
                 * @returns flatbuffers.Offset
                 */
                static createIntsVector(builder, data) {
                    builder.startVector(8, data.length, 8);
                    for (let i = data.length - 1; i >= 0; i--) {
                        builder.addInt64(data[i]);
                    }
                    return builder.endVector();
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param number numElems
                 */
                static startIntsVector(builder, numElems) {
                    builder.startVector(8, numElems, 8);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset stringsOffset
                 */
                static addStrings(builder, stringsOffset) {
                    builder.addFieldOffset(10, stringsOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param Array.<flatbuffers.Offset> data
                 * @returns flatbuffers.Offset
                 */
                static createStringsVector(builder, data) {
                    builder.startVector(4, data.length, 4);
                    for (let i = data.length - 1; i >= 0; i--) {
                        builder.addOffset(data[i]);
                    }
                    return builder.endVector();
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param number numElems
                 */
                static startStringsVector(builder, numElems) {
                    builder.startVector(4, numElems, 4);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset tensorsOffset
                 */
                static addTensors(builder, tensorsOffset) {
                    builder.addFieldOffset(11, tensorsOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param Array.<flatbuffers.Offset> data
                 * @returns flatbuffers.Offset
                 */
                static createTensorsVector(builder, data) {
                    builder.startVector(4, data.length, 4);
                    for (let i = data.length - 1; i >= 0; i--) {
                        builder.addOffset(data[i]);
                    }
                    return builder.endVector();
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param number numElems
                 */
                static startTensorsVector(builder, numElems) {
                    builder.startVector(4, numElems, 4);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset graphsOffset
                 */
                static addGraphs(builder, graphsOffset) {
                    builder.addFieldOffset(12, graphsOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param Array.<flatbuffers.Offset> data
                 * @returns flatbuffers.Offset
                 */
                static createGraphsVector(builder, data) {
                    builder.startVector(4, data.length, 4);
                    for (let i = data.length - 1; i >= 0; i--) {
                        builder.addOffset(data[i]);
                    }
                    return builder.endVector();
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param number numElems
                 */
                static startGraphsVector(builder, numElems) {
                    builder.startVector(4, numElems, 4);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @returns flatbuffers.Offset
                 */
                static endAttribute(builder) {
                    let offset = builder.endObject();
                    return offset;
                }
                static createAttribute(builder, nameOffset, docStringOffset, type, f, i, sOffset, tOffset, gOffset, floatsOffset, intsOffset, stringsOffset, tensorsOffset, graphsOffset) {
                    Attribute.startAttribute(builder);
                    Attribute.addName(builder, nameOffset);
                    Attribute.addDocString(builder, docStringOffset);
                    Attribute.addType(builder, type);
                    Attribute.addF(builder, f);
                    Attribute.addI(builder, i);
                    Attribute.addS(builder, sOffset);
                    Attribute.addT(builder, tOffset);
                    Attribute.addG(builder, gOffset);
                    Attribute.addFloats(builder, floatsOffset);
                    Attribute.addInts(builder, intsOffset);
                    Attribute.addStrings(builder, stringsOffset);
                    Attribute.addTensors(builder, tensorsOffset);
                    Attribute.addGraphs(builder, graphsOffset);
                    return Attribute.endAttribute(builder);
                }
            }
            fbs.Attribute = Attribute;
        })(fbs = experimental.fbs || (experimental.fbs = {}));
    })(experimental = onnxruntime.experimental || (onnxruntime.experimental = {}));
})(onnxruntime = exports.onnxruntime || (exports.onnxruntime = {}));
/**
 * @constructor
 */
(function (onnxruntime) {
    var experimental;
    (function (experimental) {
        var fbs;
        (function (fbs) {
            class Graph {
                constructor() {
                    this.bb = null;
                    this.bb_pos = 0;
                }
                /**
                 * @param number i
                 * @param flatbuffers.ByteBuffer bb
                 * @returns Graph
                 */
                __init(i, bb) {
                    this.bb_pos = i;
                    this.bb = bb;
                    return this;
                }
                /**
                 * @param flatbuffers.ByteBuffer bb
                 * @param Graph= obj
                 * @returns Graph
                 */
                static getRootAsGraph(bb, obj) {
                    return (obj || new Graph()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                }
                /**
                 * @param flatbuffers.ByteBuffer bb
                 * @param Graph= obj
                 * @returns Graph
                 */
                static getSizePrefixedRootAsGraph(bb, obj) {
                    bb.setPosition(bb.position() + flatbuffers_1.flatbuffers.SIZE_PREFIX_LENGTH);
                    return (obj || new Graph()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                }
                /**
                 * @param number index
                 * @param onnxruntime.experimental.fbs.Tensor= obj
                 * @returns onnxruntime.experimental.fbs.Tensor
                 */
                initializers(index, obj) {
                    let offset = this.bb.__offset(this.bb_pos, 4);
                    return offset ? (obj || new onnxruntime.experimental.fbs.Tensor())
                        .__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) :
                        null;
                }
                /**
                 * @returns number
                 */
                initializersLength() {
                    let offset = this.bb.__offset(this.bb_pos, 4);
                    return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
                }
                /**
                 * @param number index
                 * @param onnxruntime.experimental.fbs.ValueInfo= obj
                 * @returns onnxruntime.experimental.fbs.ValueInfo
                 */
                nodeArgs(index, obj) {
                    let offset = this.bb.__offset(this.bb_pos, 6);
                    return offset ? (obj || new onnxruntime.experimental.fbs.ValueInfo())
                        .__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) :
                        null;
                }
                /**
                 * @returns number
                 */
                nodeArgsLength() {
                    let offset = this.bb.__offset(this.bb_pos, 6);
                    return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
                }
                /**
                 * @param number index
                 * @param onnxruntime.experimental.fbs.Node= obj
                 * @returns onnxruntime.experimental.fbs.Node
                 */
                nodes(index, obj) {
                    let offset = this.bb.__offset(this.bb_pos, 8);
                    return offset ? (obj || new onnxruntime.experimental.fbs.Node())
                        .__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) :
                        null;
                }
                /**
                 * @returns number
                 */
                nodesLength() {
                    let offset = this.bb.__offset(this.bb_pos, 8);
                    return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
                }
                /**
                 * @returns number
                 */
                maxNodeIndex() {
                    let offset = this.bb.__offset(this.bb_pos, 10);
                    return offset ? this.bb.readUint32(this.bb_pos + offset) : 0;
                }
                /**
                 * @param number index
                 * @param onnxruntime.experimental.fbs.NodeEdge= obj
                 * @returns onnxruntime.experimental.fbs.NodeEdge
                 */
                nodeEdges(index, obj) {
                    let offset = this.bb.__offset(this.bb_pos, 12);
                    return offset ? (obj || new onnxruntime.experimental.fbs.NodeEdge())
                        .__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) :
                        null;
                }
                /**
                 * @returns number
                 */
                nodeEdgesLength() {
                    let offset = this.bb.__offset(this.bb_pos, 12);
                    return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
                }
                inputs(index, optionalEncoding) {
                    let offset = this.bb.__offset(this.bb_pos, 14);
                    return offset ? this.bb.__string(this.bb.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null;
                }
                /**
                 * @returns number
                 */
                inputsLength() {
                    let offset = this.bb.__offset(this.bb_pos, 14);
                    return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
                }
                outputs(index, optionalEncoding) {
                    let offset = this.bb.__offset(this.bb_pos, 16);
                    return offset ? this.bb.__string(this.bb.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null;
                }
                /**
                 * @returns number
                 */
                outputsLength() {
                    let offset = this.bb.__offset(this.bb_pos, 16);
                    return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
                }
                /**
                 * @param number index
                 * @param onnxruntime.experimental.fbs.SparseTensor= obj
                 * @returns onnxruntime.experimental.fbs.SparseTensor
                 */
                sparseInitializers(index, obj) {
                    let offset = this.bb.__offset(this.bb_pos, 18);
                    return offset ? (obj || new onnxruntime.experimental.fbs.SparseTensor())
                        .__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) :
                        null;
                }
                /**
                 * @returns number
                 */
                sparseInitializersLength() {
                    let offset = this.bb.__offset(this.bb_pos, 18);
                    return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
                }
                /**
                 * @param flatbuffers.Builder builder
                 */
                static startGraph(builder) {
                    builder.startObject(8);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset initializersOffset
                 */
                static addInitializers(builder, initializersOffset) {
                    builder.addFieldOffset(0, initializersOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param Array.<flatbuffers.Offset> data
                 * @returns flatbuffers.Offset
                 */
                static createInitializersVector(builder, data) {
                    builder.startVector(4, data.length, 4);
                    for (let i = data.length - 1; i >= 0; i--) {
                        builder.addOffset(data[i]);
                    }
                    return builder.endVector();
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param number numElems
                 */
                static startInitializersVector(builder, numElems) {
                    builder.startVector(4, numElems, 4);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset nodeArgsOffset
                 */
                static addNodeArgs(builder, nodeArgsOffset) {
                    builder.addFieldOffset(1, nodeArgsOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param Array.<flatbuffers.Offset> data
                 * @returns flatbuffers.Offset
                 */
                static createNodeArgsVector(builder, data) {
                    builder.startVector(4, data.length, 4);
                    for (let i = data.length - 1; i >= 0; i--) {
                        builder.addOffset(data[i]);
                    }
                    return builder.endVector();
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param number numElems
                 */
                static startNodeArgsVector(builder, numElems) {
                    builder.startVector(4, numElems, 4);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset nodesOffset
                 */
                static addNodes(builder, nodesOffset) {
                    builder.addFieldOffset(2, nodesOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param Array.<flatbuffers.Offset> data
                 * @returns flatbuffers.Offset
                 */
                static createNodesVector(builder, data) {
                    builder.startVector(4, data.length, 4);
                    for (let i = data.length - 1; i >= 0; i--) {
                        builder.addOffset(data[i]);
                    }
                    return builder.endVector();
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param number numElems
                 */
                static startNodesVector(builder, numElems) {
                    builder.startVector(4, numElems, 4);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param number maxNodeIndex
                 */
                static addMaxNodeIndex(builder, maxNodeIndex) {
                    builder.addFieldInt32(3, maxNodeIndex, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset nodeEdgesOffset
                 */
                static addNodeEdges(builder, nodeEdgesOffset) {
                    builder.addFieldOffset(4, nodeEdgesOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param Array.<flatbuffers.Offset> data
                 * @returns flatbuffers.Offset
                 */
                static createNodeEdgesVector(builder, data) {
                    builder.startVector(4, data.length, 4);
                    for (let i = data.length - 1; i >= 0; i--) {
                        builder.addOffset(data[i]);
                    }
                    return builder.endVector();
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param number numElems
                 */
                static startNodeEdgesVector(builder, numElems) {
                    builder.startVector(4, numElems, 4);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset inputsOffset
                 */
                static addInputs(builder, inputsOffset) {
                    builder.addFieldOffset(5, inputsOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param Array.<flatbuffers.Offset> data
                 * @returns flatbuffers.Offset
                 */
                static createInputsVector(builder, data) {
                    builder.startVector(4, data.length, 4);
                    for (let i = data.length - 1; i >= 0; i--) {
                        builder.addOffset(data[i]);
                    }
                    return builder.endVector();
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param number numElems
                 */
                static startInputsVector(builder, numElems) {
                    builder.startVector(4, numElems, 4);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset outputsOffset
                 */
                static addOutputs(builder, outputsOffset) {
                    builder.addFieldOffset(6, outputsOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param Array.<flatbuffers.Offset> data
                 * @returns flatbuffers.Offset
                 */
                static createOutputsVector(builder, data) {
                    builder.startVector(4, data.length, 4);
                    for (let i = data.length - 1; i >= 0; i--) {
                        builder.addOffset(data[i]);
                    }
                    return builder.endVector();
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param number numElems
                 */
                static startOutputsVector(builder, numElems) {
                    builder.startVector(4, numElems, 4);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset sparseInitializersOffset
                 */
                static addSparseInitializers(builder, sparseInitializersOffset) {
                    builder.addFieldOffset(7, sparseInitializersOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param Array.<flatbuffers.Offset> data
                 * @returns flatbuffers.Offset
                 */
                static createSparseInitializersVector(builder, data) {
                    builder.startVector(4, data.length, 4);
                    for (let i = data.length - 1; i >= 0; i--) {
                        builder.addOffset(data[i]);
                    }
                    return builder.endVector();
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param number numElems
                 */
                static startSparseInitializersVector(builder, numElems) {
                    builder.startVector(4, numElems, 4);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @returns flatbuffers.Offset
                 */
                static endGraph(builder) {
                    let offset = builder.endObject();
                    return offset;
                }
                static createGraph(builder, initializersOffset, nodeArgsOffset, nodesOffset, maxNodeIndex, nodeEdgesOffset, inputsOffset, outputsOffset, sparseInitializersOffset) {
                    Graph.startGraph(builder);
                    Graph.addInitializers(builder, initializersOffset);
                    Graph.addNodeArgs(builder, nodeArgsOffset);
                    Graph.addNodes(builder, nodesOffset);
                    Graph.addMaxNodeIndex(builder, maxNodeIndex);
                    Graph.addNodeEdges(builder, nodeEdgesOffset);
                    Graph.addInputs(builder, inputsOffset);
                    Graph.addOutputs(builder, outputsOffset);
                    Graph.addSparseInitializers(builder, sparseInitializersOffset);
                    return Graph.endGraph(builder);
                }
            }
            fbs.Graph = Graph;
        })(fbs = experimental.fbs || (experimental.fbs = {}));
    })(experimental = onnxruntime.experimental || (onnxruntime.experimental = {}));
})(onnxruntime = exports.onnxruntime || (exports.onnxruntime = {}));
/**
 * @constructor
 */
(function (onnxruntime) {
    var experimental;
    (function (experimental) {
        var fbs;
        (function (fbs) {
            class Model {
                constructor() {
                    this.bb = null;
                    this.bb_pos = 0;
                }
                /**
                 * @param number i
                 * @param flatbuffers.ByteBuffer bb
                 * @returns Model
                 */
                __init(i, bb) {
                    this.bb_pos = i;
                    this.bb = bb;
                    return this;
                }
                /**
                 * @param flatbuffers.ByteBuffer bb
                 * @param Model= obj
                 * @returns Model
                 */
                static getRootAsModel(bb, obj) {
                    return (obj || new Model()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                }
                /**
                 * @param flatbuffers.ByteBuffer bb
                 * @param Model= obj
                 * @returns Model
                 */
                static getSizePrefixedRootAsModel(bb, obj) {
                    bb.setPosition(bb.position() + flatbuffers_1.flatbuffers.SIZE_PREFIX_LENGTH);
                    return (obj || new Model()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                }
                /**
                 * @returns flatbuffers.Long
                 */
                irVersion() {
                    let offset = this.bb.__offset(this.bb_pos, 4);
                    return offset ? this.bb.readInt64(this.bb_pos + offset) : this.bb.createLong(0, 0);
                }
                /**
                 * @param number index
                 * @param onnxruntime.experimental.fbs.OperatorSetId= obj
                 * @returns onnxruntime.experimental.fbs.OperatorSetId
                 */
                opsetImport(index, obj) {
                    let offset = this.bb.__offset(this.bb_pos, 6);
                    return offset ? (obj || new onnxruntime.experimental.fbs.OperatorSetId())
                        .__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) :
                        null;
                }
                /**
                 * @returns number
                 */
                opsetImportLength() {
                    let offset = this.bb.__offset(this.bb_pos, 6);
                    return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
                }
                producerName(optionalEncoding) {
                    let offset = this.bb.__offset(this.bb_pos, 8);
                    return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
                }
                producerVersion(optionalEncoding) {
                    let offset = this.bb.__offset(this.bb_pos, 10);
                    return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
                }
                domain(optionalEncoding) {
                    let offset = this.bb.__offset(this.bb_pos, 12);
                    return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
                }
                /**
                 * @returns flatbuffers.Long
                 */
                modelVersion() {
                    let offset = this.bb.__offset(this.bb_pos, 14);
                    return offset ? this.bb.readInt64(this.bb_pos + offset) : this.bb.createLong(0, 0);
                }
                docString(optionalEncoding) {
                    let offset = this.bb.__offset(this.bb_pos, 16);
                    return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
                }
                /**
                 * @param onnxruntime.experimental.fbs.Graph= obj
                 * @returns onnxruntime.experimental.fbs.Graph|null
                 */
                graph(obj) {
                    let offset = this.bb.__offset(this.bb_pos, 18);
                    return offset ? (obj || new onnxruntime.experimental.fbs.Graph())
                        .__init(this.bb.__indirect(this.bb_pos + offset), this.bb) :
                        null;
                }
                graphDocString(optionalEncoding) {
                    let offset = this.bb.__offset(this.bb_pos, 20);
                    return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
                }
                /**
                 * @param flatbuffers.Builder builder
                 */
                static startModel(builder) {
                    builder.startObject(9);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Long irVersion
                 */
                static addIrVersion(builder, irVersion) {
                    builder.addFieldInt64(0, irVersion, builder.createLong(0, 0));
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset opsetImportOffset
                 */
                static addOpsetImport(builder, opsetImportOffset) {
                    builder.addFieldOffset(1, opsetImportOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param Array.<flatbuffers.Offset> data
                 * @returns flatbuffers.Offset
                 */
                static createOpsetImportVector(builder, data) {
                    builder.startVector(4, data.length, 4);
                    for (let i = data.length - 1; i >= 0; i--) {
                        builder.addOffset(data[i]);
                    }
                    return builder.endVector();
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param number numElems
                 */
                static startOpsetImportVector(builder, numElems) {
                    builder.startVector(4, numElems, 4);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset producerNameOffset
                 */
                static addProducerName(builder, producerNameOffset) {
                    builder.addFieldOffset(2, producerNameOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset producerVersionOffset
                 */
                static addProducerVersion(builder, producerVersionOffset) {
                    builder.addFieldOffset(3, producerVersionOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset domainOffset
                 */
                static addDomain(builder, domainOffset) {
                    builder.addFieldOffset(4, domainOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Long modelVersion
                 */
                static addModelVersion(builder, modelVersion) {
                    builder.addFieldInt64(5, modelVersion, builder.createLong(0, 0));
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset docStringOffset
                 */
                static addDocString(builder, docStringOffset) {
                    builder.addFieldOffset(6, docStringOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset graphOffset
                 */
                static addGraph(builder, graphOffset) {
                    builder.addFieldOffset(7, graphOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset graphDocStringOffset
                 */
                static addGraphDocString(builder, graphDocStringOffset) {
                    builder.addFieldOffset(8, graphDocStringOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @returns flatbuffers.Offset
                 */
                static endModel(builder) {
                    let offset = builder.endObject();
                    return offset;
                }
                static createModel(builder, irVersion, opsetImportOffset, producerNameOffset, producerVersionOffset, domainOffset, modelVersion, docStringOffset, graphOffset, graphDocStringOffset) {
                    Model.startModel(builder);
                    Model.addIrVersion(builder, irVersion);
                    Model.addOpsetImport(builder, opsetImportOffset);
                    Model.addProducerName(builder, producerNameOffset);
                    Model.addProducerVersion(builder, producerVersionOffset);
                    Model.addDomain(builder, domainOffset);
                    Model.addModelVersion(builder, modelVersion);
                    Model.addDocString(builder, docStringOffset);
                    Model.addGraph(builder, graphOffset);
                    Model.addGraphDocString(builder, graphDocStringOffset);
                    return Model.endModel(builder);
                }
            }
            fbs.Model = Model;
        })(fbs = experimental.fbs || (experimental.fbs = {}));
    })(experimental = onnxruntime.experimental || (onnxruntime.experimental = {}));
})(onnxruntime = exports.onnxruntime || (exports.onnxruntime = {}));
/**
 * @constructor
 */
(function (onnxruntime) {
    var experimental;
    (function (experimental) {
        var fbs;
        (function (fbs) {
            class KernelCreateInfos {
                constructor() {
                    this.bb = null;
                    this.bb_pos = 0;
                }
                /**
                 * @param number i
                 * @param flatbuffers.ByteBuffer bb
                 * @returns KernelCreateInfos
                 */
                __init(i, bb) {
                    this.bb_pos = i;
                    this.bb = bb;
                    return this;
                }
                /**
                 * @param flatbuffers.ByteBuffer bb
                 * @param KernelCreateInfos= obj
                 * @returns KernelCreateInfos
                 */
                static getRootAsKernelCreateInfos(bb, obj) {
                    return (obj || new KernelCreateInfos()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                }
                /**
                 * @param flatbuffers.ByteBuffer bb
                 * @param KernelCreateInfos= obj
                 * @returns KernelCreateInfos
                 */
                static getSizePrefixedRootAsKernelCreateInfos(bb, obj) {
                    bb.setPosition(bb.position() + flatbuffers_1.flatbuffers.SIZE_PREFIX_LENGTH);
                    return (obj || new KernelCreateInfos()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                }
                /**
                 * @param number index
                 * @returns number
                 */
                nodeIndices(index) {
                    let offset = this.bb.__offset(this.bb_pos, 4);
                    return offset ? this.bb.readUint32(this.bb.__vector(this.bb_pos + offset) + index * 4) : 0;
                }
                /**
                 * @returns number
                 */
                nodeIndicesLength() {
                    let offset = this.bb.__offset(this.bb_pos, 4);
                    return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
                }
                /**
                 * @returns Uint32Array
                 */
                nodeIndicesArray() {
                    let offset = this.bb.__offset(this.bb_pos, 4);
                    return offset ?
                        new Uint32Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) :
                        null;
                }
                /**
                 * @param number index
                 * @returns flatbuffers.Long
                 */
                kernelDefHashes(index) {
                    let offset = this.bb.__offset(this.bb_pos, 6);
                    return offset ? this.bb.readUint64(this.bb.__vector(this.bb_pos + offset) + index * 8) :
                        this.bb.createLong(0, 0);
                }
                /**
                 * @returns number
                 */
                kernelDefHashesLength() {
                    let offset = this.bb.__offset(this.bb_pos, 6);
                    return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
                }
                /**
                 * @param flatbuffers.Builder builder
                 */
                static startKernelCreateInfos(builder) {
                    builder.startObject(2);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset nodeIndicesOffset
                 */
                static addNodeIndices(builder, nodeIndicesOffset) {
                    builder.addFieldOffset(0, nodeIndicesOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param Array.<number> data
                 * @returns flatbuffers.Offset
                 */
                static createNodeIndicesVector(builder, data) {
                    builder.startVector(4, data.length, 4);
                    for (let i = data.length - 1; i >= 0; i--) {
                        builder.addInt32(data[i]);
                    }
                    return builder.endVector();
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param number numElems
                 */
                static startNodeIndicesVector(builder, numElems) {
                    builder.startVector(4, numElems, 4);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset kernelDefHashesOffset
                 */
                static addKernelDefHashes(builder, kernelDefHashesOffset) {
                    builder.addFieldOffset(1, kernelDefHashesOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param Array.<flatbuffers.Long> data
                 * @returns flatbuffers.Offset
                 */
                static createKernelDefHashesVector(builder, data) {
                    builder.startVector(8, data.length, 8);
                    for (let i = data.length - 1; i >= 0; i--) {
                        builder.addInt64(data[i]);
                    }
                    return builder.endVector();
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param number numElems
                 */
                static startKernelDefHashesVector(builder, numElems) {
                    builder.startVector(8, numElems, 8);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @returns flatbuffers.Offset
                 */
                static endKernelCreateInfos(builder) {
                    let offset = builder.endObject();
                    return offset;
                }
                static createKernelCreateInfos(builder, nodeIndicesOffset, kernelDefHashesOffset) {
                    KernelCreateInfos.startKernelCreateInfos(builder);
                    KernelCreateInfos.addNodeIndices(builder, nodeIndicesOffset);
                    KernelCreateInfos.addKernelDefHashes(builder, kernelDefHashesOffset);
                    return KernelCreateInfos.endKernelCreateInfos(builder);
                }
            }
            fbs.KernelCreateInfos = KernelCreateInfos;
        })(fbs = experimental.fbs || (experimental.fbs = {}));
    })(experimental = onnxruntime.experimental || (onnxruntime.experimental = {}));
})(onnxruntime = exports.onnxruntime || (exports.onnxruntime = {}));
/**
 * @constructor
 */
(function (onnxruntime) {
    var experimental;
    (function (experimental) {
        var fbs;
        (function (fbs) {
            class SubGraphSessionState {
                constructor() {
                    this.bb = null;
                    this.bb_pos = 0;
                }
                /**
                 * @param number i
                 * @param flatbuffers.ByteBuffer bb
                 * @returns SubGraphSessionState
                 */
                __init(i, bb) {
                    this.bb_pos = i;
                    this.bb = bb;
                    return this;
                }
                /**
                 * @param flatbuffers.ByteBuffer bb
                 * @param SubGraphSessionState= obj
                 * @returns SubGraphSessionState
                 */
                static getRootAsSubGraphSessionState(bb, obj) {
                    return (obj || new SubGraphSessionState()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                }
                /**
                 * @param flatbuffers.ByteBuffer bb
                 * @param SubGraphSessionState= obj
                 * @returns SubGraphSessionState
                 */
                static getSizePrefixedRootAsSubGraphSessionState(bb, obj) {
                    bb.setPosition(bb.position() + flatbuffers_1.flatbuffers.SIZE_PREFIX_LENGTH);
                    return (obj || new SubGraphSessionState()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                }
                graphId(optionalEncoding) {
                    let offset = this.bb.__offset(this.bb_pos, 4);
                    return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
                }
                /**
                 * @param onnxruntime.experimental.fbs.SessionState= obj
                 * @returns onnxruntime.experimental.fbs.SessionState|null
                 */
                sessionState(obj) {
                    let offset = this.bb.__offset(this.bb_pos, 6);
                    return offset ? (obj || new onnxruntime.experimental.fbs.SessionState())
                        .__init(this.bb.__indirect(this.bb_pos + offset), this.bb) :
                        null;
                }
                /**
                 * @param flatbuffers.Builder builder
                 */
                static startSubGraphSessionState(builder) {
                    builder.startObject(2);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset graphIdOffset
                 */
                static addGraphId(builder, graphIdOffset) {
                    builder.addFieldOffset(0, graphIdOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset sessionStateOffset
                 */
                static addSessionState(builder, sessionStateOffset) {
                    builder.addFieldOffset(1, sessionStateOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @returns flatbuffers.Offset
                 */
                static endSubGraphSessionState(builder) {
                    let offset = builder.endObject();
                    builder.requiredField(offset, 4); // graph_id
                    return offset;
                }
                static createSubGraphSessionState(builder, graphIdOffset, sessionStateOffset) {
                    SubGraphSessionState.startSubGraphSessionState(builder);
                    SubGraphSessionState.addGraphId(builder, graphIdOffset);
                    SubGraphSessionState.addSessionState(builder, sessionStateOffset);
                    return SubGraphSessionState.endSubGraphSessionState(builder);
                }
            }
            fbs.SubGraphSessionState = SubGraphSessionState;
        })(fbs = experimental.fbs || (experimental.fbs = {}));
    })(experimental = onnxruntime.experimental || (onnxruntime.experimental = {}));
})(onnxruntime = exports.onnxruntime || (exports.onnxruntime = {}));
/**
 * @constructor
 */
(function (onnxruntime) {
    var experimental;
    (function (experimental) {
        var fbs;
        (function (fbs) {
            class SessionState {
                constructor() {
                    this.bb = null;
                    this.bb_pos = 0;
                }
                /**
                 * @param number i
                 * @param flatbuffers.ByteBuffer bb
                 * @returns SessionState
                 */
                __init(i, bb) {
                    this.bb_pos = i;
                    this.bb = bb;
                    return this;
                }
                /**
                 * @param flatbuffers.ByteBuffer bb
                 * @param SessionState= obj
                 * @returns SessionState
                 */
                static getRootAsSessionState(bb, obj) {
                    return (obj || new SessionState()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                }
                /**
                 * @param flatbuffers.ByteBuffer bb
                 * @param SessionState= obj
                 * @returns SessionState
                 */
                static getSizePrefixedRootAsSessionState(bb, obj) {
                    bb.setPosition(bb.position() + flatbuffers_1.flatbuffers.SIZE_PREFIX_LENGTH);
                    return (obj || new SessionState()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                }
                /**
                 * @param onnxruntime.experimental.fbs.KernelCreateInfos= obj
                 * @returns onnxruntime.experimental.fbs.KernelCreateInfos|null
                 */
                kernels(obj) {
                    let offset = this.bb.__offset(this.bb_pos, 4);
                    return offset ? (obj || new onnxruntime.experimental.fbs.KernelCreateInfos())
                        .__init(this.bb.__indirect(this.bb_pos + offset), this.bb) :
                        null;
                }
                /**
                 * @param number index
                 * @param onnxruntime.experimental.fbs.SubGraphSessionState= obj
                 * @returns onnxruntime.experimental.fbs.SubGraphSessionState
                 */
                subGraphSessionStates(index, obj) {
                    let offset = this.bb.__offset(this.bb_pos, 6);
                    return offset ? (obj || new onnxruntime.experimental.fbs.SubGraphSessionState())
                        .__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) :
                        null;
                }
                /**
                 * @returns number
                 */
                subGraphSessionStatesLength() {
                    let offset = this.bb.__offset(this.bb_pos, 6);
                    return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
                }
                /**
                 * @param flatbuffers.Builder builder
                 */
                static startSessionState(builder) {
                    builder.startObject(2);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset kernelsOffset
                 */
                static addKernels(builder, kernelsOffset) {
                    builder.addFieldOffset(0, kernelsOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset subGraphSessionStatesOffset
                 */
                static addSubGraphSessionStates(builder, subGraphSessionStatesOffset) {
                    builder.addFieldOffset(1, subGraphSessionStatesOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param Array.<flatbuffers.Offset> data
                 * @returns flatbuffers.Offset
                 */
                static createSubGraphSessionStatesVector(builder, data) {
                    builder.startVector(4, data.length, 4);
                    for (let i = data.length - 1; i >= 0; i--) {
                        builder.addOffset(data[i]);
                    }
                    return builder.endVector();
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param number numElems
                 */
                static startSubGraphSessionStatesVector(builder, numElems) {
                    builder.startVector(4, numElems, 4);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @returns flatbuffers.Offset
                 */
                static endSessionState(builder) {
                    let offset = builder.endObject();
                    return offset;
                }
                static createSessionState(builder, kernelsOffset, subGraphSessionStatesOffset) {
                    SessionState.startSessionState(builder);
                    SessionState.addKernels(builder, kernelsOffset);
                    SessionState.addSubGraphSessionStates(builder, subGraphSessionStatesOffset);
                    return SessionState.endSessionState(builder);
                }
            }
            fbs.SessionState = SessionState;
        })(fbs = experimental.fbs || (experimental.fbs = {}));
    })(experimental = onnxruntime.experimental || (onnxruntime.experimental = {}));
})(onnxruntime = exports.onnxruntime || (exports.onnxruntime = {}));
/**
 * @constructor
 */
(function (onnxruntime) {
    var experimental;
    (function (experimental) {
        var fbs;
        (function (fbs) {
            class InferenceSession {
                constructor() {
                    this.bb = null;
                    this.bb_pos = 0;
                }
                /**
                 * @param number i
                 * @param flatbuffers.ByteBuffer bb
                 * @returns InferenceSession
                 */
                __init(i, bb) {
                    this.bb_pos = i;
                    this.bb = bb;
                    return this;
                }
                /**
                 * @param flatbuffers.ByteBuffer bb
                 * @param InferenceSession= obj
                 * @returns InferenceSession
                 */
                static getRootAsInferenceSession(bb, obj) {
                    return (obj || new InferenceSession()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                }
                /**
                 * @param flatbuffers.ByteBuffer bb
                 * @param InferenceSession= obj
                 * @returns InferenceSession
                 */
                static getSizePrefixedRootAsInferenceSession(bb, obj) {
                    bb.setPosition(bb.position() + flatbuffers_1.flatbuffers.SIZE_PREFIX_LENGTH);
                    return (obj || new InferenceSession()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
                }
                /**
                 * @param flatbuffers.ByteBuffer bb
                 * @returns boolean
                 */
                static bufferHasIdentifier(bb) {
                    return bb.__has_identifier('ORTM');
                }
                ortVersion(optionalEncoding) {
                    let offset = this.bb.__offset(this.bb_pos, 4);
                    return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
                }
                /**
                 * @param onnxruntime.experimental.fbs.Model= obj
                 * @returns onnxruntime.experimental.fbs.Model|null
                 */
                model(obj) {
                    let offset = this.bb.__offset(this.bb_pos, 6);
                    return offset ? (obj || new onnxruntime.experimental.fbs.Model())
                        .__init(this.bb.__indirect(this.bb_pos + offset), this.bb) :
                        null;
                }
                /**
                 * @param onnxruntime.experimental.fbs.SessionState= obj
                 * @returns onnxruntime.experimental.fbs.SessionState|null
                 */
                sessionState(obj) {
                    let offset = this.bb.__offset(this.bb_pos, 8);
                    return offset ? (obj || new onnxruntime.experimental.fbs.SessionState())
                        .__init(this.bb.__indirect(this.bb_pos + offset), this.bb) :
                        null;
                }
                /**
                 * @param flatbuffers.Builder builder
                 */
                static startInferenceSession(builder) {
                    builder.startObject(3);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset ortVersionOffset
                 */
                static addOrtVersion(builder, ortVersionOffset) {
                    builder.addFieldOffset(0, ortVersionOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset modelOffset
                 */
                static addModel(builder, modelOffset) {
                    builder.addFieldOffset(1, modelOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset sessionStateOffset
                 */
                static addSessionState(builder, sessionStateOffset) {
                    builder.addFieldOffset(2, sessionStateOffset, 0);
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @returns flatbuffers.Offset
                 */
                static endInferenceSession(builder) {
                    let offset = builder.endObject();
                    return offset;
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset offset
                 */
                static finishInferenceSessionBuffer(builder, offset) {
                    builder.finish(offset, 'ORTM');
                }
                /**
                 * @param flatbuffers.Builder builder
                 * @param flatbuffers.Offset offset
                 */
                static finishSizePrefixedInferenceSessionBuffer(builder, offset) {
                    builder.finish(offset, 'ORTM', true);
                }
                static createInferenceSession(builder, ortVersionOffset, modelOffset, sessionStateOffset) {
                    InferenceSession.startInferenceSession(builder);
                    InferenceSession.addOrtVersion(builder, ortVersionOffset);
                    InferenceSession.addModel(builder, modelOffset);
                    InferenceSession.addSessionState(builder, sessionStateOffset);
                    return InferenceSession.endInferenceSession(builder);
                }
            }
            fbs.InferenceSession = InferenceSession;
        })(fbs = experimental.fbs || (experimental.fbs = {}));
    })(experimental = onnxruntime.experimental || (onnxruntime.experimental = {}));
})(onnxruntime = exports.onnxruntime || (exports.onnxruntime = {}));


/***/ }),

/***/ "./lib/onnxjs/session-handler.ts":
/*!***************************************!*\
  !*** ./lib/onnxjs/session-handler.ts ***!
  \***************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.OnnxjsSessionHandler = void 0;
const onnxruntime_common_1 = __webpack_require__(/*! onnxruntime-common */ "../common/dist/lib/index.js");
const tensor_1 = __webpack_require__(/*! ./tensor */ "./lib/onnxjs/tensor.ts");
class OnnxjsSessionHandler {
    constructor(session) {
        this.session = session;
        this.inputNames = this.session.inputNames;
        this.outputNames = this.session.outputNames;
    }
    async dispose() { }
    async run(feeds, _fetches, _options) {
        const inputMap = new Map();
        for (const name in feeds) {
            if (Object.hasOwnProperty.call(feeds, name)) {
                const feed = feeds[name];
                inputMap.set(name, new tensor_1.Tensor(feed.dims, feed.type, undefined, undefined, feed.data));
            }
        }
        const outputMap = await this.session.run(inputMap);
        const output = {};
        outputMap.forEach((tensor, name) => {
            output[name] = new onnxruntime_common_1.Tensor(tensor.type, tensor.data, tensor.dims);
        });
        return output;
    }
    startProfiling() {
        this.session.startProfiling();
    }
    endProfiling() {
        this.session.endProfiling();
    }
}
exports.OnnxjsSessionHandler = OnnxjsSessionHandler;


/***/ }),

/***/ "./lib/onnxjs/session.ts":
/*!*******************************!*\
  !*** ./lib/onnxjs/session.ts ***!
  \*******************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Session = void 0;
const fs_1 = __webpack_require__(/*! fs */ "?6c45");
const util_1 = __webpack_require__(/*! util */ "?b3a2");
const backend_1 = __webpack_require__(/*! ./backend */ "./lib/onnxjs/backend.ts");
const execution_plan_1 = __webpack_require__(/*! ./execution-plan */ "./lib/onnxjs/execution-plan.ts");
const instrument_1 = __webpack_require__(/*! ./instrument */ "./lib/onnxjs/instrument.ts");
const model_1 = __webpack_require__(/*! ./model */ "./lib/onnxjs/model.ts");
class Session {
    constructor(config = {}) {
        this._initialized = false;
        this.backendHint = config.backendHint;
        this.profiler = instrument_1.Profiler.create(config.profiler);
        this.context = { profiler: this.profiler, graphInputTypes: [], graphInputDims: [] };
    }
    get inputNames() {
        return this._model.graph.getInputNames();
    }
    get outputNames() {
        return this._model.graph.getOutputNames();
    }
    startProfiling() {
        this.profiler.start();
    }
    endProfiling() {
        this.profiler.stop();
    }
    async loadModel(arg, byteOffset, length) {
        await this.profiler.event('session', 'Session.loadModel', async () => {
            // resolve backend and session handler
            const backend = await (0, backend_1.resolveBackend)(this.backendHint);
            this.sessionHandler = backend.createSessionHandler(this.context);
            this._model = new model_1.Model();
            if (typeof arg === 'string') {
                const isOrtFormat = arg.endsWith('.ort');
                if (typeof fetch === 'undefined') {
                    // node
                    const buf = await (0, util_1.promisify)(fs_1.readFile)(arg);
                    this.initialize(buf, isOrtFormat);
                }
                else {
                    // browser
                    const response = await fetch(arg);
                    const buf = await response.arrayBuffer();
                    this.initialize(new Uint8Array(buf), isOrtFormat);
                }
            }
            else if (!ArrayBuffer.isView(arg)) {
                // load model from ArrayBuffer
                const arr = new Uint8Array(arg, byteOffset || 0, length || arg.byteLength);
                this.initialize(arr);
            }
            else {
                // load model from Uint8array
                this.initialize(arg);
            }
        });
    }
    initialize(modelProtoBlob, isOrtFormat) {
        if (this._initialized) {
            throw new Error('already initialized');
        }
        this.profiler.event('session', 'Session.initialize', () => {
            // load graph
            const graphInitializer = this.sessionHandler.transformGraph ? this.sessionHandler : undefined;
            this._model.load(modelProtoBlob, graphInitializer, isOrtFormat);
            // graph is completely initialzied at this stage , let the interested handlers know
            if (this.sessionHandler.onGraphInitialized) {
                this.sessionHandler.onGraphInitialized(this._model.graph);
            }
            // initialize each operator in the graph
            this.initializeOps(this._model.graph);
            // instantiate an ExecutionPlan object to be used by the Session object
            this._executionPlan = new execution_plan_1.ExecutionPlan(this._model.graph, this._ops, this.profiler);
        });
        this._initialized = true;
    }
    async run(inputs) {
        if (!this._initialized) {
            throw new Error('session not initialized yet');
        }
        return this.profiler.event('session', 'Session.run', async () => {
            const inputTensors = this.normalizeAndValidateInputs(inputs);
            const outputTensors = await this._executionPlan.execute(this.sessionHandler, inputTensors);
            return this.createOutput(outputTensors);
        });
    }
    normalizeAndValidateInputs(inputs) {
        const modelInputNames = this._model.graph.getInputNames();
        // normalize inputs
        // inputs: Tensor[]
        if (Array.isArray(inputs)) {
            if (inputs.length !== modelInputNames.length) {
                throw new Error(`incorrect input array length: expected ${modelInputNames.length} but got ${inputs.length}`);
            }
        }
        // convert map to array
        // inputs: Map<string, Tensor>
        else {
            if (inputs.size !== modelInputNames.length) {
                throw new Error(`incorrect input map size: expected ${modelInputNames.length} but got ${inputs.size}`);
            }
            const sortedInputs = new Array(inputs.size);
            let sortedInputsIndex = 0;
            for (let i = 0; i < modelInputNames.length; ++i) {
                const tensor = inputs.get(modelInputNames[i]);
                if (!tensor) {
                    throw new Error(`missing input tensor for: '${name}'`);
                }
                sortedInputs[sortedInputsIndex++] = tensor;
            }
            inputs = sortedInputs;
        }
        // validate dims requirements
        // First session run - graph input data is not cached for the session
        if (!this.context.graphInputTypes || this.context.graphInputTypes.length === 0 || !this.context.graphInputDims ||
            this.context.graphInputDims.length === 0) {
            const modelInputIndices = this._model.graph.getInputIndices();
            const modelValues = this._model.graph.getValues();
            const graphInputDims = new Array(modelInputIndices.length);
            for (let i = 0; i < modelInputIndices.length; ++i) {
                const graphInput = modelValues[modelInputIndices[i]];
                graphInputDims[i] = graphInput.type.shape.dims;
                // cached for second and subsequent runs.
                // Some parts of the framework works on the assumption that the graph and types and shapes are static
                this.context.graphInputTypes.push(graphInput.type.tensorType);
                this.context.graphInputDims.push(inputs[i].dims);
            }
            this.validateInputTensorDims(graphInputDims, inputs, true);
        }
        // Second and subsequent session runs - graph input data is cached for the session
        else {
            this.validateInputTensorDims(this.context.graphInputDims, inputs, false);
        }
        // validate types requirement
        this.validateInputTensorTypes(this.context.graphInputTypes, inputs);
        return inputs;
    }
    validateInputTensorTypes(graphInputTypes, givenInputs) {
        for (let i = 0; i < givenInputs.length; i++) {
            const expectedType = graphInputTypes[i];
            const actualType = givenInputs[i].type;
            if (expectedType !== actualType) {
                throw new Error(`input tensor[${i}] check failed: expected type '${expectedType}' but got ${actualType}`);
            }
        }
    }
    validateInputTensorDims(graphInputDims, givenInputs, noneDimSupported) {
        for (let i = 0; i < givenInputs.length; i++) {
            const expectedDims = graphInputDims[i];
            const actualDims = givenInputs[i].dims;
            if (!this.compareTensorDims(expectedDims, actualDims, noneDimSupported)) {
                throw new Error(`input tensor[${i}] check failed: expected shape '[${expectedDims.join(',')}]' but got [${actualDims.join(',')}]`);
            }
        }
    }
    compareTensorDims(expectedDims, actualDims, noneDimSupported) {
        if (expectedDims.length !== actualDims.length) {
            return false;
        }
        for (let i = 0; i < expectedDims.length; ++i) {
            if (expectedDims[i] !== actualDims[i] && (!noneDimSupported || expectedDims[i] !== 0)) {
                // data shape mis-match AND not a 'None' dimension.
                return false;
            }
        }
        return true;
    }
    createOutput(outputTensors) {
        const modelOutputNames = this._model.graph.getOutputNames();
        if (outputTensors.length !== modelOutputNames.length) {
            throw new Error('expected number of outputs do not match number of generated outputs');
        }
        const output = new Map();
        for (let i = 0; i < modelOutputNames.length; ++i) {
            output.set(modelOutputNames[i], outputTensors[i]);
        }
        return output;
    }
    initializeOps(graph) {
        const nodes = graph.getNodes();
        this._ops = new Array(nodes.length);
        for (let i = 0; i < nodes.length; i++) {
            this._ops[i] = this.sessionHandler.resolve(nodes[i], this._model.opsets, graph);
        }
    }
}
exports.Session = Session;


/***/ }),

/***/ "./lib/onnxjs/tensor.ts":
/*!******************************!*\
  !*** ./lib/onnxjs/tensor.ts ***!
  \******************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Tensor = void 0;
const guid_typescript_1 = __webpack_require__(/*! guid-typescript */ "./node_modules/guid-typescript/dist/guid.js");
const long_1 = __importDefault(__webpack_require__(/*! long */ "./node_modules/long/src/long.js"));
const onnx_proto_1 = __webpack_require__(/*! onnx-proto */ "./node_modules/onnx-proto/dist/onnx.js");
const ort_generated_1 = __webpack_require__(/*! ./ort-schema/ort-generated */ "./lib/onnxjs/ort-schema/ort-generated.ts");
const util_1 = __webpack_require__(/*! ./util */ "./lib/onnxjs/util.ts");
var ortFbs = ort_generated_1.onnxruntime.experimental.fbs;
class Tensor {
    /**
     * get the underlying tensor data
     */
    get data() {
        if (this.cache === undefined) {
            const data = this.dataProvider(this.dataId);
            if (data.length !== this.size) {
                throw new Error('Length of data provided by the Data Provider is inconsistent with the dims of this Tensor.');
            }
            this.cache = data;
        }
        return this.cache;
    }
    /**
     * get the underlying string tensor data. Should only use when type is STRING
     */
    get stringData() {
        if (this.type !== 'string') {
            throw new TypeError('data type is not string');
        }
        return this.data;
    }
    /**
     * get the underlying integer tensor data. Should only use when type is one of the following: (UINT8, INT8, UINT16,
     * INT16, INT32, UINT32, BOOL)
     */
    get integerData() {
        switch (this.type) {
            case 'uint8':
            case 'int8':
            case 'uint16':
            case 'int16':
            case 'int32':
            case 'uint32':
            case 'bool':
                return this.data;
            default:
                throw new TypeError('data type is not integer (uint8, int8, uint16, int16, int32, uint32, bool)');
        }
    }
    /**
     * get the underlying float tensor data. Should only use when type is one of the following: (FLOAT, DOUBLE)
     */
    get floatData() {
        switch (this.type) {
            case 'float32':
            case 'float64':
                return this.data;
            default:
                throw new TypeError('data type is not float (float32, float64)');
        }
    }
    /**
     * get the underlying number tensor data. Should only use when type is one of the following: (UINT8, INT8, UINT16,
     * INT16, INT32, UINT32, BOOL, FLOAT, DOUBLE)
     */
    get numberData() {
        if (this.type !== 'string') {
            return this.data;
        }
        throw new TypeError('type cannot be non-number (string)');
    }
    /**
     * get value of an element at the given indices
     */
    get(indices) {
        return this.data[util_1.ShapeUtil.indicesToOffset(indices, this.strides)];
    }
    /**
     * set value of an element at the given indices
     */
    set(indices, value) {
        this.data[util_1.ShapeUtil.indicesToOffset(indices, this.strides)] = value;
    }
    /**
     * get the underlying tensor data asynchronously
     */
    async getData() {
        if (this.cache === undefined) {
            this.cache = await this.asyncDataProvider(this.dataId);
        }
        return this.cache;
    }
    /**
     * get the strides for each dimension
     */
    get strides() {
        if (!this._strides) {
            this._strides = util_1.ShapeUtil.computeStrides(this.dims);
        }
        return this._strides;
    }
    constructor(
    /**
     * get the dimensions of the tensor
     */
    dims, 
    /**
     * get the type of the tensor
     */
    type, dataProvider, asyncDataProvider, cache, 
    /**
     * get the data ID that used to map to a tensor data
     */
    dataId = guid_typescript_1.Guid.create()) {
        this.dims = dims;
        this.type = type;
        this.dataProvider = dataProvider;
        this.asyncDataProvider = asyncDataProvider;
        this.cache = cache;
        this.dataId = dataId;
        this.size = util_1.ShapeUtil.validateDimsAndCalcSize(dims);
        const size = this.size;
        const empty = (dataProvider === undefined && asyncDataProvider === undefined && cache === undefined);
        if (cache !== undefined) {
            if (cache.length !== size) {
                throw new RangeError('Input dims doesn\'t match data length.');
            }
        }
        if (type === 'string') {
            if (cache !== undefined && (!Array.isArray(cache) || !cache.every(i => typeof i === 'string'))) {
                throw new TypeError('cache should be a string array');
            }
            if (empty) {
                this.cache = new Array(size);
            }
        }
        else {
            if (cache !== undefined) {
                const constructor = dataviewConstructor(type);
                if (!(cache instanceof constructor)) {
                    throw new TypeError(`cache should be type ${constructor.name}`);
                }
            }
            if (empty) {
                const buf = new ArrayBuffer(size * sizeof(type));
                this.cache = createView(buf, type);
            }
        }
    }
    /**
     * Construct new Tensor from a ONNX Tensor object
     * @param tensorProto the ONNX Tensor
     */
    static fromProto(tensorProto) {
        if (!tensorProto) {
            throw new Error('cannot construct Value from an empty tensor');
        }
        const type = util_1.ProtoUtil.tensorDataTypeFromProto(tensorProto.dataType);
        const dims = util_1.ProtoUtil.tensorDimsFromProto(tensorProto.dims);
        const value = new Tensor(dims, type);
        if (type === 'string') {
            // When it's STRING type, the value should always be stored in field
            // 'stringData'
            tensorProto.stringData.forEach((str, i) => {
                value.data[i] = (0, util_1.decodeUtf8String)(str);
            });
        }
        else if (tensorProto.rawData && typeof tensorProto.rawData.byteLength === 'number' &&
            tensorProto.rawData.byteLength > 0) {
            // NOT considering segment for now (IMPORTANT)
            // populate value from rawData
            const dataDest = value.data;
            const dataSource = new DataView(tensorProto.rawData.buffer, tensorProto.rawData.byteOffset, tensorProto.rawData.byteLength);
            const elementSize = sizeofProto(tensorProto.dataType);
            const length = tensorProto.rawData.byteLength / elementSize;
            if (tensorProto.rawData.byteLength % elementSize !== 0) {
                throw new Error('invalid buffer length');
            }
            if (dataDest.length !== length) {
                throw new Error('buffer length mismatch');
            }
            for (let i = 0; i < length; i++) {
                const n = readProto(dataSource, tensorProto.dataType, i * elementSize);
                dataDest[i] = n;
            }
        }
        else {
            // populate value from array
            let array;
            switch (tensorProto.dataType) {
                case onnx_proto_1.onnx.TensorProto.DataType.FLOAT:
                    array = tensorProto.floatData;
                    break;
                case onnx_proto_1.onnx.TensorProto.DataType.INT32:
                case onnx_proto_1.onnx.TensorProto.DataType.INT16:
                case onnx_proto_1.onnx.TensorProto.DataType.UINT16:
                case onnx_proto_1.onnx.TensorProto.DataType.INT8:
                case onnx_proto_1.onnx.TensorProto.DataType.UINT8:
                case onnx_proto_1.onnx.TensorProto.DataType.BOOL:
                    array = tensorProto.int32Data;
                    break;
                case onnx_proto_1.onnx.TensorProto.DataType.INT64:
                    array = tensorProto.int64Data;
                    break;
                case onnx_proto_1.onnx.TensorProto.DataType.DOUBLE:
                    array = tensorProto.doubleData;
                    break;
                case onnx_proto_1.onnx.TensorProto.DataType.UINT32:
                case onnx_proto_1.onnx.TensorProto.DataType.UINT64:
                    array = tensorProto.uint64Data;
                    break;
                default:
                    // should never run here
                    throw new Error('unspecific error');
            }
            if (array === null || array === undefined) {
                throw new Error('failed to populate data from a tensorproto value');
            }
            const data = value.data;
            if (data.length !== array.length) {
                throw new Error('array length mismatch');
            }
            for (let i = 0; i < array.length; i++) {
                const element = array[i];
                if (long_1.default.isLong(element)) {
                    data[i] = longToNumber(element, tensorProto.dataType);
                }
                else {
                    data[i] = element;
                }
            }
        }
        return value;
    }
    /**
     * Construct new Tensor from raw data
     * @param data the raw data object. Should be a string array for 'string' tensor, and the corresponding typed array
     * for other types of tensor.
     * @param dims the dimensions of the tensor
     * @param type the type of the tensor
     */
    static fromData(data, dims, type) {
        return new Tensor(dims, type, undefined, undefined, data);
    }
    static fromOrtTensor(ortTensor) {
        if (!ortTensor) {
            throw new Error('cannot construct Value from an empty tensor');
        }
        const dims = util_1.ProtoUtil.tensorDimsFromORTFormat(ortTensor);
        const type = util_1.ProtoUtil.tensorDataTypeFromProto(ortTensor.dataType());
        const value = new Tensor(dims, type);
        if (type === 'string') {
            // When it's STRING type, the value should always be stored in field
            // 'stringData'
            for (let i = 0; i < ortTensor.stringDataLength(); i++) {
                value.data[i] = ortTensor.stringData(i);
            }
        }
        else if (ortTensor.rawDataArray() && typeof ortTensor.rawDataLength() === 'number' && ortTensor.rawDataLength() > 0) {
            // NOT considering segment for now (IMPORTANT)
            // populate value from rawData
            const dataDest = value.data;
            const dataSource = new DataView(ortTensor.rawDataArray().buffer, ortTensor.rawDataArray().byteOffset, ortTensor.rawDataLength());
            const elementSize = sizeofProto(ortTensor.dataType());
            const length = ortTensor.rawDataLength() / elementSize;
            if (ortTensor.rawDataLength() % elementSize !== 0) {
                throw new Error('invalid buffer length');
            }
            if (dataDest.length !== length) {
                throw new Error('buffer length mismatch');
            }
            for (let i = 0; i < length; i++) {
                const n = readProto(dataSource, ortTensor.dataType(), i * elementSize);
                dataDest[i] = n;
            }
        }
        return value;
    }
}
exports.Tensor = Tensor;
function sizeof(type) {
    switch (type) {
        case 'bool':
        case 'int8':
        case 'uint8':
            return 1;
        case 'int16':
        case 'uint16':
            return 2;
        case 'int32':
        case 'uint32':
        case 'float32':
            return 4;
        case 'float64':
            return 8;
        default:
            throw new Error(`cannot calculate sizeof() on type ${type}`);
    }
}
function sizeofProto(type) {
    switch (type) {
        case onnx_proto_1.onnx.TensorProto.DataType.UINT8:
        case onnx_proto_1.onnx.TensorProto.DataType.INT8:
        case onnx_proto_1.onnx.TensorProto.DataType.BOOL:
            return 1;
        case onnx_proto_1.onnx.TensorProto.DataType.UINT16:
        case onnx_proto_1.onnx.TensorProto.DataType.INT16:
            return 2;
        case onnx_proto_1.onnx.TensorProto.DataType.FLOAT:
        case onnx_proto_1.onnx.TensorProto.DataType.INT32:
        case onnx_proto_1.onnx.TensorProto.DataType.UINT32:
            return 4;
        case onnx_proto_1.onnx.TensorProto.DataType.INT64:
        case onnx_proto_1.onnx.TensorProto.DataType.DOUBLE:
        case onnx_proto_1.onnx.TensorProto.DataType.UINT64:
            return 8;
        default:
            throw new Error(`cannot calculate sizeof() on type ${onnx_proto_1.onnx.TensorProto.DataType[type]}`);
    }
}
function createView(dataBuffer, type) {
    return new (dataviewConstructor(type))(dataBuffer);
}
function dataviewConstructor(type) {
    switch (type) {
        case 'bool':
        case 'uint8':
            return Uint8Array;
        case 'int8':
            return Int8Array;
        case 'int16':
            return Int16Array;
        case 'uint16':
            return Uint16Array;
        case 'int32':
            return Int32Array;
        case 'uint32':
            return Uint32Array;
        case 'float32':
            return Float32Array;
        case 'float64':
            return Float64Array;
        default:
            // should never run to here
            throw new Error('unspecified error');
    }
}
// convert a long number to a 32-bit integer (cast-down)
function longToNumber(i, type) {
    // INT64, UINT32, UINT64
    if (type === onnx_proto_1.onnx.TensorProto.DataType.INT64 || type === ortFbs.TensorDataType.INT64) {
        if (i.greaterThanOrEqual(2147483648) || i.lessThan(-2147483648)) {
            throw new TypeError('int64 is not supported');
        }
    }
    else if (type === onnx_proto_1.onnx.TensorProto.DataType.UINT32 || type === ortFbs.TensorDataType.UINT32 ||
        type === onnx_proto_1.onnx.TensorProto.DataType.UINT64 || type === ortFbs.TensorDataType.UINT64) {
        if (i.greaterThanOrEqual(4294967296) || i.lessThan(0)) {
            throw new TypeError('uint64 is not supported');
        }
    }
    else {
        throw new TypeError(`not a LONG type: ${onnx_proto_1.onnx.TensorProto.DataType[type]}`);
    }
    return i.toNumber();
}
// read one value from TensorProto
function readProto(view, type, byteOffset) {
    switch (type) {
        case onnx_proto_1.onnx.TensorProto.DataType.BOOL:
        case onnx_proto_1.onnx.TensorProto.DataType.UINT8:
            return view.getUint8(byteOffset);
        case onnx_proto_1.onnx.TensorProto.DataType.INT8:
            return view.getInt8(byteOffset);
        case onnx_proto_1.onnx.TensorProto.DataType.UINT16:
            return view.getUint16(byteOffset, true);
        case onnx_proto_1.onnx.TensorProto.DataType.INT16:
            return view.getInt16(byteOffset, true);
        case onnx_proto_1.onnx.TensorProto.DataType.FLOAT:
            return view.getFloat32(byteOffset, true);
        case onnx_proto_1.onnx.TensorProto.DataType.INT32:
            return view.getInt32(byteOffset, true);
        case onnx_proto_1.onnx.TensorProto.DataType.UINT32:
            return view.getUint32(byteOffset, true);
        case onnx_proto_1.onnx.TensorProto.DataType.INT64:
            return longToNumber(long_1.default.fromBits(view.getUint32(byteOffset, true), view.getUint32(byteOffset + 4, true), false), type);
        case onnx_proto_1.onnx.TensorProto.DataType.DOUBLE:
            return view.getFloat64(byteOffset, true);
        case onnx_proto_1.onnx.TensorProto.DataType.UINT64:
            return longToNumber(long_1.default.fromBits(view.getUint32(byteOffset, true), view.getUint32(byteOffset + 4, true), true), type);
        default:
            throw new Error(`cannot read from DataView for type ${onnx_proto_1.onnx.TensorProto.DataType[type]}`);
    }
}


/***/ }),

/***/ "./lib/onnxjs/util.ts":
/*!****************************!*\
  !*** ./lib/onnxjs/util.ts ***!
  \****************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.decodeUtf8String = exports.MAX_CLIP = exports.MIN_CLIP = exports.PoolConvUtil = exports.ReduceUtil = exports.SplitUtil = exports.MathUtil = exports.ShapeUtil = exports.LongUtil = exports.ProtoUtil = exports.GemmUtil = exports.arrayCopyHelper = exports.BroadcastUtil = exports.MatMulUtil = exports.ArrayUtil = exports.assert = exports.checkInputsShape = void 0;
const flatbuffers_1 = __webpack_require__(/*! flatbuffers */ "./node_modules/flatbuffers/js/flatbuffers.mjs");
const long_1 = __importDefault(__webpack_require__(/*! long */ "./node_modules/long/src/long.js"));
const onnx_proto_1 = __webpack_require__(/*! onnx-proto */ "./node_modules/onnx-proto/dist/onnx.js");
const tensor_1 = __webpack_require__(/*! ./tensor */ "./lib/onnxjs/tensor.ts");
// check the inputs shape before running an OP.
// return true when the inputs pass the check
// return false when the inputs do not fit the requirement
// throw exception when fatal error or not implemented
function checkInputsShape(inputs, ...expectedDimensions) {
    if (!inputs || inputs.length !== expectedDimensions.length) {
        return false;
    }
    for (let i = 0; i < inputs.length; i++) {
        if (!inputs[i].dims || inputs[i].dims.length !== expectedDimensions[i]) {
            return false;
        }
    }
    return true;
}
exports.checkInputsShape = checkInputsShape;
// Evaluates the given expression and asserts error message if condition is unmet.
function assert(expr, msg) {
    if (!expr) {
        throw new Error(typeof msg === 'string' ? msg : msg());
    }
}
exports.assert = assert;
class ArrayUtil {
    /**
     * Verifies if 2 input arrays contain the same elements.
     * @param n1 Array 1
     * @param n2 Array 2
     * @returns Whether these 2 are equal
     */
    static arraysEqual(n1, n2) {
        if (n1.length !== n2.length) {
            return false;
        }
        for (let i = 0; i < n1.length; i++) {
            if (n1[i] !== n2[i]) {
                return false;
            }
        }
        return true;
    }
}
exports.ArrayUtil = ArrayUtil;
class MatMulUtil {
    /**
     * Fix the input shapes for MatMul operation if they need fixing
     * @param dimsA The shape of tensor A. Should be an array of positive integers
     * @param dimsB The shape of tensor B. Should be an array of positive integers
     * @returns A tuple containing the preprocessed input shapes as required by ONNX specifications
     */
    static preprocessInputShapes(dimsA, dimsB) {
        // If the first argument is 1-D, it is promoted to a matrix by prepending
        // a 1 to its dimensions. After matrix multiplication the prepended 1 is
        // removed.
        const a = (dimsA.length === 1) ? [1, dimsA[0]] : dimsA;
        // If the second argument is 1-D, it is promoted to a matrix by appending
        // a 1 to its dimensions. After matrix multiplication the appended 1 is
        // removed.
        const b = (dimsB.length === 1) ? [dimsB[0], 1] : dimsB;
        return [a, b];
    }
    /**
     * Fix the output shape computed for MatMul operation if it needs fixing
     * @param outputShape The computed outputShape. Should be an array (atleast of length 2) of positive integers.
     * This will be mutated.
     * @param aRank The rank of tensor A.
     * @param bRank The rank of tensor B.
     */
    static postprocessOutputShape(outputShape, aRank, bRank) {
        // Remove prepended dimension if first input is 1d
        if (aRank === 1) {
            // outputShape = outputShape.slice(0, outputShape.length - 2).concat(outputShape.slice(outputShape.length - 1));
            outputShape.splice(outputShape.length - 2, 1);
        }
        // Remove appended dimension if second input is 1d
        if (bRank === 1) {
            outputShape.pop();
        }
    }
    /**
     * Calculate the expected shape when matrix multiplication
     * @param a The shape of tensor A. Should be a tuple of 2 positive integers
     * @param b The shape of tensor B. Should be a tuple of 2 positive integers
     * @returns The expected shape of the result, or undefined if N/A
     */
    static calcMatMulShape(a, b) {
        return (a[1] !== b[0]) ? undefined : [a[0], b[1]];
    }
}
exports.MatMulUtil = MatMulUtil;
class BroadcastUtil {
    /**
     * Calculate the expected shape when broadcasting 2 tensors
     * @param a The shape of tensor A. Should be an array of positive integers
     * @param b The shape of tensor B. Should be an array of positive integers
     * @param isMatMul Whether the operation is MatMul
     * @returns The expected shape of the result, or undefined if N/A
     */
    static calcShape(adims, bdims, isMatMul = false) {
        const arank = adims.length;
        const brank = bdims.length;
        if (arank === 0) {
            return bdims;
        }
        if (brank === 0) {
            return adims;
        }
        const crank = Math.max(adims.length, bdims.length);
        const cdims = new Array(crank);
        // calculate the last 2 dimension if it is MatMul
        if (isMatMul) {
            if (arank < 2 || brank < 2) {
                return undefined;
            }
            const cShapeMatMul = MatMulUtil.calcMatMulShape([adims[arank - 2], adims[arank - 1]], [bdims[brank - 2], bdims[brank - 1]]);
            if (cShapeMatMul === undefined) {
                return undefined;
            }
            [cdims[crank - 2], cdims[crank - 1]] = cShapeMatMul;
        }
        for (let i = isMatMul ? 3 : 1; i <= crank; i++) {
            const aLen = arank - i < 0 ? 1 : adims[arank - i];
            const bLen = brank - i < 0 ? 1 : bdims[brank - i];
            if (aLen !== bLen && aLen > 1 && bLen > 1) {
                return undefined;
            }
            cdims[crank - i] = Math.max(aLen, bLen);
        }
        return cdims;
    }
    /**
     * Given the indices of a broadcasted tensor, calculate the original indices
     * @param broadcastedIndices The given indices of the broadcasted tensor.
     * @param originalShape The original shape of the tensor before broadcas
     * @returns The calculated indices that maps to the original tensor.
     */
    static index(broadcastedIndices, originalShape) {
        // NOTE 1: we assume the parameter broadcastedIndices is valid. ie. it should have the same
        // length as the broadcasted shape, and for each dimension the index should
        // not be out of range.
        const originalIndices = new Array(originalShape.length);
        BroadcastUtil.fillIndex(broadcastedIndices, originalShape, originalIndices);
        return originalIndices;
    }
    /**
     * Given the indices of a broadcasted tensor, calculate the original indices
     * @param broadcastedIndices The given indices of the broadcasted tensor.
     * @param originalShape The original shape of the tensor before broadcast
     * @param originalIndices The mapping of broadcastedIndices to the originalIndices (output parameter - will be
     *     mutated).
     */
    static fillIndex(broadcastedIndices, originalShape, originalIndices) {
        // NOTE 1: we assume the parameter broadcastedIndices is valid. ie. it should have the same length as the
        // broadcasted shape, and for each dimension the index should not be out of range.
        // NOTE 2: we assume the parameter originalIndices has the same length as the originalShape
        const dimOffset = broadcastedIndices.length - originalShape.length;
        for (let i = 0; i < originalShape.length; i++) {
            originalIndices[i] = broadcastedIndices[dimOffset + i] % originalShape[i];
        }
    }
    /**
     * Perform the broadcasting operation on the specific operator
     * @param a The input tensor A
     * @param b The input tensor B
     * @param op The operator lambda function
     * @param inplace Whether to write the result back to A.
     * @returns The result tensor, or undefined if input not broadcastable.
     */
    static calc(a, b, op, inplace, resultType) {
        const outputShape = BroadcastUtil.calcShape(a.dims, b.dims);
        if (outputShape) {
            if (inplace && !ShapeUtil.areEqual(outputShape, a.dims)) {
                // B is not broadcastable to A, failed to calculate inplace.
                return undefined;
            }
            const size = ShapeUtil.size(outputShape);
            const c = inplace ? a : new tensor_1.Tensor(outputShape, resultType || a.type);
            // both inputs are scalars
            if (outputShape.length === 0) {
                c.set([], op(a.get([]), b.get([])));
            }
            // atleast one input is a non-scalar
            else {
                const outputIndices = new Array(outputShape.length);
                const originalIndicesA = new Array(a.dims.length);
                const originalIndicesB = new Array(b.dims.length);
                let valA = 0;
                let valB = 0;
                let isAScalar = false;
                let isBScalar = false;
                if (a.dims.length === 0) {
                    valA = a.get([]);
                    isAScalar = true;
                }
                if (b.dims.length === 0) {
                    valB = b.get([]);
                    isBScalar = true;
                }
                let rest;
                for (let i = 0; i < size; i++) {
                    // traversal indices
                    rest = i;
                    for (let j = outputShape.length - 1; j >= 0; j--) {
                        outputIndices[j] = rest % outputShape[j];
                        rest = Math.floor(rest / outputShape[j]);
                    }
                    if (!isAScalar) {
                        // map outputIndices (which is actually broadcasted) to the originalIndices
                        BroadcastUtil.fillIndex(outputIndices, a.dims, originalIndicesA);
                        valA = a.get(originalIndicesA);
                    }
                    if (!isBScalar) {
                        BroadcastUtil.fillIndex(outputIndices, b.dims, originalIndicesB);
                        valB = b.get(originalIndicesB);
                    }
                    c.set(outputIndices, op(valA, valB));
                }
            }
            return c;
        }
        return undefined;
    }
    /**
     * Determine if a shape is unidirectional broadcastable to another shape
     * @param shape The input shape
     * @param finalShape The desired shape after broadcasting
     */
    static isValidBroadcast(shape, finalShape) {
        // align shape to the right
        const inputRank = shape.length;
        const finalRank = finalShape.length;
        if (inputRank > finalRank) {
            return false;
        }
        for (let i = 1; i <= inputRank; i++) {
            if (shape[inputRank - i] !== 1 && shape[inputRank - i] !== finalShape[finalRank - i]) {
                return false;
            }
        }
        return true;
    }
    /**
     * Determine the broadcasted dims in input shape based on the given output shape.
     * Note that this function only returns the broadcasted dims.
     * @param inputShape The input shape
     * @param outputShape The output shape
     * @returns The broadcasted dims in input shape.
     */
    static getBroadcastDims(inputShape, outputShape) {
        const inRank = inputShape.length;
        const dims = [];
        for (let i = 0; i < inRank; i++) {
            const dim = inRank - 1 - i;
            const a = inputShape[dim] || 1;
            const b = outputShape[outputShape.length - 1 - i] || 1;
            if (b > 1 && a === 1) {
                dims.unshift(dim);
            }
        }
        return dims;
    }
}
exports.BroadcastUtil = BroadcastUtil;
// copy array helper
// mimics memcpy as much as possible
function arrayCopyHelper(target, source, targetIndex, sourceIndex, blockSize) {
    if (sourceIndex < 0 || sourceIndex >= source.length) {
        throw new Error('sourceIndex out of bounds');
    }
    if (targetIndex < 0 || targetIndex >= target.length) {
        throw new Error('targetIndex out of bounds');
    }
    if (sourceIndex + blockSize > source.length) {
        throw new Error('source indices to be copied are outside bounds');
    }
    if (targetIndex + blockSize > target.length) {
        throw new Error('target array is too small to hold result');
    }
    for (let offset = 0; offset < blockSize; offset++) {
        target[targetIndex + offset] = source[sourceIndex + offset];
    }
}
exports.arrayCopyHelper = arrayCopyHelper;
class GemmUtil {
    // will make sure input shapes are compatible for this op
    // and return back the shape of the output in the form of a tuple
    // will throw exception if the input shapes are not compatible
    static getShapeOfGemmResult(leftShape, transLeft, rightShape, transRight, biasShape) {
        if (leftShape.length !== 2 || rightShape.length !== 2) {
            throw new Error('shape need to be of size 2');
        }
        let M;
        let K;
        let N;
        if (transLeft) {
            M = leftShape[1];
            K = leftShape[0];
        }
        else {
            M = leftShape[0];
            K = leftShape[1];
        }
        let kDim = -1;
        if (transRight) {
            N = rightShape[0];
            kDim = 1;
        }
        else {
            N = rightShape[1];
            kDim = 0;
        }
        if (rightShape[kDim] !== K) {
            throw new Error('dimension mismatch');
        }
        if (M <= 0 || N <= 0 || K <= 0) {
            throw new Error('invalid shape specified');
        }
        if (biasShape && !BroadcastUtil.isValidBroadcast(biasShape, [M, N])) {
            throw new Error('gemm: invalid bias shape for broadcast');
        }
        return [M, N, K];
    }
}
exports.GemmUtil = GemmUtil;
class ProtoUtil {
    static tensorDataTypeFromProto(typeProto) {
        switch (typeProto) {
            case onnx_proto_1.onnx.TensorProto.DataType.INT8:
                return 'int8';
            case onnx_proto_1.onnx.TensorProto.DataType.UINT8:
                return 'uint8';
            case onnx_proto_1.onnx.TensorProto.DataType.BOOL:
                return 'bool';
            case onnx_proto_1.onnx.TensorProto.DataType.INT16:
                return 'int16';
            case onnx_proto_1.onnx.TensorProto.DataType.UINT16:
                return 'uint16';
            case onnx_proto_1.onnx.TensorProto.DataType.INT32:
                return 'int32';
            case onnx_proto_1.onnx.TensorProto.DataType.UINT32:
                return 'uint32';
            case onnx_proto_1.onnx.TensorProto.DataType.FLOAT:
                return 'float32';
            case onnx_proto_1.onnx.TensorProto.DataType.DOUBLE:
                return 'float64';
            case onnx_proto_1.onnx.TensorProto.DataType.STRING:
                return 'string';
            // For INT64/UINT64, reduce their value to 32-bits.
            // Should throw exception when overflow
            case onnx_proto_1.onnx.TensorProto.DataType.INT64:
                return 'int32';
            case onnx_proto_1.onnx.TensorProto.DataType.UINT64:
                return 'uint32';
            default:
                throw new Error(`unsupported data type: ${onnx_proto_1.onnx.TensorProto.DataType[typeProto]}`);
        }
    }
    static tensorDataTypeStringToEnum(type) {
        switch (type) {
            case 'int8':
                return onnx_proto_1.onnx.TensorProto.DataType.INT8;
            case 'uint8':
                return onnx_proto_1.onnx.TensorProto.DataType.UINT8;
            case 'bool':
                return onnx_proto_1.onnx.TensorProto.DataType.BOOL;
            case 'int16':
                return onnx_proto_1.onnx.TensorProto.DataType.INT16;
            case 'uint16':
                return onnx_proto_1.onnx.TensorProto.DataType.UINT16;
            case 'int32':
                return onnx_proto_1.onnx.TensorProto.DataType.INT32;
            case 'uint32':
                return onnx_proto_1.onnx.TensorProto.DataType.UINT32;
            case 'float32':
                return onnx_proto_1.onnx.TensorProto.DataType.FLOAT;
            case 'float64':
                return onnx_proto_1.onnx.TensorProto.DataType.DOUBLE;
            case 'string':
                return onnx_proto_1.onnx.TensorProto.DataType.STRING;
            case 'int64':
                return onnx_proto_1.onnx.TensorProto.DataType.INT64;
            case 'uint64':
                return onnx_proto_1.onnx.TensorProto.DataType.UINT64;
            default:
                throw new Error(`unsupported data type: ${type}`);
        }
    }
    static tensorDimsFromProto(dims) {
        // get rid of Long type for dims
        return dims.map(d => long_1.default.isLong(d) ? d.toNumber() : d);
    }
    static tensorValueTypeFromProto(valueType) {
        return {
            tensorType: ProtoUtil.tensorDataTypeFromProto(valueType.elemType),
            shape: { dims: ProtoUtil.tensorDimsFromProto(valueType.shape.dim.map(d => d.dimValue)) }
        };
    }
    static tensorDimsFromORTFormat(tensor) {
        const dims = [];
        for (let i = 0; i < tensor.dimsLength(); i++) {
            dims.push(LongUtil.longToNumber(tensor.dims(i)));
        }
        return dims;
    }
    static tensorAttributesFromORTFormat(node) {
        const attributes = [];
        for (let i = 0; i < node.attributesLength(); i++) {
            attributes.push(node.attributes(i));
        }
        return attributes;
    }
}
exports.ProtoUtil = ProtoUtil;
class LongUtil {
    // This function is called to get a number from long type of data for attribute, dim, and ir version,
    // which values are signed integers.
    // To make it more generic, add an optional paramter to convert to a unsigned number.
    static longToNumber(n, unsigned) {
        if (long_1.default.isLong(n)) {
            return n.toNumber();
        }
        else if (n instanceof flatbuffers_1.flatbuffers.Long) {
            return long_1.default.fromValue({ low: n.low, high: n.high, unsigned: unsigned !== null && unsigned !== void 0 ? unsigned : false }).toNumber();
        }
        return n;
    }
    static isLong(n) {
        return long_1.default.isLong(n) || n instanceof flatbuffers_1.flatbuffers.Long;
    }
}
exports.LongUtil = LongUtil;
class ShapeUtil {
    static size(dims) {
        return ShapeUtil.getSizeFromDimensionRange(dims, 0, dims.length);
    }
    // `axis` inclusive
    static sizeFromDimension(dims, axis) {
        if (axis < 0 || axis > dims.length) {
            throw new Error(`invalid dimension of ${axis} for sizeFromDimension as Tensor has ${dims.length} dimensions.`);
        }
        return ShapeUtil.getSizeFromDimensionRange(dims, axis, dims.length);
    }
    // `axis` exclusive
    static sizeToDimension(dims, axis) {
        if (axis < 0 || axis > dims.length) {
            throw new Error(`invalid dimension of ${axis} for sizeToDimension as Tensor has ${dims.length} dimensions.`);
        }
        return ShapeUtil.getSizeFromDimensionRange(dims, 0, axis);
    }
    static getSizeFromDimensionRange(dims, start, end) {
        let size = 1;
        for (let i = start; i < end; i++) {
            // safety check as this method is called by multiple other methods requiring size.
            // size cannot be 0 or negative.
            if (dims[i] <= 0) {
                throw new Error(
                // eslint-disable-next-line max-len
                'cannot get valid size from specified dimension range. Most likely the range contains 0 or negative values in them.');
            }
            size *= dims[i];
        }
        return size;
    }
    static computeStrides(dims) {
        const rank = dims.length;
        if (rank === 0) {
            return [];
        }
        else if (rank === 1) {
            return [1];
        }
        const strides = new Array(rank);
        strides[rank - 1] = 1;
        strides[rank - 2] = dims[rank - 1];
        for (let i = rank - 3; i >= 0; --i) {
            strides[i] = strides[i + 1] * dims[i + 1];
        }
        return strides;
    }
    static transpose(dims) {
        const copy = dims.slice();
        return copy.reverse();
    }
    static indicesToOffset(indices, strides, axis) {
        if (axis === undefined) {
            axis = indices.length;
        }
        let offset = 0;
        for (let i = 0; i < axis; ++i) {
            offset += strides[i] * indices[i];
        }
        return offset;
    }
    static offsetToIndices(offset, strides) {
        const rank = strides.length;
        if (rank === 0) {
            return [];
        }
        else if (rank === 1) {
            return [offset * strides[0]];
        }
        const indices = new Array(strides.length);
        for (let i = 0; i < indices.length - 1; ++i) {
            indices[i] = Math.floor(offset / strides[i]);
            offset -= indices[i] * strides[i];
        }
        indices[indices.length - 1] = offset;
        return indices;
    }
    /**
     * normailze axis of range [-r, r) into [0, r).
     */
    static normalizeAxis(axis, tensorRank) {
        if (axis < -tensorRank && axis >= tensorRank) {
            throw new Error('unsupported axis for this operation.');
        }
        return axis < 0 ? axis + tensorRank : axis;
    }
    static normalizeAxes(axes, tensorRank) {
        return axes.map(x => this.normalizeAxis(x, tensorRank));
    }
    // Increment an index into a tensor (in lexicographic
    // ordering), wrapping around the specified upper_bound.
    /**
     * Increment an index into a tensor (in lexicographic ordering), wrapping around the specified upper_bound.
     * @param index Given index to increment (Will be mutated)
     * @param dims The dimensions of the tensor for which the given index corresponds to
     * @param axisToIncrementOn The 1-indexed axis to increment on. If undefined, axisToIncrementOn == rank
     */
    static incrementIndex(index, dims, axisToIncrementOn) {
        if (dims.length === 0 || index.length === 0) {
            throw new Error('Index incrementing unsupported for scalar Tensor');
        }
        if (axisToIncrementOn === undefined) {
            axisToIncrementOn = dims.length;
        }
        else {
            if (axisToIncrementOn <= 0 || axisToIncrementOn > dims.length) {
                throw new Error('Incorrect axis to increment on');
            }
        }
        for (let k = axisToIncrementOn - 1; k >= 0; --k) {
            index[k]++;
            if (index[k] < dims[k]) {
                break;
            }
            index[k] = 0;
        }
    }
    /**
     * Produces a new dimensions array based on the values in the 'originalDimensions' and 'shape' array
     * Used in Reshape
     * @param originalDims Original Shape array
     * @param shapeHints array containing values to compute the new dimensions
     * For example:
     * originalDims = [2,2] and shapeHints = [0,-1] will return [2,2]
     * originalDims = [2,2] and shapeHints = [4] will return [4]
     * originalDims = [2,2] and shapeHints = [5] will throw an exception
     * https://github.com/onnx/onnx/blob/main/docs/Operators.md#Reshape
     */
    static calculateReshapedDims(originalDims, shapeHints) {
        // reshape to a Scalar Tensor
        if (shapeHints.length === 0) {
            if (originalDims.length === 0 || ShapeUtil.size(originalDims) === 1) {
                return [];
            }
            else {
                throw new Error('cannot reshape to a scalar Tensor');
            }
        }
        const nDims = shapeHints.length;
        const reshapedDims = new Array(nDims);
        let unknownDimension = -1;
        let newTensorSize = 1;
        for (let i = 0; i < nDims; i++) {
            if (shapeHints[i] < -1) {
                throw new Error('a dimension in shape hints cannot be less than -1');
            }
            if (shapeHints[i] === -1) {
                if (unknownDimension !== -1) {
                    throw new Error('at most one dimension in shape hints can be -1');
                }
                unknownDimension = i;
            }
            else {
                if (shapeHints[i] === 0) {
                    if (i >= originalDims.length) {
                        throw new Error('the dimension with value zero exceeds the dimension size of the input tensor');
                    }
                    reshapedDims[i] = originalDims[i];
                }
                else {
                    reshapedDims[i] = shapeHints[i];
                }
                newTensorSize *= reshapedDims[i];
            }
        }
        const oldTensorSize = ShapeUtil.size(originalDims);
        if (unknownDimension !== -1) {
            if (oldTensorSize % newTensorSize !== 0) {
                throw new Error(`the input tensor cannot be reshaped to the requested shape. Input shape: [${originalDims}] Output shape: [${shapeHints}]`);
            }
            reshapedDims[unknownDimension] = oldTensorSize / newTensorSize;
        }
        // validate sizes from originalDims and reshapedDims match
        else {
            if (newTensorSize !== oldTensorSize) {
                throw new Error('reshapedDims and originalDims don\'t have matching sizes');
            }
        }
        return reshapedDims;
    }
    /**
     * Sorts a given array based on the indices in the Perm array
     * Used in Transpose
     * @param a Array to be sorted such as dims or strides
     * @param perm Perm given; if null a will be reversed
     */
    static sortBasedOnPerm(a, perm) {
        if (perm) {
            return perm.map((v) => a[v]);
        }
        else {
            return a.slice().reverse();
        }
    }
    /**
     * Pads a given shape according to the padding values
     * @param dims shape of the Tensor to be padded
     * @param pad pad values
     */
    static padShape(dims, pad) {
        const rank = dims.length;
        return dims.map((v, i) => v + pad[i] + pad[i + rank]);
    }
    /**
     * Determines if the two shapes are identical
     * @param shape1
     * @param shape2
     */
    static areEqual(shape1, shape2) {
        if (shape1.length !== shape2.length) {
            return false;
        }
        return shape1.every((v, i) => v === shape2[i]);
    }
    /**
     * Validates if the given `dims` or `shape` is valid in ONNX.js context and returns data size
     * @param dims - input `dims` that needs to be checked
     */
    static validateDimsAndCalcSize(dims) {
        if (dims.length > 6) {
            throw new TypeError('Only rank 0 to 6 is supported for tensor shape.');
        }
        let size = 1;
        for (const n of dims) {
            if (!Number.isInteger(n)) {
                throw new TypeError(`Invalid shape: ${n} is not an integer`);
            }
            if (n < 0 || n > 2147483647) {
                throw new TypeError(`Invalid shape: length ${n} is not allowed`);
            }
            size *= n;
        }
        return size;
    }
    /**
     * Determines the shape of output tensor y = flatten(x, axis)
     * @param dims - shape of input tensor
     * @param axis - flatten axis, in the range [-r, r]
     */
    static flattenShape(dims, axis) {
        if (axis < 0) {
            axis += dims.length;
        }
        const total = dims.reduce((x, y) => x * y, 1);
        const right = dims.slice(axis).reduce((x, y) => x * y, 1);
        const outputDims = [total / right, right];
        return outputDims;
    }
    /**
     * Determines the shape of output tensor y = squeeze(x, axes)
     * @param dims - shape of input tensor
     * @param axes - squeeze axes
     */
    static squeezeShape(dims, axes) {
        const outputDims = new Array();
        // sanity check
        axes = ShapeUtil.normalizeAxes(axes, dims.length);
        for (let i = 0; i < dims.length; i++) {
            const inSqueezeList = axes.indexOf(i) >= 0;
            if (inSqueezeList && dims[i] !== 1) {
                throw new Error('squeeze an axis of size different than 1');
            }
            if ((axes.length === 0 && dims[i] > 1) || (axes.length > 0 && !inSqueezeList)) {
                outputDims.push(dims[i]);
            }
        }
        return outputDims;
    }
    /**
     * Determines the shape of output tensor y = unsqueeze(x, axes)
     * @param dims - shape of input tensor
     * @param axes - unsqueeze axes
     */
    static unsqueezeShape(dims, axes) {
        const outputDims = new Array(dims.length + axes.length);
        // initialize the array elements to 0
        outputDims.fill(0);
        // set all axes indices to 1 in outputDims and check for duplicates
        for (let i = 0; i < axes.length; i++) {
            const axis = ShapeUtil.normalizeAxis(axes[i], outputDims.length);
            if (axis >= outputDims.length) {
                throw new Error('\'axes\' has an out of range axis');
            }
            if (outputDims[axis] !== 0) {
                throw new Error('\'axes\' has a duplicate axis');
            }
            outputDims[axis] = 1;
        }
        // fill in the zero entries of outputDims with the input tensor's shape
        let inputDimsIterator = 0;
        for (let i = 0; i < outputDims.length; i++) {
            if (outputDims[i] === 0) {
                outputDims[i] = dims[inputDimsIterator++];
            }
        }
        // sanity check assertion. 'inputDimsIterator'
        // should be equal to the length of 'dims'
        if (inputDimsIterator !== dims.length) {
            throw new Error('the unsqueezed dimension could not be established');
        }
        return outputDims;
    }
}
exports.ShapeUtil = ShapeUtil;
// bunch of helper methods that do a variety of math operations
class MathUtil {
    // y = (x*x) + y
    static sqr(target, source, targetIndex, sourceIndex, blockSize) {
        if (sourceIndex < 0 || sourceIndex >= source.length) {
            throw new Error('sourceIndex out of bounds');
        }
        if (targetIndex < 0 || targetIndex >= target.length) {
            throw new Error('targetIndex out of bounds');
        }
        if (sourceIndex + blockSize > source.length) {
            throw new Error('source indices to be copied are outside bounds');
        }
        if (targetIndex + blockSize > target.length) {
            throw new Error('target array is too small to hold result');
        }
        for (let offset = 0; offset < blockSize; offset++) {
            target[targetIndex + offset] += Math.pow(source[sourceIndex + offset], 2);
        }
    }
    // y = ax + y
    static axpy(target, source, targetIndex, sourceIndex, blockSize, alpha) {
        if (sourceIndex < 0 || sourceIndex >= source.length) {
            throw new Error('sourceIndex out of bounds');
        }
        if (targetIndex < 0 || targetIndex >= target.length) {
            throw new Error('targetIndex out of bounds');
        }
        if (sourceIndex + blockSize > source.length) {
            throw new Error('source indices to be copied are outside bounds');
        }
        if (targetIndex + blockSize > target.length) {
            throw new Error('target array is too small to hold result');
        }
        for (let offset = 0; offset < blockSize; offset++) {
            target[targetIndex + offset] += (alpha * source[sourceIndex + offset]);
        }
    }
    // y = pow(x, b)
    static powx(target, source, targetIndex, sourceIndex, blockSize, b) {
        if (sourceIndex < 0 || sourceIndex >= source.length) {
            throw new Error('sourceIndex out of bounds');
        }
        if (targetIndex < 0 || targetIndex >= target.length) {
            throw new Error('targetIndex out of bounds');
        }
        if (sourceIndex + blockSize > source.length) {
            throw new Error('source indices to be copied are outside bounds');
        }
        if (targetIndex + blockSize > target.length) {
            throw new Error('target array is too small to hold result');
        }
        for (let offset = 0; offset < blockSize; offset++) {
            target[targetIndex + offset] = Math.pow(source[sourceIndex + offset], b);
        }
    }
    // y = x * y
    static mul(target, source, targetIndex, sourceIndex, blockSize) {
        if (sourceIndex < 0 || sourceIndex >= source.length) {
            throw new Error('sourceIndex out of bounds');
        }
        if (targetIndex < 0 || targetIndex >= target.length) {
            throw new Error('targetIndex out of bounds');
        }
        if (sourceIndex + blockSize > source.length) {
            throw new Error('source indices to be copied are outside bounds');
        }
        if (targetIndex + blockSize > target.length) {
            throw new Error('target array is too small to hold result');
        }
        for (let offset = 0; offset < blockSize; offset++) {
            target[targetIndex + offset] = (source[sourceIndex + offset] * target[targetIndex + offset]);
        }
    }
}
exports.MathUtil = MathUtil;
class SplitUtil {
    /**
     * Calculates new Shapes from existing one and the splits given along the axis provides
     * @param dims Shape of the Tensor to be splitted into two or more Shapes
     * @param axis The dimension along which the Tensor will be split
     * @param splits Offsets for the start of each split
     */
    static splitShape(dims, axis, split, numOutputs) {
        if (split.length === 0) {
            if (!numOutputs) {
                throw new Error('need to know number of outputs when the \'split\' attribute is not specified');
            }
            SplitUtil.determineSplit(dims[axis], numOutputs, split);
        }
        const shapes = [];
        const offsets = [0];
        for (let i = 0; i < split.length; ++i) {
            if (i !== 0) {
                offsets.push(offsets[i - 1] + split[i - 1]);
            }
            const shape = dims.slice();
            shape[axis] = split[i];
            shapes.push(shape);
        }
        return [shapes, offsets];
    }
    static determineSplit(numElementsAlongAxis, numOutputs, split) {
        // If 'split' is not specified by the user, we need to partition the number of elements equally among the outputs
        if (numElementsAlongAxis % numOutputs !== 0) {
            throw new Error('cannot split tensor to equal sized parts');
        }
        for (let i = 0; i < numOutputs; ++i) {
            split.push(numElementsAlongAxis / numOutputs);
        }
    }
}
exports.SplitUtil = SplitUtil;
class ReduceUtil {
    /**
     * Perform reduce operations on the specific operator
     * @param a Input tensor data
     * @param axes The dimensions along which the Tensor will be reduced
     * @param keepdims If set to true, the axes which are reduced are left in the
     *    result as dimensions with size one.
     * @param op1 The operation to be performed on each element in the tensor
     * @param op2 The operation to be performed between elements in the tensor
     */
    static calcReduce(a, axes, keepdims, op1, op2) {
        const dims = a.dims.slice(0);
        // if axes is not set, perform reduce on all axes
        if (axes.length === 0) {
            dims.forEach((d, ind) => axes.push(ind));
        }
        // get a temporary broadcastable output shape
        const outputDims = ReduceUtil.calcReduceShape(dims, axes, true);
        // loop through the output and calculate result one by one
        const size = ShapeUtil.size(outputDims);
        const y = new tensor_1.Tensor(outputDims, a.type);
        const strides = ShapeUtil.computeStrides(outputDims);
        const inputStrides = ShapeUtil.computeStrides(dims);
        const indicesY = new Array(dims.length);
        for (let i = 0; i < size; i++) {
            const indices = ShapeUtil.offsetToIndices(i, strides);
            // map index
            BroadcastUtil.fillIndex(indices, dims, indicesY);
            y.set(indices, ReduceUtil.calcReduceByAxis(a.numberData, axes, dims, 0, ShapeUtil.indicesToOffset(indicesY, inputStrides), op1, op2));
        }
        if (keepdims) {
            return y;
        }
        else {
            // keepdims == 0, calculate the expected shape
            return new tensor_1.Tensor(ReduceUtil.calcReduceShape(dims, axes, keepdims), y.type, undefined, undefined, y.data, y.dataId);
        }
    }
    /**
     * Perform reduce operations on the specific operator on specific axes
     * @param a Input tensor data
     * @param axes The dimensions along which the Tensor will be reduced
     * @param dims The input dimension.
     * @param curAxisInd Index in axes specifying the current dimension along
     *      which the tensor will be reduced
     * @param pos The current index of element to perform operation
     * @param op1 The operation to be performed on each element in the tensor
     * @param op2 The operation to be performed between elements in the tensor
     */
    static calcReduceByAxis(input, axes, dims, curAxisInd, pos, op1, op2) {
        let res = 0;
        if (curAxisInd >= axes.length) {
            return op1(input[pos]);
        }
        const axis = axes[curAxisInd];
        const step = axis >= dims.length ? 1 : ShapeUtil.size(dims.slice(axis + 1));
        for (let i = 0; i < dims[axis]; i++) {
            res = i === 0 ? ReduceUtil.calcReduceByAxis(input, axes, dims, curAxisInd + 1, pos, op1, op2) :
                op2(res, ReduceUtil.calcReduceByAxis(input, axes, dims, curAxisInd + 1, pos, op1, op2));
            pos += step;
        }
        return res;
    }
    /**
     * Calculate the expected shape of a reduce operation
     * @param dims The input tensor dimension
     * @param axes The dimensions along which the Tensor will be reduced
     * @param keepdims If set to true, the axes which are reduced are left in the
     *    result as dimensions with size one.
     */
    static calcReduceShape(dims, axes, keepDims) {
        const outputDims = dims.slice();
        for (let i = 0; i < axes.length; i++) {
            if (keepDims) {
                outputDims[axes[i]] = 1;
            }
            else {
                outputDims[axes[i]] = 0;
            }
        }
        return outputDims.filter(dim => dim !== 0);
    }
}
exports.ReduceUtil = ReduceUtil;
class PoolConvUtil {
    /**
     * Adjust the kernel, strides, pads to correct rank. Set to default value if not present
     * @param isGlobalOperator If true, perform global pooling.
     * @param inputDims The input tensor dimension.
     * @param kernelShape The size of the kernel along each axis.
     * @param strides Stride along each axis.
     * @param dilations Dilation along each axis.
     * @param pads Padding for the beginning and ending along each axis.
     */
    static adjustPoolAttributes(isGlobalOperator, inputDims, kernelShape, strides, dilations, pads) {
        if (!isGlobalOperator && kernelShape.length !== inputDims.length - 2) {
            throw new Error('length of specified kernel shapes should be 2 less than length of input dimensions');
        }
        if (isGlobalOperator) {
            // adjust kernel shape to cover the input dims
            for (let dim = 0; dim < inputDims.length - 2; dim++) {
                if (dim >= kernelShape.length) {
                    kernelShape.push(inputDims[dim + 2]);
                }
                else {
                    kernelShape[dim] = inputDims[dim + 2];
                }
            }
        }
        // adjust strides length to match kernel shape length
        for (let dim = 0; dim < kernelShape.length; dim++) {
            if (dim < strides.length) {
                if (strides[dim] < 0) {
                    throw new Error('strides should be greater than or equal to 1');
                }
            }
            else {
                strides.push(1);
            }
        }
        // adjust dilation value
        for (let dim = 0; dim < kernelShape.length; dim++) {
            if (dim < dilations.length) {
                if (dilations[dim] < 0) {
                    throw new Error('dilations should be greater than or equal to 1');
                }
            }
            else {
                dilations.push(1);
            }
        }
        // adjust pads length to match 2 * kernel shape length
        for (let dim = 0; dim < kernelShape.length * 2; dim++) {
            if (dim < pads.length) {
                if (pads[dim] < 0) {
                    throw new Error('pad should be greater than or equal to 1');
                }
            }
            else {
                pads.push(0);
            }
        }
        // sanity checks for values in kernel shapes and pads
        for (let dim = 0; dim < kernelShape.length; dim++) {
            if (kernelShape[dim] <= 0) {
                throw new Error('kernel shapes need to be greater than 0');
            }
            if (pads[dim] >= kernelShape[dim] || pads[dim + kernelShape.length] >= kernelShape[dim]) {
                throw new Error('pads should be smaller than kernel');
            }
        }
    }
    // adjust pad values based on 'autoPad' attribute
    static adjustPadsBasedOnAutoPad(inputDims, strides, dilations, kernelShape, pads, autoPad) {
        if (!autoPad) {
            return;
        }
        if (pads.length !== 2 * (inputDims.length - 2)) {
            throw new Error('length of pads should be twice the length of data dimensions');
        }
        if (strides.length !== (inputDims.length - 2)) {
            throw new Error('length of strides should be the length of data dimensions');
        }
        if (kernelShape.length !== (inputDims.length - 2)) {
            throw new Error('length of kernel shapes should be the length of data dimensions');
        }
        for (let dim = 0; dim < inputDims.length - 2; dim++) {
            PoolConvUtil.adjustPadAndReturnShape(inputDims[dim + 2], strides[dim], dilations[dim], kernelShape[dim], pads, dim, dim + inputDims.length - 2, autoPad);
        }
    }
    /**
     * Calculate the output shape for Pool ops based on input attributes. (Should be used only for Pool ops)
     * @param isGlobalOperator If true, perform global pooling.
     * @param inputDims The input tensor dimension. (inputs[0].dims)
     * @param strides Stride along each axis.
     * @param dilations Dilation along each axis.
     * @param kernelShape The size of the kernel along each axis.
     * @param pads Padding for the beginning and ending along each axis.
     * @param autoPad DEPRECATED attribute supported for legacy models. Specifies how to implicitly calculate pads in each
     *     dimension. Can take values NOTSET, SAME_UPPER, SAME_LOWER, or VALID.
     */
    static computePoolOutputShape(isGlobalOperator, inputDims, strides, dilations, kernelShape, pads, autoPad) {
        if (inputDims.length <= 0) {
            throw new Error('input shape must be of size greater than 0');
        }
        // Add batch size and number of channels of output
        const outputDims = [inputDims[0], inputDims[1]];
        PoolConvUtil.computeShapeHelper(isGlobalOperator, inputDims, outputDims, strides, dilations, kernelShape, pads, autoPad);
        return outputDims;
    }
    /**
     * Calculate the output shape for Conv op based on input attributes. (Should be used only for Conv op)
     * @param inputDims The input tensor dimension. (inputs[0].dims)
     * @param filterDims The filter tensor dimension. (inputs[1].dims)
     * @param strides Stride along each axis.
     * @param kernelShape The size of the kernel along each axis.
     * @param pads Padding for the beginning and ending along each axis.
     * @param autoPad DEPRECATED attribute supported for legacy models. Specifies how to implicitly calculate pads in each
     *     dimension. Can take values NOTSET, SAME_UPPER, SAME_LOWER, or VALID.
     */
    static computeConvOutputShape(inputDims, filterDims, strides, dilations, kernelShape, pads, autoPad) {
        if (inputDims.length <= 0 || filterDims.length <= 0) {
            throw new Error('invalid input tensor dims or invalid filter tensor dims');
        }
        // Add batch size and number of channels of output
        const outputDims = [inputDims[0], filterDims[0]];
        PoolConvUtil.computeShapeHelper(false, inputDims, outputDims, strides, dilations, kernelShape, pads, autoPad);
        return outputDims;
    }
    // will compute output shapes for data dimensions ONLY (i.e.) no batch size and channels
    // called by computePoolOutputShape() and computeConvOutputShape()
    // adjust pads based on 'autoPad' attribute prior to shape computation
    static computeShapeHelper(isGlobalOperator, inputDims, outputDims, strides, dilations, kernelShape, pads, autoPad) {
        if (isGlobalOperator) {
            for (let dim = 0; dim < inputDims.length - 2; dim++) {
                outputDims.push(1);
            }
        }
        else {
            for (let dim = 0; dim < inputDims.length - 2; dim++) {
                outputDims.push(PoolConvUtil.adjustPadAndReturnShape(inputDims[dim + 2], strides[dim], dilations[dim], kernelShape[dim], pads, dim, dim + inputDims.length - 2, autoPad));
            }
        }
    }
    // helper for computeShapeHelper() and adjustPadsBasedOnAutoPad()
    // adjusts pad value for given 'autoPad' string and computes output shape along a particular dimension
    static adjustPadAndReturnShape(inSize, stride, dilation, kernel, pads, padHeadIndex, padTailIndex, autoPad) {
        const dkernel = dilation * (kernel - 1) + 1;
        if (autoPad && autoPad !== 'NOTSET') {
            switch (autoPad) {
                case 'VALID':
                    pads[padHeadIndex] = 0;
                    pads[padTailIndex] = 0;
                    return Math.floor(((inSize - dkernel) / stride) + 1);
                case 'SAME_LOWER':
                case 'SAME_UPPER':
                    if (dilation !== 1) {
                        throw new Error('Dilation not supported for SAME_UPPER or SAME_LOWER');
                    }
                    else {
                        const legacyTargetSize = (inSize + stride - 1) / stride;
                        const padNeeded = (legacyTargetSize - 1) * stride + kernel - inSize;
                        pads[padHeadIndex] =
                            (autoPad === 'SAME_LOWER') ? Math.floor((padNeeded + 1) / 2) : Math.floor(padNeeded / 2);
                        pads[padTailIndex] = padNeeded - pads[padHeadIndex];
                        return Math.floor(((inSize + padNeeded - kernel) / stride) + 1);
                    }
                default:
                    throw new Error('Unsupported AutoPad type');
            }
        }
        else {
            return Math.floor(((inSize + pads[padHeadIndex] + pads[padTailIndex] - dkernel) / stride) + 1);
        }
    }
}
exports.PoolConvUtil = PoolConvUtil;
exports.MIN_CLIP = -3.4028234663852886e+38;
exports.MAX_CLIP = 3.4028234663852886e+38;
function decodeUtf8String(buffer) {
    return new TextDecoder().decode(buffer);
}
exports.decodeUtf8String = decodeUtf8String;


/***/ }),

/***/ "./lib/wasm/options-utils.ts":
/*!***********************************!*\
  !*** ./lib/wasm/options-utils.ts ***!
  \***********************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.iterateExtraOptions = void 0;
const iterateExtraOptions = (options, prefix, seen, handler) => {
    if (typeof options == 'object' && options !== null) {
        if (seen.has(options)) {
            throw new Error('Circular reference in options');
        }
        else {
            seen.add(options);
        }
    }
    Object.entries(options).forEach(([key, value]) => {
        const name = (prefix) ? prefix + key : key;
        if (typeof value === 'object') {
            (0, exports.iterateExtraOptions)(value, name + '.', seen, handler);
        }
        else if (typeof value === 'string' || typeof value === 'number') {
            handler(name, value.toString());
        }
        else if (typeof value === 'boolean') {
            handler(name, (value) ? '1' : '0');
        }
        else {
            throw new Error(`Can't handle extra config type: ${typeof value}`);
        }
    });
};
exports.iterateExtraOptions = iterateExtraOptions;


/***/ }),

/***/ "./lib/wasm/proxy-wrapper.ts":
/*!***********************************!*\
  !*** ./lib/wasm/proxy-wrapper.ts ***!
  \***********************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var _a;
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.endProfiling = exports.run = exports.releaseSession = exports.createSession = exports.createSessionFinalize = exports.createSessionAllocate = exports.initOrt = exports.initWasm = void 0;
const onnxruntime_common_1 = __webpack_require__(/*! onnxruntime-common */ "../common/dist/lib/index.js");
const core = __importStar(__webpack_require__(/*! ./wasm-core-impl */ "./lib/wasm/wasm-core-impl.ts"));
const wasm_factory_1 = __webpack_require__(/*! ./wasm-factory */ "./lib/wasm/wasm-factory.ts");
const isProxy = () => !!onnxruntime_common_1.env.wasm.proxy && typeof document !== 'undefined';
let proxyWorker;
let initializing = false;
let initialized = false;
let aborted = false;
let initWasmCallbacks;
let initOrtCallbacks;
const createSessionAllocateCallbacks = [];
const createSessionFinalizeCallbacks = [];
const createSessionCallbacks = [];
const releaseSessionCallbacks = [];
const runCallbacks = [];
const endProfilingCallbacks = [];
const ensureWorker = () => {
    if (initializing || !initialized || aborted || !proxyWorker) {
        throw new Error('worker not ready');
    }
};
const onProxyWorkerMessage = (ev) => {
    switch (ev.data.type) {
        case 'init-wasm':
            initializing = false;
            if (ev.data.err) {
                aborted = true;
                initWasmCallbacks[1](ev.data.err);
            }
            else {
                initialized = true;
                initWasmCallbacks[0]();
            }
            break;
        case 'init-ort':
            if (ev.data.err) {
                initOrtCallbacks[1](ev.data.err);
            }
            else {
                initOrtCallbacks[0]();
            }
            break;
        case 'create_allocate':
            if (ev.data.err) {
                createSessionAllocateCallbacks.shift()[1](ev.data.err);
            }
            else {
                createSessionAllocateCallbacks.shift()[0](ev.data.out);
            }
            break;
        case 'create_finalize':
            if (ev.data.err) {
                createSessionFinalizeCallbacks.shift()[1](ev.data.err);
            }
            else {
                createSessionFinalizeCallbacks.shift()[0](ev.data.out);
            }
            break;
        case 'create':
            if (ev.data.err) {
                createSessionCallbacks.shift()[1](ev.data.err);
            }
            else {
                createSessionCallbacks.shift()[0](ev.data.out);
            }
            break;
        case 'release':
            if (ev.data.err) {
                releaseSessionCallbacks.shift()[1](ev.data.err);
            }
            else {
                releaseSessionCallbacks.shift()[0]();
            }
            break;
        case 'run':
            if (ev.data.err) {
                runCallbacks.shift()[1](ev.data.err);
            }
            else {
                runCallbacks.shift()[0](ev.data.out);
            }
            break;
        case 'end-profiling':
            if (ev.data.err) {
                endProfilingCallbacks.shift()[1](ev.data.err);
            }
            else {
                endProfilingCallbacks.shift()[0]();
            }
            break;
        default:
    }
};
const scriptSrc = typeof document !== 'undefined' ? (_a = document === null || document === void 0 ? void 0 : document.currentScript) === null || _a === void 0 ? void 0 : _a.src : undefined;
const initWasm = async () => {
    if ( true && isProxy()) {
        if (initialized) {
            return;
        }
        if (initializing) {
            throw new Error('multiple calls to \'initWasm()\' detected.');
        }
        if (aborted) {
            throw new Error('previous call to \'initWasm()\' failed.');
        }
        initializing = true;
        // overwrite wasm filepaths
        if (onnxruntime_common_1.env.wasm.wasmPaths === undefined) {
            if (scriptSrc && scriptSrc.indexOf('blob:') !== 0) {
                onnxruntime_common_1.env.wasm.wasmPaths = scriptSrc.substr(0, +(scriptSrc).lastIndexOf('/') + 1);
            }
        }
        return new Promise((resolve, reject) => {
            proxyWorker === null || proxyWorker === void 0 ? void 0 : proxyWorker.terminate();
            // eslint-disable-next-line @typescript-eslint/no-var-requires, @typescript-eslint/no-require-imports
            proxyWorker = (__webpack_require__(/*! worker-loader?inline=no-fallback!./proxy-worker/main */ "./node_modules/worker-loader/dist/cjs.js?inline=no-fallback!./lib/wasm/proxy-worker/main.ts")["default"])();
            proxyWorker.onmessage = onProxyWorkerMessage;
            initWasmCallbacks = [resolve, reject];
            const message = { type: 'init-wasm', in: onnxruntime_common_1.env.wasm };
            proxyWorker.postMessage(message);
        });
    }
    else {
        return (0, wasm_factory_1.initializeWebAssembly)(onnxruntime_common_1.env.wasm);
    }
};
exports.initWasm = initWasm;
const initOrt = async (numThreads, loggingLevel) => {
    if ( true && isProxy()) {
        ensureWorker();
        return new Promise((resolve, reject) => {
            initOrtCallbacks = [resolve, reject];
            const message = { type: 'init-ort', in: { numThreads, loggingLevel } };
            proxyWorker.postMessage(message);
        });
    }
    else {
        core.initOrt(numThreads, loggingLevel);
    }
};
exports.initOrt = initOrt;
const createSessionAllocate = async (model) => {
    if ( true && isProxy()) {
        ensureWorker();
        return new Promise((resolve, reject) => {
            createSessionAllocateCallbacks.push([resolve, reject]);
            const message = { type: 'create_allocate', in: { model } };
            proxyWorker.postMessage(message, [model.buffer]);
        });
    }
    else {
        return core.createSessionAllocate(model);
    }
};
exports.createSessionAllocate = createSessionAllocate;
const createSessionFinalize = async (modeldata, options) => {
    if ( true && isProxy()) {
        ensureWorker();
        return new Promise((resolve, reject) => {
            createSessionFinalizeCallbacks.push([resolve, reject]);
            const message = { type: 'create_finalize', in: { modeldata, options } };
            proxyWorker.postMessage(message);
        });
    }
    else {
        return core.createSessionFinalize(modeldata, options);
    }
};
exports.createSessionFinalize = createSessionFinalize;
const createSession = async (model, options) => {
    if ( true && isProxy()) {
        ensureWorker();
        return new Promise((resolve, reject) => {
            createSessionCallbacks.push([resolve, reject]);
            const message = { type: 'create', in: { model, options } };
            proxyWorker.postMessage(message, [model.buffer]);
        });
    }
    else {
        return core.createSession(model, options);
    }
};
exports.createSession = createSession;
const releaseSession = async (sessionId) => {
    if ( true && isProxy()) {
        ensureWorker();
        return new Promise((resolve, reject) => {
            releaseSessionCallbacks.push([resolve, reject]);
            const message = { type: 'release', in: sessionId };
            proxyWorker.postMessage(message);
        });
    }
    else {
        core.releaseSession(sessionId);
    }
};
exports.releaseSession = releaseSession;
const run = async (sessionId, inputIndices, inputs, outputIndices, options) => {
    if ( true && isProxy()) {
        ensureWorker();
        return new Promise((resolve, reject) => {
            runCallbacks.push([resolve, reject]);
            const message = { type: 'run', in: { sessionId, inputIndices, inputs, outputIndices, options } };
            proxyWorker.postMessage(message, core.extractTransferableBuffers(inputs));
        });
    }
    else {
        return core.run(sessionId, inputIndices, inputs, outputIndices, options);
    }
};
exports.run = run;
const endProfiling = async (sessionId) => {
    if ( true && isProxy()) {
        ensureWorker();
        return new Promise((resolve, reject) => {
            endProfilingCallbacks.push([resolve, reject]);
            const message = { type: 'end-profiling', in: sessionId };
            proxyWorker.postMessage(message);
        });
    }
    else {
        core.endProfiling(sessionId);
    }
};
exports.endProfiling = endProfiling;


/***/ }),

/***/ "./lib/wasm/run-options.ts":
/*!*********************************!*\
  !*** ./lib/wasm/run-options.ts ***!
  \*********************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.setRunOptions = void 0;
const options_utils_1 = __webpack_require__(/*! ./options-utils */ "./lib/wasm/options-utils.ts");
const string_utils_1 = __webpack_require__(/*! ./string-utils */ "./lib/wasm/string-utils.ts");
const wasm_factory_1 = __webpack_require__(/*! ./wasm-factory */ "./lib/wasm/wasm-factory.ts");
const setRunOptions = (options) => {
    const wasm = (0, wasm_factory_1.getInstance)();
    let runOptionsHandle = 0;
    const allocs = [];
    const runOptions = options || {};
    try {
        if ((options === null || options === void 0 ? void 0 : options.logSeverityLevel) === undefined) {
            runOptions.logSeverityLevel = 2; // Default to warning
        }
        else if (typeof options.logSeverityLevel !== 'number' || !Number.isInteger(options.logSeverityLevel) ||
            options.logSeverityLevel < 0 || options.logSeverityLevel > 4) {
            throw new Error(`log serverity level is not valid: ${options.logSeverityLevel}`);
        }
        if ((options === null || options === void 0 ? void 0 : options.logVerbosityLevel) === undefined) {
            runOptions.logVerbosityLevel = 0; // Default to 0
        }
        else if (typeof options.logVerbosityLevel !== 'number' || !Number.isInteger(options.logVerbosityLevel)) {
            throw new Error(`log verbosity level is not valid: ${options.logVerbosityLevel}`);
        }
        if ((options === null || options === void 0 ? void 0 : options.terminate) === undefined) {
            runOptions.terminate = false;
        }
        let tagDataOffset = 0;
        if ((options === null || options === void 0 ? void 0 : options.tag) !== undefined) {
            tagDataOffset = (0, string_utils_1.allocWasmString)(options.tag, allocs);
        }
        runOptionsHandle = wasm._OrtCreateRunOptions(runOptions.logSeverityLevel, runOptions.logVerbosityLevel, !!runOptions.terminate, tagDataOffset);
        if (runOptionsHandle === 0) {
            throw new Error('Can\'t create run options');
        }
        if ((options === null || options === void 0 ? void 0 : options.extra) !== undefined) {
            (0, options_utils_1.iterateExtraOptions)(options.extra, '', new WeakSet(), (key, value) => {
                const keyDataOffset = (0, string_utils_1.allocWasmString)(key, allocs);
                const valueDataOffset = (0, string_utils_1.allocWasmString)(value, allocs);
                if (wasm._OrtAddRunConfigEntry(runOptionsHandle, keyDataOffset, valueDataOffset) !== 0) {
                    throw new Error(`Can't set a run config entry: ${key} - ${value}`);
                }
            });
        }
        return [runOptionsHandle, allocs];
    }
    catch (e) {
        if (runOptionsHandle !== 0) {
            wasm._OrtReleaseRunOptions(runOptionsHandle);
        }
        allocs.forEach(wasm._free);
        throw e;
    }
};
exports.setRunOptions = setRunOptions;


/***/ }),

/***/ "./lib/wasm/session-handler.ts":
/*!*************************************!*\
  !*** ./lib/wasm/session-handler.ts ***!
  \*************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.OnnxruntimeWebAssemblySessionHandler = void 0;
const fs_1 = __webpack_require__(/*! fs */ "?295d");
const onnxruntime_common_1 = __webpack_require__(/*! onnxruntime-common */ "../common/dist/lib/index.js");
const util_1 = __webpack_require__(/*! util */ "?cf98");
const proxy_wrapper_1 = __webpack_require__(/*! ./proxy-wrapper */ "./lib/wasm/proxy-wrapper.ts");
let ortInit;
const getLogLevel = (logLevel) => {
    switch (logLevel) {
        case 'verbose':
            return 0;
        case 'info':
            return 1;
        case 'warning':
            return 2;
        case 'error':
            return 3;
        case 'fatal':
            return 4;
        default:
            throw new Error(`unsupported logging level: ${logLevel}`);
    }
};
class OnnxruntimeWebAssemblySessionHandler {
    async createSessionAllocate(path) {
        // fetch model from url and move to wasm heap. The arraybufffer that held the http
        // response is freed once we return
        const response = await fetch(path);
        const arrayBuffer = await response.arrayBuffer();
        return (0, proxy_wrapper_1.createSessionAllocate)(new Uint8Array(arrayBuffer));
    }
    async loadModel(pathOrBuffer, options) {
        if (!ortInit) {
            await (0, proxy_wrapper_1.initOrt)(onnxruntime_common_1.env.wasm.numThreads, getLogLevel(onnxruntime_common_1.env.logLevel));
            ortInit = true;
        }
        if (typeof pathOrBuffer === 'string') {
            if (typeof fetch === 'undefined') {
                // node
                const model = await (0, util_1.promisify)(fs_1.readFile)(pathOrBuffer);
                [this.sessionId, this.inputNames, this.outputNames] = await (0, proxy_wrapper_1.createSession)(model, options);
            }
            else {
                // browser
                // fetch model and move to wasm heap.
                const modelData = await this.createSessionAllocate(pathOrBuffer);
                // create the session
                [this.sessionId, this.inputNames, this.outputNames] = await (0, proxy_wrapper_1.createSessionFinalize)(modelData, options);
            }
        }
        else {
            [this.sessionId, this.inputNames, this.outputNames] = await (0, proxy_wrapper_1.createSession)(pathOrBuffer, options);
        }
    }
    async dispose() {
        return (0, proxy_wrapper_1.releaseSession)(this.sessionId);
    }
    async run(feeds, fetches, options) {
        const inputArray = [];
        const inputIndices = [];
        Object.entries(feeds).forEach(kvp => {
            const name = kvp[0];
            const tensor = kvp[1];
            const index = this.inputNames.indexOf(name);
            if (index === -1) {
                throw new Error(`invalid input '${name}'`);
            }
            inputArray.push(tensor);
            inputIndices.push(index);
        });
        const outputIndices = [];
        Object.entries(fetches).forEach(kvp => {
            const name = kvp[0];
            // TODO: support pre-allocated output
            const index = this.outputNames.indexOf(name);
            if (index === -1) {
                throw new Error(`invalid output '${name}'`);
            }
            outputIndices.push(index);
        });
        const outputs = await (0, proxy_wrapper_1.run)(this.sessionId, inputIndices, inputArray.map(t => [t.type, t.dims, t.data]), outputIndices, options);
        const result = {};
        for (let i = 0; i < outputs.length; i++) {
            result[this.outputNames[outputIndices[i]]] = new onnxruntime_common_1.Tensor(outputs[i][0], outputs[i][2], outputs[i][1]);
        }
        return result;
    }
    startProfiling() {
        // TODO: implement profiling
    }
    endProfiling() {
        void (0, proxy_wrapper_1.endProfiling)(this.sessionId);
    }
}
exports.OnnxruntimeWebAssemblySessionHandler = OnnxruntimeWebAssemblySessionHandler;


/***/ }),

/***/ "./lib/wasm/session-options.ts":
/*!*************************************!*\
  !*** ./lib/wasm/session-options.ts ***!
  \*************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.setSessionOptions = void 0;
const options_utils_1 = __webpack_require__(/*! ./options-utils */ "./lib/wasm/options-utils.ts");
const string_utils_1 = __webpack_require__(/*! ./string-utils */ "./lib/wasm/string-utils.ts");
const wasm_factory_1 = __webpack_require__(/*! ./wasm-factory */ "./lib/wasm/wasm-factory.ts");
const getGraphOptimzationLevel = (graphOptimizationLevel) => {
    switch (graphOptimizationLevel) {
        case 'disabled':
            return 0;
        case 'basic':
            return 1;
        case 'extended':
            return 2;
        case 'all':
            return 99;
        default:
            throw new Error(`unsupported graph optimization level: ${graphOptimizationLevel}`);
    }
};
const getExecutionMode = (executionMode) => {
    switch (executionMode) {
        case 'sequential':
            return 0;
        case 'parallel':
            return 1;
        default:
            throw new Error(`unsupported execution mode: ${executionMode}`);
    }
};
const appendDefaultOptions = (options) => {
    if (!options.extra) {
        options.extra = {};
    }
    if (!options.extra.session) {
        options.extra.session = {};
    }
    const session = options.extra.session;
    if (!session.use_ort_model_bytes_directly) {
        // eslint-disable-next-line camelcase
        session.use_ort_model_bytes_directly = '1';
    }
};
const setExecutionProviders = (sessionOptionsHandle, executionProviders, allocs) => {
    for (const ep of executionProviders) {
        let epName = typeof ep === 'string' ? ep : ep.name;
        // check EP name
        switch (epName) {
            case 'xnnpack':
                epName = 'XNNPACK';
                break;
            case 'wasm':
            case 'cpu':
                continue;
            default:
                throw new Error(`not supported EP: ${epName}`);
        }
        const epNameDataOffset = (0, string_utils_1.allocWasmString)(epName, allocs);
        if ((0, wasm_factory_1.getInstance)()._OrtAppendExecutionProvider(sessionOptionsHandle, epNameDataOffset) !== 0) {
            throw new Error(`Can't append execution provider: ${epName}`);
        }
    }
};
const setSessionOptions = (options) => {
    const wasm = (0, wasm_factory_1.getInstance)();
    let sessionOptionsHandle = 0;
    const allocs = [];
    const sessionOptions = options || {};
    appendDefaultOptions(sessionOptions);
    try {
        if ((options === null || options === void 0 ? void 0 : options.graphOptimizationLevel) === undefined) {
            sessionOptions.graphOptimizationLevel = 'all';
        }
        const graphOptimizationLevel = getGraphOptimzationLevel(sessionOptions.graphOptimizationLevel);
        if ((options === null || options === void 0 ? void 0 : options.enableCpuMemArena) === undefined) {
            sessionOptions.enableCpuMemArena = true;
        }
        if ((options === null || options === void 0 ? void 0 : options.enableMemPattern) === undefined) {
            sessionOptions.enableMemPattern = true;
        }
        if ((options === null || options === void 0 ? void 0 : options.executionMode) === undefined) {
            sessionOptions.executionMode = 'sequential';
        }
        const executionMode = getExecutionMode(sessionOptions.executionMode);
        let logIdDataOffset = 0;
        if ((options === null || options === void 0 ? void 0 : options.logId) !== undefined) {
            logIdDataOffset = (0, string_utils_1.allocWasmString)(options.logId, allocs);
        }
        if ((options === null || options === void 0 ? void 0 : options.logSeverityLevel) === undefined) {
            sessionOptions.logSeverityLevel = 2; // Default to warning
        }
        else if (typeof options.logSeverityLevel !== 'number' || !Number.isInteger(options.logSeverityLevel) ||
            options.logSeverityLevel < 0 || options.logSeverityLevel > 4) {
            throw new Error(`log serverity level is not valid: ${options.logSeverityLevel}`);
        }
        if ((options === null || options === void 0 ? void 0 : options.logVerbosityLevel) === undefined) {
            sessionOptions.logVerbosityLevel = 0; // Default to 0
        }
        else if (typeof options.logVerbosityLevel !== 'number' || !Number.isInteger(options.logVerbosityLevel)) {
            throw new Error(`log verbosity level is not valid: ${options.logVerbosityLevel}`);
        }
        if ((options === null || options === void 0 ? void 0 : options.enableProfiling) === undefined) {
            sessionOptions.enableProfiling = false;
        }
        sessionOptionsHandle = wasm._OrtCreateSessionOptions(graphOptimizationLevel, !!sessionOptions.enableCpuMemArena, !!sessionOptions.enableMemPattern, executionMode, !!sessionOptions.enableProfiling, 0, logIdDataOffset, sessionOptions.logSeverityLevel, sessionOptions.logVerbosityLevel);
        if (sessionOptionsHandle === 0) {
            throw new Error('Can\'t create session options');
        }
        if (options === null || options === void 0 ? void 0 : options.executionProviders) {
            setExecutionProviders(sessionOptionsHandle, options.executionProviders, allocs);
        }
        if ((options === null || options === void 0 ? void 0 : options.extra) !== undefined) {
            (0, options_utils_1.iterateExtraOptions)(options.extra, '', new WeakSet(), (key, value) => {
                const keyDataOffset = (0, string_utils_1.allocWasmString)(key, allocs);
                const valueDataOffset = (0, string_utils_1.allocWasmString)(value, allocs);
                if (wasm._OrtAddSessionConfigEntry(sessionOptionsHandle, keyDataOffset, valueDataOffset) !== 0) {
                    throw new Error(`Can't set a session config entry: ${key} - ${value}`);
                }
            });
        }
        return [sessionOptionsHandle, allocs];
    }
    catch (e) {
        if (sessionOptionsHandle !== 0) {
            wasm._OrtReleaseSessionOptions(sessionOptionsHandle);
        }
        allocs.forEach(wasm._free);
        throw e;
    }
};
exports.setSessionOptions = setSessionOptions;


/***/ }),

/***/ "./lib/wasm/string-utils.ts":
/*!**********************************!*\
  !*** ./lib/wasm/string-utils.ts ***!
  \**********************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.allocWasmString = void 0;
const wasm_factory_1 = __webpack_require__(/*! ./wasm-factory */ "./lib/wasm/wasm-factory.ts");
const allocWasmString = (data, allocs) => {
    const wasm = (0, wasm_factory_1.getInstance)();
    const dataLength = wasm.lengthBytesUTF8(data) + 1;
    const dataOffset = wasm._malloc(dataLength);
    wasm.stringToUTF8(data, dataOffset, dataLength);
    allocs.push(dataOffset);
    return dataOffset;
};
exports.allocWasmString = allocWasmString;


/***/ }),

/***/ "./lib/wasm/wasm-core-impl.ts":
/*!************************************!*\
  !*** ./lib/wasm/wasm-core-impl.ts ***!
  \************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.extractTransferableBuffers = exports.endProfiling = exports.run = exports.releaseSession = exports.createSession = exports.createSessionFinalize = exports.createSessionAllocate = exports.initOrt = void 0;
const run_options_1 = __webpack_require__(/*! ./run-options */ "./lib/wasm/run-options.ts");
const session_options_1 = __webpack_require__(/*! ./session-options */ "./lib/wasm/session-options.ts");
const string_utils_1 = __webpack_require__(/*! ./string-utils */ "./lib/wasm/string-utils.ts");
const wasm_factory_1 = __webpack_require__(/*! ./wasm-factory */ "./lib/wasm/wasm-factory.ts");
/**
 * initialize ORT environment.
 * @param numThreads SetGlobalIntraOpNumThreads(numThreads)
 * @param loggingLevel CreateEnv(static_cast<OrtLoggingLevel>(logging_level))
 */
const initOrt = (numThreads, loggingLevel) => {
    const errorCode = (0, wasm_factory_1.getInstance)()._OrtInit(numThreads, loggingLevel);
    if (errorCode !== 0) {
        throw new Error(`Can't initialize onnxruntime. error code = ${errorCode}`);
    }
};
exports.initOrt = initOrt;
const activeSessions = new Map();
/**
 * create an instance of InferenceSession.
 * @returns the metadata of InferenceSession. 0-value handle for failure.
 */
const createSessionAllocate = (model) => {
    const wasm = (0, wasm_factory_1.getInstance)();
    const modelDataOffset = wasm._malloc(model.byteLength);
    wasm.HEAPU8.set(model, modelDataOffset);
    return [modelDataOffset, model.byteLength];
};
exports.createSessionAllocate = createSessionAllocate;
const createSessionFinalize = (modelData, options) => {
    const wasm = (0, wasm_factory_1.getInstance)();
    let sessionHandle = 0;
    let sessionOptionsHandle = 0;
    let allocs = [];
    try {
        [sessionOptionsHandle, allocs] = (0, session_options_1.setSessionOptions)(options);
        sessionHandle = wasm._OrtCreateSession(modelData[0], modelData[1], sessionOptionsHandle);
        if (sessionHandle === 0) {
            throw new Error('Can\'t create a session');
        }
    }
    finally {
        wasm._free(modelData[0]);
        wasm._OrtReleaseSessionOptions(sessionOptionsHandle);
        allocs.forEach(wasm._free);
    }
    const inputCount = wasm._OrtGetInputCount(sessionHandle);
    const outputCount = wasm._OrtGetOutputCount(sessionHandle);
    const inputNames = [];
    const inputNamesUTF8Encoded = [];
    const outputNames = [];
    const outputNamesUTF8Encoded = [];
    for (let i = 0; i < inputCount; i++) {
        const name = wasm._OrtGetInputName(sessionHandle, i);
        if (name === 0) {
            throw new Error('Can\'t get an input name');
        }
        inputNamesUTF8Encoded.push(name);
        inputNames.push(wasm.UTF8ToString(name));
    }
    for (let i = 0; i < outputCount; i++) {
        const name = wasm._OrtGetOutputName(sessionHandle, i);
        if (name === 0) {
            throw new Error('Can\'t get an output name');
        }
        outputNamesUTF8Encoded.push(name);
        outputNames.push(wasm.UTF8ToString(name));
    }
    activeSessions.set(sessionHandle, [sessionHandle, inputNamesUTF8Encoded, outputNamesUTF8Encoded]);
    return [sessionHandle, inputNames, outputNames];
};
exports.createSessionFinalize = createSessionFinalize;
/**
 * create an instance of InferenceSession.
 * @returns the metadata of InferenceSession. 0-value handle for failure.
 */
const createSession = (model, options) => {
    const modelData = (0, exports.createSessionAllocate)(model);
    return (0, exports.createSessionFinalize)(modelData, options);
};
exports.createSession = createSession;
const releaseSession = (sessionId) => {
    const wasm = (0, wasm_factory_1.getInstance)();
    const session = activeSessions.get(sessionId);
    if (!session) {
        throw new Error('invalid session id');
    }
    const sessionHandle = session[0];
    const inputNamesUTF8Encoded = session[1];
    const outputNamesUTF8Encoded = session[2];
    inputNamesUTF8Encoded.forEach(wasm._OrtFree);
    outputNamesUTF8Encoded.forEach(wasm._OrtFree);
    wasm._OrtReleaseSession(sessionHandle);
    activeSessions.delete(sessionId);
};
exports.releaseSession = releaseSession;
const tensorDataTypeStringToEnum = (type) => {
    switch (type) {
        case 'int8':
            return 3 /* DataType.int8 */;
        case 'uint8':
            return 2 /* DataType.uint8 */;
        case 'bool':
            return 9 /* DataType.bool */;
        case 'int16':
            return 5 /* DataType.int16 */;
        case 'uint16':
            return 4 /* DataType.uint16 */;
        case 'int32':
            return 6 /* DataType.int32 */;
        case 'uint32':
            return 12 /* DataType.uint32 */;
        case 'float32':
            return 1 /* DataType.float */;
        case 'float64':
            return 11 /* DataType.double */;
        case 'string':
            return 8 /* DataType.string */;
        case 'int64':
            return 7 /* DataType.int64 */;
        case 'uint64':
            return 13 /* DataType.uint64 */;
        default:
            throw new Error(`unsupported data type: ${type}`);
    }
};
const tensorDataTypeEnumToString = (typeProto) => {
    switch (typeProto) {
        case 3 /* DataType.int8 */:
            return 'int8';
        case 2 /* DataType.uint8 */:
            return 'uint8';
        case 9 /* DataType.bool */:
            return 'bool';
        case 5 /* DataType.int16 */:
            return 'int16';
        case 4 /* DataType.uint16 */:
            return 'uint16';
        case 6 /* DataType.int32 */:
            return 'int32';
        case 12 /* DataType.uint32 */:
            return 'uint32';
        case 1 /* DataType.float */:
            return 'float32';
        case 11 /* DataType.double */:
            return 'float64';
        case 8 /* DataType.string */:
            return 'string';
        case 7 /* DataType.int64 */:
            return 'int64';
        case 13 /* DataType.uint64 */:
            return 'uint64';
        default:
            throw new Error(`unsupported data type: ${typeProto}`);
    }
};
const numericTensorTypeToTypedArray = (type) => {
    switch (type) {
        case 'float32':
            return Float32Array;
        case 'uint8':
            return Uint8Array;
        case 'int8':
            return Int8Array;
        case 'uint16':
            return Uint16Array;
        case 'int16':
            return Int16Array;
        case 'int32':
            return Int32Array;
        case 'bool':
            return Uint8Array;
        case 'float64':
            return Float64Array;
        case 'uint32':
            return Uint32Array;
        case 'int64':
            return BigInt64Array;
        case 'uint64':
            return BigUint64Array;
        default:
            throw new Error(`unsupported type: ${type}`);
    }
};
/**
 * perform inference run
 */
const run = (sessionId, inputIndices, inputs, outputIndices, options) => {
    const wasm = (0, wasm_factory_1.getInstance)();
    const session = activeSessions.get(sessionId);
    if (!session) {
        throw new Error('invalid session id');
    }
    const sessionHandle = session[0];
    const inputNamesUTF8Encoded = session[1];
    const outputNamesUTF8Encoded = session[2];
    const inputCount = inputIndices.length;
    const outputCount = outputIndices.length;
    let runOptionsHandle = 0;
    let runOptionsAllocs = [];
    const inputValues = [];
    const inputAllocs = [];
    try {
        [runOptionsHandle, runOptionsAllocs] = (0, run_options_1.setRunOptions)(options);
        // create input tensors
        for (let i = 0; i < inputCount; i++) {
            const dataType = inputs[i][0];
            const dims = inputs[i][1];
            const data = inputs[i][2];
            let dataOffset;
            let dataByteLength;
            if (Array.isArray(data)) {
                // string tensor
                dataByteLength = 4 * data.length;
                dataOffset = wasm._malloc(dataByteLength);
                inputAllocs.push(dataOffset);
                let dataIndex = dataOffset / 4;
                for (let i = 0; i < data.length; i++) {
                    if (typeof data[i] !== 'string') {
                        throw new TypeError(`tensor data at index ${i} is not a string`);
                    }
                    wasm.HEAPU32[dataIndex++] = (0, string_utils_1.allocWasmString)(data[i], inputAllocs);
                }
            }
            else {
                dataByteLength = data.byteLength;
                dataOffset = wasm._malloc(dataByteLength);
                inputAllocs.push(dataOffset);
                wasm.HEAPU8.set(new Uint8Array(data.buffer, data.byteOffset, dataByteLength), dataOffset);
            }
            const stack = wasm.stackSave();
            const dimsOffset = wasm.stackAlloc(4 * dims.length);
            try {
                let dimIndex = dimsOffset / 4;
                dims.forEach(d => wasm.HEAP32[dimIndex++] = d);
                const tensor = wasm._OrtCreateTensor(tensorDataTypeStringToEnum(dataType), dataOffset, dataByteLength, dimsOffset, dims.length);
                if (tensor === 0) {
                    throw new Error('Can\'t create a tensor');
                }
                inputValues.push(tensor);
            }
            finally {
                wasm.stackRestore(stack);
            }
        }
        const beforeRunStack = wasm.stackSave();
        const inputValuesOffset = wasm.stackAlloc(inputCount * 4);
        const inputNamesOffset = wasm.stackAlloc(inputCount * 4);
        const outputValuesOffset = wasm.stackAlloc(outputCount * 4);
        const outputNamesOffset = wasm.stackAlloc(outputCount * 4);
        try {
            let inputValuesIndex = inputValuesOffset / 4;
            let inputNamesIndex = inputNamesOffset / 4;
            let outputValuesIndex = outputValuesOffset / 4;
            let outputNamesIndex = outputNamesOffset / 4;
            for (let i = 0; i < inputCount; i++) {
                wasm.HEAPU32[inputValuesIndex++] = inputValues[i];
                wasm.HEAPU32[inputNamesIndex++] = inputNamesUTF8Encoded[inputIndices[i]];
            }
            for (let i = 0; i < outputCount; i++) {
                wasm.HEAPU32[outputValuesIndex++] = 0;
                wasm.HEAPU32[outputNamesIndex++] = outputNamesUTF8Encoded[outputIndices[i]];
            }
            // support RunOptions
            let errorCode = wasm._OrtRun(sessionHandle, inputNamesOffset, inputValuesOffset, inputCount, outputNamesOffset, outputCount, outputValuesOffset, runOptionsHandle);
            const output = [];
            if (errorCode === 0) {
                for (let i = 0; i < outputCount; i++) {
                    const tensor = wasm.HEAPU32[outputValuesOffset / 4 + i];
                    const beforeGetTensorDataStack = wasm.stackSave();
                    // stack allocate 4 pointer value
                    const tensorDataOffset = wasm.stackAlloc(4 * 4);
                    let type, dataOffset = 0;
                    try {
                        errorCode = wasm._OrtGetTensorData(tensor, tensorDataOffset, tensorDataOffset + 4, tensorDataOffset + 8, tensorDataOffset + 12);
                        if (errorCode !== 0) {
                            throw new Error(`Can't access output tensor data. error code = ${errorCode}`);
                        }
                        let tensorDataIndex = tensorDataOffset / 4;
                        const dataType = wasm.HEAPU32[tensorDataIndex++];
                        dataOffset = wasm.HEAPU32[tensorDataIndex++];
                        const dimsOffset = wasm.HEAPU32[tensorDataIndex++];
                        const dimsLength = wasm.HEAPU32[tensorDataIndex++];
                        const dims = [];
                        for (let i = 0; i < dimsLength; i++) {
                            dims.push(wasm.HEAPU32[dimsOffset / 4 + i]);
                        }
                        wasm._OrtFree(dimsOffset);
                        const size = dims.length === 0 ? 1 : dims.reduce((a, b) => a * b);
                        type = tensorDataTypeEnumToString(dataType);
                        if (type === 'string') {
                            const stringData = [];
                            let dataIndex = dataOffset / 4;
                            for (let i = 0; i < size; i++) {
                                const offset = wasm.HEAPU32[dataIndex++];
                                const maxBytesToRead = i === size - 1 ? undefined : wasm.HEAPU32[dataIndex] - offset;
                                stringData.push(wasm.UTF8ToString(offset, maxBytesToRead));
                            }
                            output.push([type, dims, stringData]);
                        }
                        else {
                            const typedArrayConstructor = numericTensorTypeToTypedArray(type);
                            const data = new typedArrayConstructor(size);
                            new Uint8Array(data.buffer, data.byteOffset, data.byteLength)
                                .set(wasm.HEAPU8.subarray(dataOffset, dataOffset + data.byteLength));
                            output.push([type, dims, data]);
                        }
                    }
                    finally {
                        wasm.stackRestore(beforeGetTensorDataStack);
                        if (type === 'string' && dataOffset) {
                            wasm._free(dataOffset);
                        }
                        wasm._OrtReleaseTensor(tensor);
                    }
                }
            }
            if (errorCode === 0) {
                return output;
            }
            else {
                throw new Error(`failed to call OrtRun(). error code = ${errorCode}.`);
            }
        }
        finally {
            wasm.stackRestore(beforeRunStack);
        }
    }
    finally {
        inputValues.forEach(wasm._OrtReleaseTensor);
        inputAllocs.forEach(wasm._free);
        wasm._OrtReleaseRunOptions(runOptionsHandle);
        runOptionsAllocs.forEach(wasm._free);
    }
};
exports.run = run;
/**
 * end profiling
 */
const endProfiling = (sessionId) => {
    const wasm = (0, wasm_factory_1.getInstance)();
    const session = activeSessions.get(sessionId);
    if (!session) {
        throw new Error('invalid session id');
    }
    const sessionHandle = session[0];
    // profile file name is not used yet, but it must be freed.
    const profileFileName = wasm._OrtEndProfiling(sessionHandle);
    if (profileFileName === 0) {
        throw new Error('Can\'t get an profile file name');
    }
    wasm._OrtFree(profileFileName);
};
exports.endProfiling = endProfiling;
const extractTransferableBuffers = (tensors) => {
    const buffers = [];
    for (const tensor of tensors) {
        const data = tensor[2];
        if (!Array.isArray(data) && data.buffer) {
            buffers.push(data.buffer);
        }
    }
    return buffers;
};
exports.extractTransferableBuffers = extractTransferableBuffers;


/***/ }),

/***/ "./lib/wasm/wasm-factory.ts":
/*!**********************************!*\
  !*** ./lib/wasm/wasm-factory.ts ***!
  \**********************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";
var __dirname = "/";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.dispose = exports.getInstance = exports.initializeWebAssembly = void 0;
const path = __importStar(__webpack_require__(/*! path */ "?7aa5"));
const ort_wasm_js_1 = __importDefault(__webpack_require__(/*! ./binding/ort-wasm.js */ "./lib/wasm/binding/ort-wasm.js"));
const ortWasmFactoryThreaded = 
// eslint-disable-next-line @typescript-eslint/no-require-imports
 true ? __webpack_require__(/*! ./binding/ort-wasm-threaded.js */ "./lib/wasm/binding/ort-wasm-threaded.js") : 0;
let wasm;
let initialized = false;
let initializing = false;
let aborted = false;
const isMultiThreadSupported = () => {
    try {
        // If 'SharedArrayBuffer' is not available, WebAssembly threads will not work.
        if (typeof SharedArrayBuffer === 'undefined') {
            return false;
        }
        // Test for transferability of SABs (for browsers. needed for Firefox)
        // https://groups.google.com/forum/#!msg/mozilla.dev.platform/IHkBZlHETpA/dwsMNchWEQAJ
        if (typeof MessageChannel !== 'undefined') {
            new MessageChannel().port1.postMessage(new SharedArrayBuffer(1));
        }
        // Test for WebAssembly threads capability (for both browsers and Node.js)
        // This typed array is a WebAssembly program containing threaded instructions.
        return WebAssembly.validate(new Uint8Array([
            0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 5,
            4, 1, 3, 1, 1, 10, 11, 1, 9, 0, 65, 0, 254, 16, 2, 0, 26, 11
        ]));
    }
    catch (e) {
        return false;
    }
};
const isSimdSupported = () => {
    try {
        // Test for WebAssembly SIMD capability (for both browsers and Node.js)
        // This typed array is a WebAssembly program containing SIMD instructions.
        // The binary data is generated from the following code by wat2wasm:
        //
        // (module
        //   (type $t0 (func))
        //   (func $f0 (type $t0)
        //     (drop
        //       (i32x4.dot_i16x8_s
        //         (i8x16.splat
        //           (i32.const 0))
        //         (v128.const i32x4 0x00000000 0x00000000 0x00000000 0x00000000)))))
        return WebAssembly.validate(new Uint8Array([
            0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 10, 30, 1, 28, 0, 65, 0,
            253, 15, 253, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 253, 186, 1, 26, 11
        ]));
    }
    catch (e) {
        return false;
    }
};
const getWasmFileName = (useSimd, useThreads) => {
    if (useThreads) {
        return useSimd ? 'ort-wasm-simd-threaded.wasm' : 'ort-wasm-threaded.wasm';
    }
    else {
        return useSimd ? 'ort-wasm-simd.wasm' : 'ort-wasm.wasm';
    }
};
const initializeWebAssembly = async (flags) => {
    if (initialized) {
        return Promise.resolve();
    }
    if (initializing) {
        throw new Error('multiple calls to \'initializeWebAssembly()\' detected.');
    }
    if (aborted) {
        throw new Error('previous call to \'initializeWebAssembly()\' failed.');
    }
    initializing = true;
    // wasm flags are already initialized
    const timeout = flags.initTimeout;
    const numThreads = flags.numThreads;
    const simd = flags.simd;
    const useThreads = numThreads > 1 && isMultiThreadSupported();
    const useSimd = simd && isSimdSupported();
    const wasmPrefixOverride = typeof flags.wasmPaths === 'string' ? flags.wasmPaths : undefined;
    const wasmFileName = getWasmFileName(false, useThreads);
    const wasmOverrideFileName = getWasmFileName(useSimd, useThreads);
    const wasmPathOverride = typeof flags.wasmPaths === 'object' ? flags.wasmPaths[wasmOverrideFileName] : undefined;
    let isTimeout = false;
    const tasks = [];
    // promise for timeout
    if (timeout > 0) {
        tasks.push(new Promise((resolve) => {
            setTimeout(() => {
                isTimeout = true;
                resolve();
            }, timeout);
        }));
    }
    // promise for module initialization
    tasks.push(new Promise((resolve, reject) => {
        const factory = useThreads ? ortWasmFactoryThreaded : ort_wasm_js_1.default;
        const config = {
            locateFile: (fileName, scriptDirectory) => {
                if ( true && useThreads && fileName.endsWith('.worker.js') &&
                    typeof Blob !== 'undefined') {
                    return URL.createObjectURL(new Blob([
                        // This require() function is handled by webpack to load file content of the corresponding .worker.js
                        // eslint-disable-next-line @typescript-eslint/no-require-imports
                        __webpack_require__(/*! ./binding/ort-wasm-threaded.worker.js */ "./lib/wasm/binding/ort-wasm-threaded.worker.js")
                    ], { type: 'text/javascript' }));
                }
                if (fileName === wasmFileName) {
                    const prefix = wasmPrefixOverride !== null && wasmPrefixOverride !== void 0 ? wasmPrefixOverride : scriptDirectory;
                    return wasmPathOverride !== null && wasmPathOverride !== void 0 ? wasmPathOverride : prefix + wasmOverrideFileName;
                }
                return scriptDirectory + fileName;
            }
        };
        if ( true && useThreads) {
            if (typeof Blob === 'undefined') {
                config.mainScriptUrlOrBlob = path.join(__dirname, 'ort-wasm-threaded.js');
            }
            else {
                const scriptSourceCode = `var ortWasmThreaded=(function(){var _scriptDir;return ${factory.toString()}})();`;
                config.mainScriptUrlOrBlob = new Blob([scriptSourceCode], { type: 'text/javascript' });
            }
        }
        factory(config).then(
        // wasm module initialized successfully
        module => {
            initializing = false;
            initialized = true;
            wasm = module;
            resolve();
        }, 
        // wasm module failed to initialize
        (what) => {
            initializing = false;
            aborted = true;
            reject(what);
        });
    }));
    await Promise.race(tasks);
    if (isTimeout) {
        throw new Error(`WebAssembly backend initializing failed due to timeout: ${timeout}ms`);
    }
};
exports.initializeWebAssembly = initializeWebAssembly;
const getInstance = () => {
    if (initialized && wasm) {
        return wasm;
    }
    throw new Error('WebAssembly is not initialized yet.');
};
exports.getInstance = getInstance;
const dispose = () => {
    var _a;
    if (initialized && !initializing && !aborted) {
        initializing = true;
        (_a = wasm.PThread) === null || _a === void 0 ? void 0 : _a.terminateAllThreads();
        wasm = undefined;
        initializing = false;
        initialized = false;
        aborted = true;
    }
};
exports.dispose = dispose;


/***/ }),

/***/ "./node_modules/worker-loader/dist/cjs.js?inline=no-fallback!./lib/wasm/proxy-worker/main.ts":
/*!***************************************************************************************************!*\
  !*** ./node_modules/worker-loader/dist/cjs.js?inline=no-fallback!./lib/wasm/proxy-worker/main.ts ***!
  \***************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ Worker_fn)
/* harmony export */ });
/* harmony import */ var _node_modules_worker_loader_dist_runtime_inline_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! !!../../../node_modules/worker-loader/dist/runtime/inline.js */ "./node_modules/worker-loader/dist/runtime/inline.js");
/* harmony import */ var _node_modules_worker_loader_dist_runtime_inline_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_worker_loader_dist_runtime_inline_js__WEBPACK_IMPORTED_MODULE_0__);



function Worker_fn() {
  return _node_modules_worker_loader_dist_runtime_inline_js__WEBPACK_IMPORTED_MODULE_0___default()("/*!\n* ONNX Runtime Web v1.14.0\n* Copyright (c) Microsoft Corporation. All rights reserved.\n* Licensed under the MIT License.\n*/\n/******/ (() => { // webpackBootstrap\n/******/ \tvar __webpack_modules__ = ({\n\n/***/ \"./lib/wasm/binding/ort-wasm-threaded.js\":\n/*!***********************************************!*\\\n  !*** ./lib/wasm/binding/ort-wasm-threaded.js ***!\n  \\***********************************************/\n/***/ ((module, __unused_webpack_exports, __webpack_require__) => {\n\nvar __filename = \"/index.js\";\nvar __dirname = \"/\";\n\r\nvar ortWasmThreaded = (() => {\r\n  var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined;\r\n  if (true) _scriptDir = _scriptDir || __filename;\r\n  return (\r\nfunction(ortWasmThreaded) {\r\n  ortWasmThreaded = ortWasmThreaded || {};\r\n\r\n\r\nfunction d(){m.buffer!=n&&p(m.buffer);return aa}function q(){m.buffer!=n&&p(m.buffer);return ba}function r(){m.buffer!=n&&p(m.buffer);return ca}function v(){m.buffer!=n&&p(m.buffer);return da}function ea(){m.buffer!=n&&p(m.buffer);return fa}var x;x||(x=typeof ortWasmThreaded !== 'undefined' ? ortWasmThreaded : {});var ha,ia;x.ready=new Promise(function(a,b){ha=a;ia=b});\r\nvar ja=Object.assign({},x),ka=\"./this.program\",la=(a,b)=>{throw b;},ma=\"object\"==typeof window,y=\"function\"==typeof importScripts,B=\"object\"==typeof process&&\"object\"==typeof process.versions&&\"string\"==typeof process.versions.node,C=x.ENVIRONMENT_IS_PTHREAD||!1,D=\"\";function na(a){return x.locateFile?x.locateFile(a,D):D+a}var oa,pa,qa,fs,ra,sa;\r\nif(B){D=y?(__webpack_require__(/*! path */ \"?75c6\").dirname)(D)+\"/\":__dirname+\"/\";sa=()=>{ra||(fs=__webpack_require__(/*! fs */ \"?63c8\"),ra=__webpack_require__(/*! path */ \"?75c6\"))};oa=function(b,c){sa();b=ra.normalize(b);return fs.readFileSync(b,c?void 0:\"utf8\")};qa=b=>{b=oa(b,!0);b.buffer||(b=new Uint8Array(b));return b};pa=(b,c,e)=>{sa();b=ra.normalize(b);fs.readFile(b,function(f,h){f?e(f):c(h.buffer)})};1<process.argv.length&&(ka=process.argv[1].replace(/\\\\/g,\"/\"));process.argv.slice(2);process.on(\"uncaughtException\",function(b){if(!(b instanceof E))throw b;});process.on(\"unhandledRejection\",\r\nfunction(b){throw b;});la=(b,c)=>{if(F())throw process.exitCode=b,c;c instanceof E||G(\"exiting due to exception: \"+c);process.exit(b)};x.inspect=function(){return\"[Emscripten Module object]\"};let a;try{a=__webpack_require__(/*! worker_threads */ \"?c6f7\")}catch(b){throw console.error('The \"worker_threads\" module is not supported in this node.js build - perhaps a newer version is needed?'),b;}__webpack_require__.g.Worker=a.Worker}else if(ma||y)y?D=self.location.href:\"undefined\"!=typeof document&&document.currentScript&&(D=document.currentScript.src),\r\n_scriptDir&&(D=_scriptDir),0!==D.indexOf(\"blob:\")?D=D.substr(0,D.replace(/[?#].*/,\"\").lastIndexOf(\"/\")+1):D=\"\",B||(oa=a=>{var b=new XMLHttpRequest;b.open(\"GET\",a,!1);b.send(null);return b.responseText},y&&(qa=a=>{var b=new XMLHttpRequest;b.open(\"GET\",a,!1);b.responseType=\"arraybuffer\";b.send(null);return new Uint8Array(b.response)}),pa=(a,b,c)=>{var e=new XMLHttpRequest;e.open(\"GET\",a,!0);e.responseType=\"arraybuffer\";e.onload=()=>{200==e.status||0==e.status&&e.response?b(e.response):c()};e.onerror=\r\nc;e.send(null)});B&&\"undefined\"==typeof performance&&(__webpack_require__.g.performance=(__webpack_require__(/*! perf_hooks */ \"?674f\").performance));var ta=console.log.bind(console),ua=console.warn.bind(console);B&&(sa(),ta=a=>fs.writeSync(1,a+\"\\n\"),ua=a=>fs.writeSync(2,a+\"\\n\"));var va=x.print||ta,G=x.printErr||ua;Object.assign(x,ja);ja=null;x.thisProgram&&(ka=x.thisProgram);x.quit&&(la=x.quit);var H;x.wasmBinary&&(H=x.wasmBinary);var noExitRuntime=x.noExitRuntime||!1;\"object\"!=typeof WebAssembly&&I(\"no native wasm support detected\");\r\nvar m,wa,xa=!1,ya=\"undefined\"!=typeof TextDecoder?new TextDecoder(\"utf8\"):void 0;\r\nfunction za(a,b,c){b>>>=0;var e=b+c;for(c=b;a[c]&&!(c>=e);)++c;if(16<c-b&&a.buffer&&ya)return ya.decode(a.buffer instanceof SharedArrayBuffer?a.slice(b,c):a.subarray(b,c));for(e=\"\";b<c;){var f=a[b++];if(f&128){var h=a[b++]&63;if(192==(f&224))e+=String.fromCharCode((f&31)<<6|h);else{var k=a[b++]&63;f=224==(f&240)?(f&15)<<12|h<<6|k:(f&7)<<18|h<<12|k<<6|a[b++]&63;65536>f?e+=String.fromCharCode(f):(f-=65536,e+=String.fromCharCode(55296|f>>10,56320|f&1023))}}else e+=String.fromCharCode(f)}return e}\r\nfunction Aa(a,b){return(a>>>=0)?za(q(),a,b):\"\"}\r\nfunction Ba(a,b,c,e){c>>>=0;if(!(0<e))return 0;var f=c;e=c+e-1;for(var h=0;h<a.length;++h){var k=a.charCodeAt(h);if(55296<=k&&57343>=k){var l=a.charCodeAt(++h);k=65536+((k&1023)<<10)|l&1023}if(127>=k){if(c>=e)break;b[c++>>>0]=k}else{if(2047>=k){if(c+1>=e)break;b[c++>>>0]=192|k>>6}else{if(65535>=k){if(c+2>=e)break;b[c++>>>0]=224|k>>12}else{if(c+3>=e)break;b[c++>>>0]=240|k>>18;b[c++>>>0]=128|k>>12&63}b[c++>>>0]=128|k>>6&63}b[c++>>>0]=128|k&63}}b[c>>>0]=0;return c-f}\r\nfunction Ca(a){for(var b=0,c=0;c<a.length;++c){var e=a.charCodeAt(c);127>=e?b++:2047>=e?b+=2:55296<=e&&57343>=e?(b+=4,++c):b+=3}return b}var n,aa,ba,ca,da,fa;C&&(n=x.buffer);function p(a){n=a;x.HEAP8=aa=new Int8Array(a);x.HEAP16=new Int16Array(a);x.HEAP32=ca=new Int32Array(a);x.HEAPU8=ba=new Uint8Array(a);x.HEAPU16=new Uint16Array(a);x.HEAPU32=da=new Uint32Array(a);x.HEAPF32=new Float32Array(a);x.HEAPF64=fa=new Float64Array(a)}var Da=x.INITIAL_MEMORY||16777216;\r\nif(C)m=x.wasmMemory,n=x.buffer;else if(x.wasmMemory)m=x.wasmMemory;else if(m=new WebAssembly.Memory({initial:Da/65536,maximum:65536,shared:!0}),!(m.buffer instanceof SharedArrayBuffer))throw G(\"requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag\"),B&&console.log(\"(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)\"),\r\nError(\"bad memory\");m&&(n=m.buffer);Da=n.byteLength;p(n);var Ea,Fa=[],Ga=[],Ha=[],Ia=[],Ja=0;function F(){return noExitRuntime||0<Ja}function Ka(){var a=x.preRun.shift();Fa.unshift(a)}var L=0,La=null,M=null;function I(a){if(C)postMessage({cmd:\"onAbort\",arg:a});else if(x.onAbort)x.onAbort(a);a=\"Aborted(\"+a+\")\";G(a);xa=!0;a=new WebAssembly.RuntimeError(a+\". Build with -sASSERTIONS for more info.\");ia(a);throw a;}function Ma(){return O.startsWith(\"data:application/octet-stream;base64,\")}var O;O=\"ort-wasm-threaded.wasm\";\r\nMa()||(O=na(O));function Na(){var a=O;try{if(a==O&&H)return new Uint8Array(H);if(qa)return qa(a);throw\"both async and sync fetching of the wasm failed\";}catch(b){I(b)}}\r\nfunction Oa(){if(!H&&(ma||y)){if(\"function\"==typeof fetch&&!O.startsWith(\"file://\"))return fetch(O,{credentials:\"same-origin\"}).then(function(a){if(!a.ok)throw\"failed to load wasm binary file at '\"+O+\"'\";return a.arrayBuffer()}).catch(function(){return Na()});if(pa)return new Promise(function(a,b){pa(O,function(c){a(new Uint8Array(c))},b)})}return Promise.resolve().then(function(){return Na()})}var Pa={};\r\nfunction E(a){this.name=\"ExitStatus\";this.message=\"Program terminated with exit(\"+a+\")\";this.status=a}function Qa(a){(a=P.Vb[a])||I();P.mc(a)}function Ra(a){var b=P.Cc();if(!b)return 6;P.ac.push(b);P.Vb[a.Ub]=b;b.Ub=a.Ub;var c={cmd:\"run\",start_routine:a.Ic,arg:a.zc,pthread_ptr:a.Ub};b.$b=()=>{c.time=performance.now();b.postMessage(c,a.Nc)};b.loaded&&(b.$b(),delete b.$b);return 0}function Sa(a){if(C)return Q(1,1,a);if(!F()){P.oc();if(x.onExit)x.onExit(a);xa=!0}la(a,new E(a))}\r\nfunction Ta(a,b){if(!b&&C)throw Ua(a),\"unwind\";F()||C||(Va(),R(Ha),Wa(0),Xa[1].length&&Ya(1,10),Xa[2].length&&Ya(2,10),P.oc());Sa(a)}\r\nvar P={Yb:[],ac:[],qc:[],Vb:{},fc:function(){C&&P.Ec()},Pc:function(){},Ec:function(){P.receiveObjectTransfer=P.Gc;P.threadInitTLS=P.pc;P.setExitStatus=P.nc;noExitRuntime=!1},nc:function(){},oc:function(){for(var a of Object.values(P.Vb))P.mc(a);for(a of P.Yb)a.terminate();P.Yb=[]},mc:function(a){var b=a.Ub;delete P.Vb[b];P.Yb.push(a);P.ac.splice(P.ac.indexOf(a),1);a.Ub=0;Za(b)},Gc:function(){},pc:function(){P.qc.forEach(a=>a())},Fc:function(a,b){a.onmessage=c=>{c=c.data;var e=c.cmd;a.Ub&&(P.Bc=a.Ub);\r\nif(c.targetThread&&c.targetThread!=$a()){var f=P.Vb[c.Qc];f?f.postMessage(c,c.transferList):G('Internal error! Worker sent a message \"'+e+'\" to target pthread '+c.targetThread+\", but that thread no longer exists!\")}else if(\"processProxyingQueue\"===e)ab(c.queue);else if(\"spawnThread\"===e)Ra(c);else if(\"cleanupThread\"===e)Qa(c.thread);else if(\"killThread\"===e)c=c.thread,e=P.Vb[c],delete P.Vb[c],e.terminate(),Za(c),P.ac.splice(P.ac.indexOf(e),1),e.Ub=0;else if(\"cancelThread\"===e)P.Vb[c.thread].postMessage({cmd:\"cancel\"});\r\nelse if(\"loaded\"===e)a.loaded=!0,b&&b(a),a.$b&&(a.$b(),delete a.$b);else if(\"print\"===e)va(\"Thread \"+c.threadId+\": \"+c.text);else if(\"printErr\"===e)G(\"Thread \"+c.threadId+\": \"+c.text);else if(\"alert\"===e)alert(\"Thread \"+c.threadId+\": \"+c.text);else if(\"setimmediate\"===c.target)a.postMessage(c);else if(\"onAbort\"===e){if(x.onAbort)x.onAbort(c.arg)}else e&&G(\"worker sent an unknown command \"+e);P.Bc=void 0};a.onerror=c=>{G(\"worker sent an error! \"+c.filename+\":\"+c.lineno+\": \"+c.message);throw c;};B&&\r\n(a.on(\"message\",function(c){a.onmessage({data:c})}),a.on(\"error\",function(c){a.onerror(c)}),a.on(\"detachedExit\",function(){}));a.postMessage({cmd:\"load\",urlOrBlob:x.mainScriptUrlOrBlob||_scriptDir,wasmMemory:m,wasmModule:wa})},yc:function(){var a=na(\"ort-wasm-threaded.worker.js\");P.Yb.push(new Worker(a))},Cc:function(){0==P.Yb.length&&(P.yc(),P.Fc(P.Yb[0]));return P.Yb.pop()}};x.PThread=P;function R(a){for(;0<a.length;)a.shift()(x)}function bb(a){var b=S();a=a();U(b);return a}\r\nx.establishStackSpace=function(){var a=$a(),b=r()[a+44>>2>>>0];a=r()[a+48>>2>>>0];cb(b,b-a);U(b)};function Ua(a){if(C)return Q(2,0,a);try{Ta(a)}catch(b){b instanceof E||\"unwind\"==b||la(1,b)}}var db=[];function V(a){var b=db[a];b||(a>=db.length&&(db.length=a+1),db[a]=b=Ea.get(a));return b}x.invokeEntryPoint=function(a,b){a=V(a)(b);F()?P.nc(a):eb(a)};function fb(a,b){d().set(a,b>>>0)}var gb=[],hb=0,W=0;\r\nfunction X(a){this.Zb=a;this.Sb=a-24;this.xc=function(b){v()[this.Sb+4>>2>>>0]=b};this.bc=function(){return v()[this.Sb+4>>2>>>0]};this.wc=function(b){v()[this.Sb+8>>2>>>0]=b};this.Dc=function(){return v()[this.Sb+8>>2>>>0]};this.rc=function(){r()[this.Sb>>2>>>0]=0};this.hc=function(b){b=b?1:0;d()[this.Sb+12>>0>>>0]=b};this.uc=function(){return 0!=d()[this.Sb+12>>0>>>0]};this.ic=function(b){b=b?1:0;d()[this.Sb+13>>0>>>0]=b};this.kc=function(){return 0!=d()[this.Sb+13>>0>>>0]};this.fc=function(b,c){this.cc(0);\r\nthis.xc(b);this.wc(c);this.rc();this.hc(!1);this.ic(!1)};this.sc=function(){Atomics.add(r(),this.Sb>>2,1)};this.Hc=function(){return 1===Atomics.sub(r(),this.Sb>>2,1)};this.cc=function(b){v()[this.Sb+16>>2>>>0]=b};this.tc=function(){return v()[this.Sb+16>>2>>>0]};this.vc=function(){if(ib(this.bc()))return v()[this.Zb>>2>>>0];var b=this.tc();return 0!==b?b:this.Zb}}function jb(a){return kb((new X(a)).Sb)}function lb(a,b,c,e){return C?Q(3,1,a,b,c,e):mb(a,b,c,e)}\r\nfunction mb(a,b,c,e){if(\"undefined\"==typeof SharedArrayBuffer)return G(\"Current environment does not support SharedArrayBuffer, pthreads are not available!\"),6;var f=[];if(C&&0===f.length)return lb(a,b,c,e);a={Ic:c,Ub:a,zc:e,Nc:f};return C?(a.Oc=\"spawnThread\",postMessage(a,f),0):Ra(a)}function nb(a,b,c){return C?Q(4,1,a,b,c):0}function ob(a,b){if(C)return Q(5,1,a,b)}function pb(a,b){if(C)return Q(6,1,a,b)}function qb(a,b,c){if(C)return Q(7,1,a,b,c)}function rb(a,b,c){return C?Q(8,1,a,b,c):0}\r\nfunction sb(a,b){if(C)return Q(9,1,a,b)}function tb(a,b,c){if(C)return Q(10,1,a,b,c)}function ub(a,b,c,e){if(C)return Q(11,1,a,b,c,e)}function vb(a,b,c,e){if(C)return Q(12,1,a,b,c,e)}function wb(a,b,c,e){if(C)return Q(13,1,a,b,c,e)}function xb(a){if(C)return Q(14,1,a)}function yb(a,b){if(C)return Q(15,1,a,b)}function zb(a,b,c){if(C)return Q(16,1,a,b,c)}function ab(a){Atomics.store(r(),a>>2,1);$a()&&Ab(a);Atomics.compareExchange(r(),a>>2,1,0)}x.executeNotifiedProxyingQueue=ab;\r\nfunction Bb(a){return v()[a>>>2]+4294967296*r()[a+4>>>2]}function Cb(a,b,c,e,f,h){return C?Q(17,1,a,b,c,e,f,h):-52}function Db(a,b,c,e,f,h){if(C)return Q(18,1,a,b,c,e,f,h)}function Eb(a){var b=Ca(a)+1,c=Fb(b);c&&Ba(a,d(),c,b);return c}\r\nfunction Gb(a,b,c){function e(t){return(t=t.toTimeString().match(/\\(([A-Za-z ]+)\\)$/))?t[1]:\"GMT\"}if(C)return Q(19,1,a,b,c);var f=(new Date).getFullYear(),h=new Date(f,0,1),k=new Date(f,6,1);f=h.getTimezoneOffset();var l=k.getTimezoneOffset(),u=Math.max(f,l);r()[a>>2>>>0]=60*u;r()[b>>2>>>0]=Number(f!=l);a=e(h);b=e(k);a=Eb(a);b=Eb(b);l<f?(v()[c>>2>>>0]=a,v()[c+4>>2>>>0]=b):(v()[c>>2>>>0]=b,v()[c+4>>2>>>0]=a)}function Hb(a,b,c){Hb.Ac||(Hb.Ac=!0,Gb(a,b,c))}var Ib,Jb;\r\nJb=B?()=>{var a=process.hrtime();return 1E3*a[0]+a[1]/1E6}:C?()=>performance.now()-x.__performance_now_clock_drift:()=>performance.now();function Q(a,b){var c=arguments.length-2,e=arguments;return bb(()=>{for(var f=Kb(8*c),h=f>>3,k=0;k<c;k++){var l=e[2+k];ea()[h+k>>>0]=l}return Lb(a,c,f,b)})}var Mb=[],Nb={};\r\nfunction Ob(){if(!Pb){var a={USER:\"web_user\",LOGNAME:\"web_user\",PATH:\"/\",PWD:\"/\",HOME:\"/home/web_user\",LANG:(\"object\"==typeof navigator&&navigator.languages&&navigator.languages[0]||\"C\").replace(\"-\",\"_\")+\".UTF-8\",_:ka||\"./this.program\"},b;for(b in Nb)void 0===Nb[b]?delete a[b]:a[b]=Nb[b];var c=[];for(b in a)c.push(b+\"=\"+a[b]);Pb=c}return Pb}var Pb;\r\nfunction Qb(a,b){if(C)return Q(20,1,a,b);var c=0;Ob().forEach(function(e,f){var h=b+c;f=v()[a+4*f>>2>>>0]=h;for(h=0;h<e.length;++h)d()[f++>>0>>>0]=e.charCodeAt(h);d()[f>>0>>>0]=0;c+=e.length+1});return 0}function Rb(a,b){if(C)return Q(21,1,a,b);var c=Ob();v()[a>>2>>>0]=c.length;var e=0;c.forEach(function(f){e+=f.length+1});v()[b>>2>>>0]=e;return 0}function Sb(a){return C?Q(22,1,a):52}function Tb(a,b,c,e){return C?Q(23,1,a,b,c,e):52}function Ub(a,b,c,e,f){return C?Q(24,1,a,b,c,e,f):70}\r\nvar Xa=[null,[],[]];function Ya(a,b){var c=Xa[a];0===b||10===b?((1===a?va:G)(za(c,0)),c.length=0):c.push(b)}function Vb(a,b,c,e){if(C)return Q(25,1,a,b,c,e);for(var f=0,h=0;h<c;h++){var k=v()[b>>2>>>0],l=v()[b+4>>2>>>0];b+=8;for(var u=0;u<l;u++)Ya(a,q()[k+u>>>0]);f+=l}v()[e>>2>>>0]=f;return 0}var Y=0;\r\nfunction Wb(){if(\"object\"==typeof crypto&&\"function\"==typeof crypto.getRandomValues){var a=new Uint8Array(1);return()=>{crypto.getRandomValues(a);return a[0]}}if(B)try{var b=__webpack_require__(Object(function webpackMissingModule() { var e = new Error(\"Cannot find module 'crypto'\"); e.code = 'MODULE_NOT_FOUND'; throw e; }()));return()=>b.randomBytes(1)[0]}catch(c){}return()=>I(\"randomDevice\")}function Xb(a,b){Xb.lc||(Xb.lc=Wb());for(var c=0;c<b;c++)d()[a+c>>0>>>0]=Xb.lc();return 0}function Yb(a){return 0===a%4&&(0!==a%100||0===a%400)}var Zb=[31,29,31,30,31,30,31,31,30,31,30,31],$b=[31,28,31,30,31,30,31,31,30,31,30,31];\r\nfunction ac(a){var b=Array(Ca(a)+1);Ba(a,b,0,b.length);return b}\r\nfunction bc(a,b,c,e){function f(g,w,z){for(g=\"number\"==typeof g?g.toString():g||\"\";g.length<w;)g=z[0]+g;return g}function h(g,w){return f(g,w,\"0\")}function k(g,w){function z(T){return 0>T?-1:0<T?1:0}var N;0===(N=z(g.getFullYear()-w.getFullYear()))&&0===(N=z(g.getMonth()-w.getMonth()))&&(N=z(g.getDate()-w.getDate()));return N}function l(g){switch(g.getDay()){case 0:return new Date(g.getFullYear()-1,11,29);case 1:return g;case 2:return new Date(g.getFullYear(),0,3);case 3:return new Date(g.getFullYear(),\r\n0,2);case 4:return new Date(g.getFullYear(),0,1);case 5:return new Date(g.getFullYear()-1,11,31);case 6:return new Date(g.getFullYear()-1,11,30)}}function u(g){var w=g.Wb;for(g=new Date((new Date(g.Xb+1900,0,1)).getTime());0<w;){var z=g.getMonth(),N=(Yb(g.getFullYear())?Zb:$b)[z];if(w>N-g.getDate())w-=N-g.getDate()+1,g.setDate(1),11>z?g.setMonth(z+1):(g.setMonth(0),g.setFullYear(g.getFullYear()+1));else{g.setDate(g.getDate()+w);break}}z=new Date(g.getFullYear()+1,0,4);w=l(new Date(g.getFullYear(),\r\n0,4));z=l(z);return 0>=k(w,g)?0>=k(z,g)?g.getFullYear()+1:g.getFullYear():g.getFullYear()-1}var t=r()[e+40>>2>>>0];e={Lc:r()[e>>2>>>0],Kc:r()[e+4>>2>>>0],dc:r()[e+8>>2>>>0],jc:r()[e+12>>2>>>0],ec:r()[e+16>>2>>>0],Xb:r()[e+20>>2>>>0],Tb:r()[e+24>>2>>>0],Wb:r()[e+28>>2>>>0],Rc:r()[e+32>>2>>>0],Jc:r()[e+36>>2>>>0],Mc:t?Aa(t):\"\"};c=Aa(c);t={\"%c\":\"%a %b %d %H:%M:%S %Y\",\"%D\":\"%m/%d/%y\",\"%F\":\"%Y-%m-%d\",\"%h\":\"%b\",\"%r\":\"%I:%M:%S %p\",\"%R\":\"%H:%M\",\"%T\":\"%H:%M:%S\",\"%x\":\"%m/%d/%y\",\"%X\":\"%H:%M:%S\",\"%Ec\":\"%c\",\"%EC\":\"%C\",\r\n\"%Ex\":\"%m/%d/%y\",\"%EX\":\"%H:%M:%S\",\"%Ey\":\"%y\",\"%EY\":\"%Y\",\"%Od\":\"%d\",\"%Oe\":\"%e\",\"%OH\":\"%H\",\"%OI\":\"%I\",\"%Om\":\"%m\",\"%OM\":\"%M\",\"%OS\":\"%S\",\"%Ou\":\"%u\",\"%OU\":\"%U\",\"%OV\":\"%V\",\"%Ow\":\"%w\",\"%OW\":\"%W\",\"%Oy\":\"%y\"};for(var A in t)c=c.replace(new RegExp(A,\"g\"),t[A]);var K=\"Sunday Monday Tuesday Wednesday Thursday Friday Saturday\".split(\" \"),J=\"January February March April May June July August September October November December\".split(\" \");t={\"%a\":function(g){return K[g.Tb].substring(0,3)},\"%A\":function(g){return K[g.Tb]},\r\n\"%b\":function(g){return J[g.ec].substring(0,3)},\"%B\":function(g){return J[g.ec]},\"%C\":function(g){return h((g.Xb+1900)/100|0,2)},\"%d\":function(g){return h(g.jc,2)},\"%e\":function(g){return f(g.jc,2,\" \")},\"%g\":function(g){return u(g).toString().substring(2)},\"%G\":function(g){return u(g)},\"%H\":function(g){return h(g.dc,2)},\"%I\":function(g){g=g.dc;0==g?g=12:12<g&&(g-=12);return h(g,2)},\"%j\":function(g){for(var w=0,z=0;z<=g.ec-1;w+=(Yb(g.Xb+1900)?Zb:$b)[z++]);return h(g.jc+w,3)},\"%m\":function(g){return h(g.ec+\r\n1,2)},\"%M\":function(g){return h(g.Kc,2)},\"%n\":function(){return\"\\n\"},\"%p\":function(g){return 0<=g.dc&&12>g.dc?\"AM\":\"PM\"},\"%S\":function(g){return h(g.Lc,2)},\"%t\":function(){return\"\\t\"},\"%u\":function(g){return g.Tb||7},\"%U\":function(g){return h(Math.floor((g.Wb+7-g.Tb)/7),2)},\"%V\":function(g){var w=Math.floor((g.Wb+7-(g.Tb+6)%7)/7);2>=(g.Tb+371-g.Wb-2)%7&&w++;if(w)53==w&&(z=(g.Tb+371-g.Wb)%7,4==z||3==z&&Yb(g.Xb)||(w=1));else{w=52;var z=(g.Tb+7-g.Wb-1)%7;(4==z||5==z&&Yb(g.Xb%400-1))&&w++}return h(w,\r\n2)},\"%w\":function(g){return g.Tb},\"%W\":function(g){return h(Math.floor((g.Wb+7-(g.Tb+6)%7)/7),2)},\"%y\":function(g){return(g.Xb+1900).toString().substring(2)},\"%Y\":function(g){return g.Xb+1900},\"%z\":function(g){g=g.Jc;var w=0<=g;g=Math.abs(g)/60;return(w?\"+\":\"-\")+String(\"0000\"+(g/60*100+g%60)).slice(-4)},\"%Z\":function(g){return g.Mc},\"%%\":function(){return\"%\"}};c=c.replace(/%%/g,\"\\x00\\x00\");for(A in t)c.includes(A)&&(c=c.replace(new RegExp(A,\"g\"),t[A](e)));c=c.replace(/\\0\\0/g,\"%\");A=ac(c);if(A.length>\r\nb)return 0;fb(A,a);return A.length-1}P.fc();\r\nvar cc=[null,Sa,Ua,lb,nb,ob,pb,qb,rb,sb,tb,ub,vb,wb,xb,yb,zb,Cb,Db,Gb,Qb,Rb,Sb,Tb,Ub,Vb],Pc={b:function(a){return Fb(a+24)+24},n:function(a){a=new X(a);a.uc()||(a.hc(!0),hb--);a.ic(!1);gb.push(a);a.sc();return a.vc()},ma:function(a){G(\"Unexpected exception thrown, this is not properly supported - aborting\");xa=!0;throw a;},x:function(){Z(0);var a=gb.pop();if(a.Hc()&&!a.kc()){var b=a.Dc();b&&V(b)(a.Zb);jb(a.Zb)}W=0},e:function(){var a=W;if(!a)return Y=0;var b=new X(a);b.cc(a);var c=b.bc();if(!c)return Y=\r\n0,a;for(var e=Array.prototype.slice.call(arguments),f=0;f<e.length;f++){var h=e[f];if(0===h||h===c)break;if(dc(h,c,b.Sb+16))return Y=h,a}Y=c;return a},l:function(){var a=W;if(!a)return Y=0;var b=new X(a);b.cc(a);var c=b.bc();if(!c)return Y=0,a;for(var e=Array.prototype.slice.call(arguments),f=0;f<e.length;f++){var h=e[f];if(0===h||h===c)break;if(dc(h,c,b.Sb+16))return Y=h,a}Y=c;return a},h:function(){var a=W;if(!a)return Y=0;var b=new X(a);b.cc(a);var c=b.bc();if(!c)return Y=0,a;for(var e=Array.prototype.slice.call(arguments),\r\nf=0;f<e.length;f++){var h=e[f];if(0===h||h===c)break;if(dc(h,c,b.Sb+16))return Y=h,a}Y=c;return a},t:jb,M:function(){var a=gb.pop();a||I(\"no exception to throw\");var b=a.Zb;a.kc()||(gb.push(a),a.ic(!0),a.hc(!1),hb++);W=b;throw b;},c:function(a,b,c){(new X(a)).fc(b,c);W=a;hb++;throw a;},pa:function(){return hb},Fa:function(a){ec(a,!y,1,!ma);P.pc()},T:function(a){C?postMessage({cmd:\"cleanupThread\",thread:a}):Qa(a)},xa:mb,j:function(a){W||(W=a);throw a;},H:nb,Ma:ob,ua:pb,wa:qb,oa:rb,Ka:sb,Ca:tb,Ja:ub,\r\nV:vb,va:wb,sa:xb,La:yb,ta:zb,Ta:function(){},X:function(){I(\"To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking\")},Ua:function(){I(\"To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking\")},W:function(){return Date.now()},ya:function(){return 2097152},Oa:function(){return!0},za:function(a,b,c,e){if(a==b)setTimeout(()=>ab(e));else if(C)postMessage({targetThread:a,cmd:\"processProxyingQueue\",\r\nqueue:e});else{a=P.Vb[a];if(!a)return;a.postMessage({cmd:\"processProxyingQueue\",queue:e})}return 1},Ea:function(){return-1},Pa:function(a,b){a=new Date(1E3*Bb(a));r()[b>>2>>>0]=a.getUTCSeconds();r()[b+4>>2>>>0]=a.getUTCMinutes();r()[b+8>>2>>>0]=a.getUTCHours();r()[b+12>>2>>>0]=a.getUTCDate();r()[b+16>>2>>>0]=a.getUTCMonth();r()[b+20>>2>>>0]=a.getUTCFullYear()-1900;r()[b+24>>2>>>0]=a.getUTCDay();a=(a.getTime()-Date.UTC(a.getUTCFullYear(),0,1,0,0,0,0))/864E5|0;r()[b+28>>2>>>0]=a},Qa:function(a,b){a=\r\nnew Date(1E3*Bb(a));r()[b>>2>>>0]=a.getSeconds();r()[b+4>>2>>>0]=a.getMinutes();r()[b+8>>2>>>0]=a.getHours();r()[b+12>>2>>>0]=a.getDate();r()[b+16>>2>>>0]=a.getMonth();r()[b+20>>2>>>0]=a.getFullYear()-1900;r()[b+24>>2>>>0]=a.getDay();var c=new Date(a.getFullYear(),0,1),e=(a.getTime()-c.getTime())/864E5|0;r()[b+28>>2>>>0]=e;r()[b+36>>2>>>0]=-(60*a.getTimezoneOffset());e=(new Date(a.getFullYear(),6,1)).getTimezoneOffset();c=c.getTimezoneOffset();a=(e!=c&&a.getTimezoneOffset()==Math.min(c,e))|0;r()[b+\r\n32>>2>>>0]=a},Ra:function(a){var b=new Date(r()[a+20>>2>>>0]+1900,r()[a+16>>2>>>0],r()[a+12>>2>>>0],r()[a+8>>2>>>0],r()[a+4>>2>>>0],r()[a>>2>>>0],0),c=r()[a+32>>2>>>0],e=b.getTimezoneOffset(),f=new Date(b.getFullYear(),0,1),h=(new Date(b.getFullYear(),6,1)).getTimezoneOffset(),k=f.getTimezoneOffset(),l=Math.min(k,h);0>c?r()[a+32>>2>>>0]=Number(h!=k&&l==e):0<c!=(l==e)&&(h=Math.max(k,h),b.setTime(b.getTime()+6E4*((0<c?l:h)-e)));r()[a+24>>2>>>0]=b.getDay();c=(b.getTime()-f.getTime())/864E5|0;r()[a+28>>\r\n2>>>0]=c;r()[a>>2>>>0]=b.getSeconds();r()[a+4>>2>>>0]=b.getMinutes();r()[a+8>>2>>>0]=b.getHours();r()[a+12>>2>>>0]=b.getDate();r()[a+16>>2>>>0]=b.getMonth();return b.getTime()/1E3|0},Aa:Cb,Ba:Db,Sa:Hb,y:function(){I(\"\")},U:function(){if(!B&&!y){var a=\"Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread\";Ib||(Ib={});Ib[a]||(Ib[a]=1,B&&(a=\"warning: \"+a),G(a))}},ra:function(){return 4294901760},B:Jb,Ia:function(a,b,\r\nc){q().copyWithin(a>>>0,b>>>0,b+c>>>0)},F:function(){return B?(__webpack_require__(/*! os */ \"?aedb\").cpus)().length:navigator.hardwareConcurrency},Da:function(a,b,c){Mb.length=b;c>>=3;for(var e=0;e<b;e++)Mb[e]=ea()[c+e>>>0];return(0>a?Pa[-a-1]:cc[a]).apply(null,Mb)},qa:function(a){var b=q().length;a>>>=0;if(a<=b||4294901760<a)return!1;for(var c=1;4>=c;c*=2){var e=b*(1+.2/c);e=Math.min(e,a+100663296);var f=Math;e=Math.max(a,e);f=f.min.call(f,4294901760,e+(65536-e%65536)%65536);a:{try{m.grow(f-n.byteLength+65535>>>16);p(m.buffer);\r\nvar h=1;break a}catch(k){}h=void 0}if(h)return!0}return!1},Na:function(){throw\"unwind\";},Ga:Qb,Ha:Rb,J:Ta,I:Sb,S:Tb,ga:Ub,R:Vb,d:function(){return Y},na:Xb,ia:fc,ja:gc,K:hc,f:ic,P:jc,Q:kc,k:lc,p:mc,q:nc,N:oc,s:pc,w:qc,L:rc,E:sc,aa:tc,_:uc,Z:vc,ca:wc,$:xc,ba:yc,Y:zc,g:Ac,r:Bc,i:Cc,ha:Dc,m:Ec,v:Fc,u:Gc,O:Hc,A:Ic,ka:Jc,C:Kc,D:Lc,fa:Mc,da:Nc,ea:Oc,o:function(a){return a},a:m||x.wasmMemory,G:function(a){Y=a},la:bc,z:function(a,b,c,e){return bc(a,b,c,e)}};\r\n(function(){function a(f,h){x.asm=f.exports;P.qc.push(x.asm.sb);Ea=x.asm.ub;Ga.unshift(x.asm.Va);wa=h;C||(L--,x.monitorRunDependencies&&x.monitorRunDependencies(L),0==L&&(null!==La&&(clearInterval(La),La=null),M&&(f=M,M=null,f())))}function b(f){a(f.instance,f.module)}function c(f){return Oa().then(function(h){return WebAssembly.instantiate(h,e)}).then(function(h){return h}).then(f,function(h){G(\"failed to asynchronously prepare wasm: \"+h);I(h)})}var e={a:Pc};C||(L++,x.monitorRunDependencies&&x.monitorRunDependencies(L));\r\nif(x.instantiateWasm)try{return x.instantiateWasm(e,a)}catch(f){return G(\"Module.instantiateWasm callback failed with error: \"+f),!1}(function(){return H||\"function\"!=typeof WebAssembly.instantiateStreaming||Ma()||O.startsWith(\"file://\")||B||\"function\"!=typeof fetch?c(b):fetch(O,{credentials:\"same-origin\"}).then(function(f){return WebAssembly.instantiateStreaming(f,e).then(b,function(h){G(\"wasm streaming compile failed: \"+h);G(\"falling back to ArrayBuffer instantiation\");return c(b)})})})().catch(ia);\r\nreturn{}})();x.___wasm_call_ctors=function(){return(x.___wasm_call_ctors=x.asm.Va).apply(null,arguments)};x._OrtInit=function(){return(x._OrtInit=x.asm.Wa).apply(null,arguments)};x._OrtCreateSessionOptions=function(){return(x._OrtCreateSessionOptions=x.asm.Xa).apply(null,arguments)};x._OrtAppendExecutionProvider=function(){return(x._OrtAppendExecutionProvider=x.asm.Ya).apply(null,arguments)};x._OrtAddSessionConfigEntry=function(){return(x._OrtAddSessionConfigEntry=x.asm.Za).apply(null,arguments)};\r\nx._OrtReleaseSessionOptions=function(){return(x._OrtReleaseSessionOptions=x.asm._a).apply(null,arguments)};x._OrtCreateSession=function(){return(x._OrtCreateSession=x.asm.$a).apply(null,arguments)};x._OrtReleaseSession=function(){return(x._OrtReleaseSession=x.asm.ab).apply(null,arguments)};x._OrtGetInputCount=function(){return(x._OrtGetInputCount=x.asm.bb).apply(null,arguments)};x._OrtGetOutputCount=function(){return(x._OrtGetOutputCount=x.asm.cb).apply(null,arguments)};\r\nx._OrtGetInputName=function(){return(x._OrtGetInputName=x.asm.db).apply(null,arguments)};x._OrtGetOutputName=function(){return(x._OrtGetOutputName=x.asm.eb).apply(null,arguments)};x._OrtFree=function(){return(x._OrtFree=x.asm.fb).apply(null,arguments)};x._OrtCreateTensor=function(){return(x._OrtCreateTensor=x.asm.gb).apply(null,arguments)};x._OrtGetTensorData=function(){return(x._OrtGetTensorData=x.asm.hb).apply(null,arguments)};\r\nx._OrtReleaseTensor=function(){return(x._OrtReleaseTensor=x.asm.ib).apply(null,arguments)};x._OrtCreateRunOptions=function(){return(x._OrtCreateRunOptions=x.asm.jb).apply(null,arguments)};x._OrtAddRunConfigEntry=function(){return(x._OrtAddRunConfigEntry=x.asm.kb).apply(null,arguments)};x._OrtReleaseRunOptions=function(){return(x._OrtReleaseRunOptions=x.asm.lb).apply(null,arguments)};x._OrtRun=function(){return(x._OrtRun=x.asm.mb).apply(null,arguments)};\r\nx._OrtEndProfiling=function(){return(x._OrtEndProfiling=x.asm.nb).apply(null,arguments)};var $a=x._pthread_self=function(){return($a=x._pthread_self=x.asm.ob).apply(null,arguments)},Fb=x._malloc=function(){return(Fb=x._malloc=x.asm.pb).apply(null,arguments)},kb=x._free=function(){return(kb=x._free=x.asm.qb).apply(null,arguments)},Wa=x._fflush=function(){return(Wa=x._fflush=x.asm.rb).apply(null,arguments)};x.__emscripten_tls_init=function(){return(x.__emscripten_tls_init=x.asm.sb).apply(null,arguments)};\r\nvar Va=x.___funcs_on_exit=function(){return(Va=x.___funcs_on_exit=x.asm.tb).apply(null,arguments)},ec=x.__emscripten_thread_init=function(){return(ec=x.__emscripten_thread_init=x.asm.vb).apply(null,arguments)};x.__emscripten_thread_crashed=function(){return(x.__emscripten_thread_crashed=x.asm.wb).apply(null,arguments)};\r\nvar Lb=x._emscripten_run_in_main_runtime_thread_js=function(){return(Lb=x._emscripten_run_in_main_runtime_thread_js=x.asm.xb).apply(null,arguments)},Ab=x.__emscripten_proxy_execute_task_queue=function(){return(Ab=x.__emscripten_proxy_execute_task_queue=x.asm.yb).apply(null,arguments)},Za=x.__emscripten_thread_free_data=function(){return(Za=x.__emscripten_thread_free_data=x.asm.zb).apply(null,arguments)},eb=x.__emscripten_thread_exit=function(){return(eb=x.__emscripten_thread_exit=x.asm.Ab).apply(null,\r\narguments)},Z=x._setThrew=function(){return(Z=x._setThrew=x.asm.Bb).apply(null,arguments)},cb=x._emscripten_stack_set_limits=function(){return(cb=x._emscripten_stack_set_limits=x.asm.Cb).apply(null,arguments)},S=x.stackSave=function(){return(S=x.stackSave=x.asm.Db).apply(null,arguments)},U=x.stackRestore=function(){return(U=x.stackRestore=x.asm.Eb).apply(null,arguments)},Kb=x.stackAlloc=function(){return(Kb=x.stackAlloc=x.asm.Fb).apply(null,arguments)},dc=x.___cxa_can_catch=function(){return(dc=x.___cxa_can_catch=\r\nx.asm.Gb).apply(null,arguments)},ib=x.___cxa_is_pointer_type=function(){return(ib=x.___cxa_is_pointer_type=x.asm.Hb).apply(null,arguments)},Qc=x.dynCall_j=function(){return(Qc=x.dynCall_j=x.asm.Ib).apply(null,arguments)},Rc=x.dynCall_iiiiij=function(){return(Rc=x.dynCall_iiiiij=x.asm.Jb).apply(null,arguments)},Sc=x.dynCall_jii=function(){return(Sc=x.dynCall_jii=x.asm.Kb).apply(null,arguments)},Tc=x.dynCall_viiiiij=function(){return(Tc=x.dynCall_viiiiij=x.asm.Lb).apply(null,arguments)},Uc=x.dynCall_vjji=\r\nfunction(){return(Uc=x.dynCall_vjji=x.asm.Mb).apply(null,arguments)},Vc=x.dynCall_viiijjjii=function(){return(Vc=x.dynCall_viiijjjii=x.asm.Nb).apply(null,arguments)},Wc=x.dynCall_iij=function(){return(Wc=x.dynCall_iij=x.asm.Ob).apply(null,arguments)},Xc=x.dynCall_ji=function(){return(Xc=x.dynCall_ji=x.asm.Pb).apply(null,arguments)},Yc=x.dynCall_iiiiiij=function(){return(Yc=x.dynCall_iiiiiij=x.asm.Qb).apply(null,arguments)},Zc=x.dynCall_iiij=function(){return(Zc=x.dynCall_iiij=x.asm.Rb).apply(null,\r\narguments)};function ic(a,b){var c=S();try{return V(a)(b)}catch(e){U(c);if(e!==e+0)throw e;Z(1,0)}}function Bc(a,b){var c=S();try{V(a)(b)}catch(e){U(c);if(e!==e+0)throw e;Z(1,0)}}function Cc(a,b,c){var e=S();try{V(a)(b,c)}catch(f){U(e);if(f!==f+0)throw f;Z(1,0)}}function lc(a,b,c){var e=S();try{return V(a)(b,c)}catch(f){U(e);if(f!==f+0)throw f;Z(1,0)}}function mc(a,b,c,e){var f=S();try{return V(a)(b,c,e)}catch(h){U(f);if(h!==h+0)throw h;Z(1,0)}}\r\nfunction qc(a,b,c,e,f,h,k){var l=S();try{return V(a)(b,c,e,f,h,k)}catch(u){U(l);if(u!==u+0)throw u;Z(1,0)}}function Ac(a){var b=S();try{V(a)()}catch(c){U(b);if(c!==c+0)throw c;Z(1,0)}}function pc(a,b,c,e,f,h){var k=S();try{return V(a)(b,c,e,f,h)}catch(l){U(k);if(l!==l+0)throw l;Z(1,0)}}function nc(a,b,c,e,f){var h=S();try{return V(a)(b,c,e,f)}catch(k){U(h);if(k!==k+0)throw k;Z(1,0)}}function Ec(a,b,c,e){var f=S();try{V(a)(b,c,e)}catch(h){U(f);if(h!==h+0)throw h;Z(1,0)}}\r\nfunction Gc(a,b,c,e,f,h){var k=S();try{V(a)(b,c,e,f,h)}catch(l){U(k);if(l!==l+0)throw l;Z(1,0)}}function Fc(a,b,c,e,f){var h=S();try{V(a)(b,c,e,f)}catch(k){U(h);if(k!==k+0)throw k;Z(1,0)}}function Ic(a,b,c,e,f,h,k,l){var u=S();try{V(a)(b,c,e,f,h,k,l)}catch(t){U(u);if(t!==t+0)throw t;Z(1,0)}}function kc(a,b,c){var e=S();try{return V(a)(b,c)}catch(f){U(e);if(f!==f+0)throw f;Z(1,0)}}function jc(a,b,c){var e=S();try{return V(a)(b,c)}catch(f){U(e);if(f!==f+0)throw f;Z(1,0)}}\r\nfunction Jc(a,b,c,e,f,h,k,l,u){var t=S();try{V(a)(b,c,e,f,h,k,l,u)}catch(A){U(t);if(A!==A+0)throw A;Z(1,0)}}function Hc(a,b,c,e,f,h,k){var l=S();try{V(a)(b,c,e,f,h,k)}catch(u){U(l);if(u!==u+0)throw u;Z(1,0)}}function oc(a,b,c,e,f,h){var k=S();try{return V(a)(b,c,e,f,h)}catch(l){U(k);if(l!==l+0)throw l;Z(1,0)}}function rc(a,b,c,e,f,h,k,l){var u=S();try{return V(a)(b,c,e,f,h,k,l)}catch(t){U(u);if(t!==t+0)throw t;Z(1,0)}}\r\nfunction sc(a,b,c,e,f,h,k,l,u,t,A,K){var J=S();try{return V(a)(b,c,e,f,h,k,l,u,t,A,K)}catch(g){U(J);if(g!==g+0)throw g;Z(1,0)}}function Kc(a,b,c,e,f,h,k,l,u,t,A){var K=S();try{V(a)(b,c,e,f,h,k,l,u,t,A)}catch(J){U(K);if(J!==J+0)throw J;Z(1,0)}}function Lc(a,b,c,e,f,h,k,l,u,t,A,K,J,g,w,z){var N=S();try{V(a)(b,c,e,f,h,k,l,u,t,A,K,J,g,w,z)}catch(T){U(N);if(T!==T+0)throw T;Z(1,0)}}function hc(a){var b=S();try{return V(a)()}catch(c){U(b);if(c!==c+0)throw c;Z(1,0)}}\r\nfunction gc(a,b,c){var e=S();try{return V(a)(b,c)}catch(f){U(e);if(f!==f+0)throw f;Z(1,0)}}function fc(a,b,c){var e=S();try{return V(a)(b,c)}catch(f){U(e);if(f!==f+0)throw f;Z(1,0)}}function Dc(a,b,c,e){var f=S();try{V(a)(b,c,e)}catch(h){U(f);if(h!==h+0)throw h;Z(1,0)}}function Mc(a,b,c,e,f,h,k,l){var u=S();try{Tc(a,b,c,e,f,h,k,l)}catch(t){U(u);if(t!==t+0)throw t;Z(1,0)}}function Oc(a,b,c,e,f,h){var k=S();try{Uc(a,b,c,e,f,h)}catch(l){U(k);if(l!==l+0)throw l;Z(1,0)}}\r\nfunction Nc(a,b,c,e,f,h,k,l,u,t,A,K){var J=S();try{Vc(a,b,c,e,f,h,k,l,u,t,A,K)}catch(g){U(J);if(g!==g+0)throw g;Z(1,0)}}function wc(a,b,c,e){var f=S();try{return Wc(a,b,c,e)}catch(h){U(f);if(h!==h+0)throw h;Z(1,0)}}function yc(a,b){var c=S();try{return Xc(a,b)}catch(e){U(c);if(e!==e+0)throw e;Z(1,0)}}function tc(a,b,c,e,f,h,k,l){var u=S();try{return Yc(a,b,c,e,f,h,k,l)}catch(t){U(u);if(t!==t+0)throw t;Z(1,0)}}function xc(a){var b=S();try{return Qc(a)}catch(c){U(b);if(c!==c+0)throw c;Z(1,0)}}\r\nfunction uc(a,b,c,e,f,h,k){var l=S();try{return Rc(a,b,c,e,f,h,k)}catch(u){U(l);if(u!==u+0)throw u;Z(1,0)}}function vc(a,b,c,e,f){var h=S();try{return Zc(a,b,c,e,f)}catch(k){U(h);if(k!==k+0)throw k;Z(1,0)}}function zc(a,b,c){var e=S();try{return Sc(a,b,c)}catch(f){U(e);if(f!==f+0)throw f;Z(1,0)}}x.UTF8ToString=Aa;x.stringToUTF8=function(a,b,c){return Ba(a,q(),b,c)};x.lengthBytesUTF8=Ca;x.keepRuntimeAlive=F;x.wasmMemory=m;x.stackSave=S;x.stackRestore=U;x.stackAlloc=Kb;x.ExitStatus=E;x.PThread=P;var $c;\r\nM=function ad(){$c||bd();$c||(M=ad)};\r\nfunction bd(){function a(){if(!$c&&($c=!0,x.calledRun=!0,!xa)){C||R(Ga);ha(x);if(x.onRuntimeInitialized)x.onRuntimeInitialized();if(!C){if(x.postRun)for(\"function\"==typeof x.postRun&&(x.postRun=[x.postRun]);x.postRun.length;){var b=x.postRun.shift();Ia.unshift(b)}R(Ia)}}}if(!(0<L))if(C)ha(x),C||R(Ga),postMessage({cmd:\"loaded\"});else{if(x.preRun)for(\"function\"==typeof x.preRun&&(x.preRun=[x.preRun]);x.preRun.length;)Ka();R(Fa);0<L||(x.setStatus?(x.setStatus(\"Running...\"),setTimeout(function(){setTimeout(function(){x.setStatus(\"\")},\r\n1);a()},1)):a())}}if(x.preInit)for(\"function\"==typeof x.preInit&&(x.preInit=[x.preInit]);0<x.preInit.length;)x.preInit.pop()();bd();\r\n\r\n\r\n  return ortWasmThreaded.ready\r\n}\r\n);\r\n})();\r\nif (true)\r\n  module.exports = ortWasmThreaded;\r\nelse {}\r\n\n\n/***/ }),\n\n/***/ \"./lib/wasm/binding/ort-wasm.js\":\n/*!**************************************!*\\\n  !*** ./lib/wasm/binding/ort-wasm.js ***!\n  \\**************************************/\n/***/ ((module, __unused_webpack_exports, __webpack_require__) => {\n\nvar __filename = \"/index.js\";\nvar __dirname = \"/\";\n\r\nvar ortWasm = (() => {\r\n  var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined;\r\n  if (true) _scriptDir = _scriptDir || __filename;\r\n  return (\r\nfunction(ortWasm) {\r\n  ortWasm = ortWasm || {};\r\n\r\n\r\nvar d;d||(d=typeof ortWasm !== 'undefined' ? ortWasm : {});var aa,ba;d.ready=new Promise(function(a,b){aa=a;ba=b});var ca=Object.assign({},d),da=\"./this.program\",ea=(a,b)=>{throw b;},fa=\"object\"==typeof window,m=\"function\"==typeof importScripts,p=\"object\"==typeof process&&\"object\"==typeof process.versions&&\"string\"==typeof process.versions.node,q=\"\",ha,r,v,fs,y,ia;\r\nif(p)q=m?(__webpack_require__(/*! path */ \"?75c6\").dirname)(q)+\"/\":__dirname+\"/\",ia=()=>{y||(fs=__webpack_require__(/*! fs */ \"?63c8\"),y=__webpack_require__(/*! path */ \"?75c6\"))},ha=function(a,b){ia();a=y.normalize(a);return fs.readFileSync(a,b?void 0:\"utf8\")},v=a=>{a=ha(a,!0);a.buffer||(a=new Uint8Array(a));return a},r=(a,b,c)=>{ia();a=y.normalize(a);fs.readFile(a,function(e,f){e?c(e):b(f.buffer)})},1<process.argv.length&&(da=process.argv[1].replace(/\\\\/g,\"/\")),process.argv.slice(2),process.on(\"uncaughtException\",function(a){if(!(a instanceof ja))throw a;}),process.on(\"unhandledRejection\",\r\nfunction(a){throw a;}),ea=(a,b)=>{if(noExitRuntime||0<ka)throw process.exitCode=a,b;b instanceof ja||z(\"exiting due to exception: \"+b);process.exit(a)},d.inspect=function(){return\"[Emscripten Module object]\"};else if(fa||m)m?q=self.location.href:\"undefined\"!=typeof document&&document.currentScript&&(q=document.currentScript.src),_scriptDir&&(q=_scriptDir),0!==q.indexOf(\"blob:\")?q=q.substr(0,q.replace(/[?#].*/,\"\").lastIndexOf(\"/\")+1):q=\"\",ha=a=>{var b=new XMLHttpRequest;b.open(\"GET\",a,!1);b.send(null);\r\nreturn b.responseText},m&&(v=a=>{var b=new XMLHttpRequest;b.open(\"GET\",a,!1);b.responseType=\"arraybuffer\";b.send(null);return new Uint8Array(b.response)}),r=(a,b,c)=>{var e=new XMLHttpRequest;e.open(\"GET\",a,!0);e.responseType=\"arraybuffer\";e.onload=()=>{200==e.status||0==e.status&&e.response?b(e.response):c()};e.onerror=c;e.send(null)};var la=d.print||console.log.bind(console),z=d.printErr||console.warn.bind(console);Object.assign(d,ca);ca=null;d.thisProgram&&(da=d.thisProgram);d.quit&&(ea=d.quit);\r\nvar A;d.wasmBinary&&(A=d.wasmBinary);var noExitRuntime=d.noExitRuntime||!1;\"object\"!=typeof WebAssembly&&B(\"no native wasm support detected\");var ma,D=!1,na=\"undefined\"!=typeof TextDecoder?new TextDecoder(\"utf8\"):void 0;\r\nfunction oa(a,b,c){b>>>=0;var e=b+c;for(c=b;a[c]&&!(c>=e);)++c;if(16<c-b&&a.buffer&&na)return na.decode(a.subarray(b,c));for(e=\"\";b<c;){var f=a[b++];if(f&128){var h=a[b++]&63;if(192==(f&224))e+=String.fromCharCode((f&31)<<6|h);else{var k=a[b++]&63;f=224==(f&240)?(f&15)<<12|h<<6|k:(f&7)<<18|h<<12|k<<6|a[b++]&63;65536>f?e+=String.fromCharCode(f):(f-=65536,e+=String.fromCharCode(55296|f>>10,56320|f&1023))}}else e+=String.fromCharCode(f)}return e}function pa(a,b){return(a>>>=0)?oa(G,a,b):\"\"}\r\nfunction qa(a,b,c,e){c>>>=0;if(!(0<e))return 0;var f=c;e=c+e-1;for(var h=0;h<a.length;++h){var k=a.charCodeAt(h);if(55296<=k&&57343>=k){var l=a.charCodeAt(++h);k=65536+((k&1023)<<10)|l&1023}if(127>=k){if(c>=e)break;b[c++>>>0]=k}else{if(2047>=k){if(c+1>=e)break;b[c++>>>0]=192|k>>6}else{if(65535>=k){if(c+2>=e)break;b[c++>>>0]=224|k>>12}else{if(c+3>=e)break;b[c++>>>0]=240|k>>18;b[c++>>>0]=128|k>>12&63}b[c++>>>0]=128|k>>6&63}b[c++>>>0]=128|k&63}}b[c>>>0]=0;return c-f}\r\nfunction ra(a){for(var b=0,c=0;c<a.length;++c){var e=a.charCodeAt(c);127>=e?b++:2047>=e?b+=2:55296<=e&&57343>=e?(b+=4,++c):b+=3}return b}var sa,H,G,I,J;function ta(){var a=ma.buffer;sa=a;d.HEAP8=H=new Int8Array(a);d.HEAP16=new Int16Array(a);d.HEAP32=I=new Int32Array(a);d.HEAPU8=G=new Uint8Array(a);d.HEAPU16=new Uint16Array(a);d.HEAPU32=J=new Uint32Array(a);d.HEAPF32=new Float32Array(a);d.HEAPF64=new Float64Array(a)}var ua,va=[],wa=[],xa=[],ya=[],ka=0;\r\nfunction za(){var a=d.preRun.shift();va.unshift(a)}var K=0,Aa=null,L=null;function B(a){if(d.onAbort)d.onAbort(a);a=\"Aborted(\"+a+\")\";z(a);D=!0;a=new WebAssembly.RuntimeError(a+\". Build with -sASSERTIONS for more info.\");ba(a);throw a;}function Ba(){return N.startsWith(\"data:application/octet-stream;base64,\")}var N;N=\"ort-wasm.wasm\";if(!Ba()){var Ca=N;N=d.locateFile?d.locateFile(Ca,q):q+Ca}\r\nfunction Da(){var a=N;try{if(a==N&&A)return new Uint8Array(A);if(v)return v(a);throw\"both async and sync fetching of the wasm failed\";}catch(b){B(b)}}\r\nfunction Ea(){if(!A&&(fa||m)){if(\"function\"==typeof fetch&&!N.startsWith(\"file://\"))return fetch(N,{credentials:\"same-origin\"}).then(function(a){if(!a.ok)throw\"failed to load wasm binary file at '\"+N+\"'\";return a.arrayBuffer()}).catch(function(){return Da()});if(r)return new Promise(function(a,b){r(N,function(c){a(new Uint8Array(c))},b)})}return Promise.resolve().then(function(){return Da()})}function ja(a){this.name=\"ExitStatus\";this.message=\"Program terminated with exit(\"+a+\")\";this.status=a}\r\nfunction O(a){for(;0<a.length;)a.shift()(d)}var P=[],Q=0,R=0;\r\nfunction S(a){this.Db=a;this.zb=a-24;this.Ub=function(b){J[this.zb+4>>2>>>0]=b};this.Eb=function(){return J[this.zb+4>>2>>>0]};this.Sb=function(b){J[this.zb+8>>2>>>0]=b};this.Wb=function(){return J[this.zb+8>>2>>>0]};this.Tb=function(){I[this.zb>>2>>>0]=0};this.Ib=function(b){H[this.zb+12>>0>>>0]=b?1:0};this.Pb=function(){return 0!=H[this.zb+12>>0>>>0]};this.Jb=function(b){H[this.zb+13>>0>>>0]=b?1:0};this.Lb=function(){return 0!=H[this.zb+13>>0>>>0]};this.Rb=function(b,c){this.Fb(0);this.Ub(b);this.Sb(c);\r\nthis.Tb();this.Ib(!1);this.Jb(!1)};this.Nb=function(){I[this.zb>>2>>>0]+=1};this.Xb=function(){var b=I[this.zb>>2>>>0];I[this.zb>>2>>>0]=b-1;return 1===b};this.Fb=function(b){J[this.zb+16>>2>>>0]=b};this.Ob=function(){return J[this.zb+16>>2>>>0]};this.Qb=function(){if(Fa(this.Eb()))return J[this.Db>>2>>>0];var b=this.Ob();return 0!==b?b:this.Db}}function Ga(a){return Ha((new S(a)).zb)}var T=[];function U(a){var b=T[a];b||(a>=T.length&&(T.length=a+1),T[a]=b=ua.get(a));return b}\r\nfunction Ia(a){var b=ra(a)+1,c=Ja(b);c&&qa(a,H,c,b);return c}function Ka(a,b,c){function e(n){return(n=n.toTimeString().match(/\\(([A-Za-z ]+)\\)$/))?n[1]:\"GMT\"}var f=(new Date).getFullYear(),h=new Date(f,0,1),k=new Date(f,6,1);f=h.getTimezoneOffset();var l=k.getTimezoneOffset();I[a>>2>>>0]=60*Math.max(f,l);I[b>>2>>>0]=Number(f!=l);a=e(h);b=e(k);a=Ia(a);b=Ia(b);l<f?(J[c>>2>>>0]=a,J[c+4>>2>>>0]=b):(J[c>>2>>>0]=b,J[c+4>>2>>>0]=a)}function La(a,b,c){La.Vb||(La.Vb=!0,Ka(a,b,c))}var Ma={};\r\nfunction Na(){if(!Oa){var a={USER:\"web_user\",LOGNAME:\"web_user\",PATH:\"/\",PWD:\"/\",HOME:\"/home/web_user\",LANG:(\"object\"==typeof navigator&&navigator.languages&&navigator.languages[0]||\"C\").replace(\"-\",\"_\")+\".UTF-8\",_:da||\"./this.program\"},b;for(b in Ma)void 0===Ma[b]?delete a[b]:a[b]=Ma[b];var c=[];for(b in a)c.push(b+\"=\"+a[b]);Oa=c}return Oa}var Oa,Pa=[null,[],[]];function Qa(a,b){var c=Pa[a];0===b||10===b?((1===a?la:z)(oa(c,0)),c.length=0):c.push(b)}var V=0;\r\nfunction Ra(){if(\"object\"==typeof crypto&&\"function\"==typeof crypto.getRandomValues){var a=new Uint8Array(1);return()=>{crypto.getRandomValues(a);return a[0]}}if(p)try{var b=__webpack_require__(Object(function webpackMissingModule() { var e = new Error(\"Cannot find module 'crypto'\"); e.code = 'MODULE_NOT_FOUND'; throw e; }()));return()=>b.randomBytes(1)[0]}catch(c){}return()=>B(\"randomDevice\")}function W(a,b){W.Mb||(W.Mb=Ra());for(var c=0;c<b;c++)H[a+c>>0>>>0]=W.Mb();return 0}function Sa(a){return 0===a%4&&(0!==a%100||0===a%400)}var Ta=[31,29,31,30,31,30,31,31,30,31,30,31],Ua=[31,28,31,30,31,30,31,31,30,31,30,31];\r\nfunction Va(a){var b=Array(ra(a)+1);qa(a,b,0,b.length);return b}\r\nfunction Wa(a,b,c,e){function f(g,u,w){for(g=\"number\"==typeof g?g.toString():g||\"\";g.length<u;)g=w[0]+g;return g}function h(g,u){return f(g,u,\"0\")}function k(g,u){function w(M){return 0>M?-1:0<M?1:0}var F;0===(F=w(g.getFullYear()-u.getFullYear()))&&0===(F=w(g.getMonth()-u.getMonth()))&&(F=w(g.getDate()-u.getDate()));return F}function l(g){switch(g.getDay()){case 0:return new Date(g.getFullYear()-1,11,29);case 1:return g;case 2:return new Date(g.getFullYear(),0,3);case 3:return new Date(g.getFullYear(),\r\n0,2);case 4:return new Date(g.getFullYear(),0,1);case 5:return new Date(g.getFullYear()-1,11,31);case 6:return new Date(g.getFullYear()-1,11,30)}}function n(g){var u=g.Bb;for(g=new Date((new Date(g.Cb+1900,0,1)).getTime());0<u;){var w=g.getMonth(),F=(Sa(g.getFullYear())?Ta:Ua)[w];if(u>F-g.getDate())u-=F-g.getDate()+1,g.setDate(1),11>w?g.setMonth(w+1):(g.setMonth(0),g.setFullYear(g.getFullYear()+1));else{g.setDate(g.getDate()+u);break}}w=new Date(g.getFullYear()+1,0,4);u=l(new Date(g.getFullYear(),\r\n0,4));w=l(w);return 0>=k(u,g)?0>=k(w,g)?g.getFullYear()+1:g.getFullYear():g.getFullYear()-1}var t=I[e+40>>2>>>0];e={$b:I[e>>2>>>0],Zb:I[e+4>>2>>>0],Gb:I[e+8>>2>>>0],Kb:I[e+12>>2>>>0],Hb:I[e+16>>2>>>0],Cb:I[e+20>>2>>>0],Ab:I[e+24>>2>>>0],Bb:I[e+28>>2>>>0],bc:I[e+32>>2>>>0],Yb:I[e+36>>2>>>0],ac:t?pa(t):\"\"};c=pa(c);t={\"%c\":\"%a %b %d %H:%M:%S %Y\",\"%D\":\"%m/%d/%y\",\"%F\":\"%Y-%m-%d\",\"%h\":\"%b\",\"%r\":\"%I:%M:%S %p\",\"%R\":\"%H:%M\",\"%T\":\"%H:%M:%S\",\"%x\":\"%m/%d/%y\",\"%X\":\"%H:%M:%S\",\"%Ec\":\"%c\",\"%EC\":\"%C\",\"%Ex\":\"%m/%d/%y\",\r\n\"%EX\":\"%H:%M:%S\",\"%Ey\":\"%y\",\"%EY\":\"%Y\",\"%Od\":\"%d\",\"%Oe\":\"%e\",\"%OH\":\"%H\",\"%OI\":\"%I\",\"%Om\":\"%m\",\"%OM\":\"%M\",\"%OS\":\"%S\",\"%Ou\":\"%u\",\"%OU\":\"%U\",\"%OV\":\"%V\",\"%Ow\":\"%w\",\"%OW\":\"%W\",\"%Oy\":\"%y\"};for(var x in t)c=c.replace(new RegExp(x,\"g\"),t[x]);var E=\"Sunday Monday Tuesday Wednesday Thursday Friday Saturday\".split(\" \"),C=\"January February March April May June July August September October November December\".split(\" \");t={\"%a\":function(g){return E[g.Ab].substring(0,3)},\"%A\":function(g){return E[g.Ab]},\"%b\":function(g){return C[g.Hb].substring(0,\r\n3)},\"%B\":function(g){return C[g.Hb]},\"%C\":function(g){return h((g.Cb+1900)/100|0,2)},\"%d\":function(g){return h(g.Kb,2)},\"%e\":function(g){return f(g.Kb,2,\" \")},\"%g\":function(g){return n(g).toString().substring(2)},\"%G\":function(g){return n(g)},\"%H\":function(g){return h(g.Gb,2)},\"%I\":function(g){g=g.Gb;0==g?g=12:12<g&&(g-=12);return h(g,2)},\"%j\":function(g){for(var u=0,w=0;w<=g.Hb-1;u+=(Sa(g.Cb+1900)?Ta:Ua)[w++]);return h(g.Kb+u,3)},\"%m\":function(g){return h(g.Hb+1,2)},\"%M\":function(g){return h(g.Zb,\r\n2)},\"%n\":function(){return\"\\n\"},\"%p\":function(g){return 0<=g.Gb&&12>g.Gb?\"AM\":\"PM\"},\"%S\":function(g){return h(g.$b,2)},\"%t\":function(){return\"\\t\"},\"%u\":function(g){return g.Ab||7},\"%U\":function(g){return h(Math.floor((g.Bb+7-g.Ab)/7),2)},\"%V\":function(g){var u=Math.floor((g.Bb+7-(g.Ab+6)%7)/7);2>=(g.Ab+371-g.Bb-2)%7&&u++;if(u)53==u&&(w=(g.Ab+371-g.Bb)%7,4==w||3==w&&Sa(g.Cb)||(u=1));else{u=52;var w=(g.Ab+7-g.Bb-1)%7;(4==w||5==w&&Sa(g.Cb%400-1))&&u++}return h(u,2)},\"%w\":function(g){return g.Ab},\"%W\":function(g){return h(Math.floor((g.Bb+\r\n7-(g.Ab+6)%7)/7),2)},\"%y\":function(g){return(g.Cb+1900).toString().substring(2)},\"%Y\":function(g){return g.Cb+1900},\"%z\":function(g){g=g.Yb;var u=0<=g;g=Math.abs(g)/60;return(u?\"+\":\"-\")+String(\"0000\"+(g/60*100+g%60)).slice(-4)},\"%Z\":function(g){return g.ac},\"%%\":function(){return\"%\"}};c=c.replace(/%%/g,\"\\x00\\x00\");for(x in t)c.includes(x)&&(c=c.replace(new RegExp(x,\"g\"),t[x](e)));c=c.replace(/\\0\\0/g,\"%\");x=Va(c);if(x.length>b)return 0;H.set(x,a>>>0);return x.length-1}\r\nvar Jb={a:function(a){return Ja(a+24)+24},m:function(a){a=new S(a);a.Pb()||(a.Ib(!0),Q--);a.Jb(!1);P.push(a);a.Nb();return a.Qb()},ia:function(a){z(\"Unexpected exception thrown, this is not properly supported - aborting\");D=!0;throw a;},w:function(){X(0);var a=P.pop();if(a.Xb()&&!a.Lb()){var b=a.Wb();b&&U(b)(a.Db);Ga(a.Db)}R=0},d:function(){var a=R;if(!a)return V=0;var b=new S(a);b.Fb(a);var c=b.Eb();if(!c)return V=0,a;for(var e=Array.prototype.slice.call(arguments),f=0;f<e.length;f++){var h=e[f];\r\nif(0===h||h===c)break;if(Xa(h,c,b.zb+16))return V=h,a}V=c;return a},k:function(){var a=R;if(!a)return V=0;var b=new S(a);b.Fb(a);var c=b.Eb();if(!c)return V=0,a;for(var e=Array.prototype.slice.call(arguments),f=0;f<e.length;f++){var h=e[f];if(0===h||h===c)break;if(Xa(h,c,b.zb+16))return V=h,a}V=c;return a},g:function(){var a=R;if(!a)return V=0;var b=new S(a);b.Fb(a);var c=b.Eb();if(!c)return V=0,a;for(var e=Array.prototype.slice.call(arguments),f=0;f<e.length;f++){var h=e[f];if(0===h||h===c)break;\r\nif(Xa(h,c,b.zb+16))return V=h,a}V=c;return a},s:Ga,L:function(){var a=P.pop();a||B(\"no exception to throw\");var b=a.Db;a.Lb()||(P.push(a),a.Jb(!0),a.Ib(!1),Q++);R=b;throw b;},b:function(a,b,c){(new S(a)).Rb(b,c);R=a;Q++;throw a;},la:function(){return Q},i:function(a){R||(R=a);throw a;},H:function(){return 0},Ba:function(){},pa:function(){},ra:function(){},ka:function(){return 0},za:function(){},ua:function(){},ya:function(){},R:function(){},qa:function(){},na:function(){},Aa:function(){},oa:function(){},\r\nHa:function(){},Ja:function(){B(\"To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking\")},Ia:function(){B(\"To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking\")},S:function(){return Date.now()},Ca:function(){return!0},Da:function(a,b){a=new Date(1E3*(J[a>>>2]+4294967296*I[a+4>>>2]));I[b>>2>>>0]=a.getUTCSeconds();I[b+4>>2>>>0]=a.getUTCMinutes();I[b+8>>2>>>0]=a.getUTCHours();I[b+12>>2>>>\r\n0]=a.getUTCDate();I[b+16>>2>>>0]=a.getUTCMonth();I[b+20>>2>>>0]=a.getUTCFullYear()-1900;I[b+24>>2>>>0]=a.getUTCDay();I[b+28>>2>>>0]=(a.getTime()-Date.UTC(a.getUTCFullYear(),0,1,0,0,0,0))/864E5|0},Ea:function(a,b){a=new Date(1E3*(J[a>>>2]+4294967296*I[a+4>>>2]));I[b>>2>>>0]=a.getSeconds();I[b+4>>2>>>0]=a.getMinutes();I[b+8>>2>>>0]=a.getHours();I[b+12>>2>>>0]=a.getDate();I[b+16>>2>>>0]=a.getMonth();I[b+20>>2>>>0]=a.getFullYear()-1900;I[b+24>>2>>>0]=a.getDay();var c=new Date(a.getFullYear(),0,1);I[b+\r\n28>>2>>>0]=(a.getTime()-c.getTime())/864E5|0;I[b+36>>2>>>0]=-(60*a.getTimezoneOffset());var e=(new Date(a.getFullYear(),6,1)).getTimezoneOffset();c=c.getTimezoneOffset();I[b+32>>2>>>0]=(e!=c&&a.getTimezoneOffset()==Math.min(c,e))|0},Fa:function(a){var b=new Date(I[a+20>>2>>>0]+1900,I[a+16>>2>>>0],I[a+12>>2>>>0],I[a+8>>2>>>0],I[a+4>>2>>>0],I[a>>2>>>0],0),c=I[a+32>>2>>>0],e=b.getTimezoneOffset(),f=new Date(b.getFullYear(),0,1),h=(new Date(b.getFullYear(),6,1)).getTimezoneOffset(),k=f.getTimezoneOffset(),\r\nl=Math.min(k,h);0>c?I[a+32>>2>>>0]=Number(h!=k&&l==e):0<c!=(l==e)&&(h=Math.max(k,h),b.setTime(b.getTime()+6E4*((0<c?l:h)-e)));I[a+24>>2>>>0]=b.getDay();I[a+28>>2>>>0]=(b.getTime()-f.getTime())/864E5|0;I[a>>2>>>0]=b.getSeconds();I[a+4>>2>>>0]=b.getMinutes();I[a+8>>2>>>0]=b.getHours();I[a+12>>2>>>0]=b.getDate();I[a+16>>2>>>0]=b.getMonth();return b.getTime()/1E3|0},sa:function(){return-52},ta:function(){},Ga:La,B:function(){B(\"\")},ma:function(){return 4294901760},I:p?()=>{var a=process.hrtime();return 1E3*\r\na[0]+a[1]/1E6}:()=>performance.now(),xa:function(a,b,c){G.copyWithin(a>>>0,b>>>0,b+c>>>0)},G:function(a){var b=G.length;a>>>=0;if(4294901760<a)return!1;for(var c=1;4>=c;c*=2){var e=b*(1+.2/c);e=Math.min(e,a+100663296);var f=Math;e=Math.max(a,e);f=f.min.call(f,4294901760,e+(65536-e%65536)%65536);a:{try{ma.grow(f-sa.byteLength+65535>>>16);ta();var h=1;break a}catch(k){}h=void 0}if(h)return!0}return!1},va:function(a,b){var c=0;Na().forEach(function(e,f){var h=b+c;f=J[a+4*f>>2>>>0]=h;for(h=0;h<e.length;++h)H[f++>>\r\n0>>>0]=e.charCodeAt(h);H[f>>0>>>0]=0;c+=e.length+1});return 0},wa:function(a,b){var c=Na();J[a>>2>>>0]=c.length;var e=0;c.forEach(function(f){e+=f.length+1});J[b>>2>>>0]=e;return 0},ba:function(a){noExitRuntime||0<ka||(Ya(),O(xa),Za(0),Pa[1].length&&Qa(1,10),Pa[2].length&&Qa(2,10));if(!(noExitRuntime||0<ka)){if(d.onExit)d.onExit(a);D=!0}ea(a,new ja(a))},E:function(){return 52},Q:function(){return 52},ca:function(){return 70},P:function(a,b,c,e){for(var f=0,h=0;h<c;h++){var k=J[b>>2>>>0],l=J[b+4>>\r\n2>>>0];b+=8;for(var n=0;n<l;n++)Qa(a,G[k+n>>>0]);f+=l}J[e>>2>>>0]=f;return 0},c:function(){return V},ja:W,ea:$a,fa:ab,J:bb,e:cb,N:db,O:eb,j:fb,o:gb,p:hb,M:ib,r:jb,v:kb,K:lb,D:mb,X:nb,V:ob,U:pb,Z:qb,W:rb,Y:sb,T:tb,f:ub,q:vb,h:wb,da:xb,l:yb,t:zb,u:Ab,x:Bb,z:Cb,ga:Db,A:Eb,C:Fb,aa:Gb,_:Hb,$:Ib,n:function(a){return a},F:function(a){V=a},ha:Wa,y:function(a,b,c,e){return Wa(a,b,c,e)}};\r\n(function(){function a(f){d.asm=f.exports;ma=d.asm.Ka;ta();ua=d.asm.ib;wa.unshift(d.asm.La);K--;d.monitorRunDependencies&&d.monitorRunDependencies(K);0==K&&(null!==Aa&&(clearInterval(Aa),Aa=null),L&&(f=L,L=null,f()))}function b(f){a(f.instance)}function c(f){return Ea().then(function(h){return WebAssembly.instantiate(h,e)}).then(function(h){return h}).then(f,function(h){z(\"failed to asynchronously prepare wasm: \"+h);B(h)})}var e={a:Jb};K++;d.monitorRunDependencies&&d.monitorRunDependencies(K);if(d.instantiateWasm)try{return d.instantiateWasm(e,\r\na)}catch(f){return z(\"Module.instantiateWasm callback failed with error: \"+f),!1}(function(){return A||\"function\"!=typeof WebAssembly.instantiateStreaming||Ba()||N.startsWith(\"file://\")||p||\"function\"!=typeof fetch?c(b):fetch(N,{credentials:\"same-origin\"}).then(function(f){return WebAssembly.instantiateStreaming(f,e).then(b,function(h){z(\"wasm streaming compile failed: \"+h);z(\"falling back to ArrayBuffer instantiation\");return c(b)})})})().catch(ba);return{}})();\r\nd.___wasm_call_ctors=function(){return(d.___wasm_call_ctors=d.asm.La).apply(null,arguments)};d._OrtInit=function(){return(d._OrtInit=d.asm.Ma).apply(null,arguments)};d._OrtCreateSessionOptions=function(){return(d._OrtCreateSessionOptions=d.asm.Na).apply(null,arguments)};d._OrtAppendExecutionProvider=function(){return(d._OrtAppendExecutionProvider=d.asm.Oa).apply(null,arguments)};d._OrtAddSessionConfigEntry=function(){return(d._OrtAddSessionConfigEntry=d.asm.Pa).apply(null,arguments)};\r\nd._OrtReleaseSessionOptions=function(){return(d._OrtReleaseSessionOptions=d.asm.Qa).apply(null,arguments)};d._OrtCreateSession=function(){return(d._OrtCreateSession=d.asm.Ra).apply(null,arguments)};d._OrtReleaseSession=function(){return(d._OrtReleaseSession=d.asm.Sa).apply(null,arguments)};d._OrtGetInputCount=function(){return(d._OrtGetInputCount=d.asm.Ta).apply(null,arguments)};d._OrtGetOutputCount=function(){return(d._OrtGetOutputCount=d.asm.Ua).apply(null,arguments)};\r\nd._OrtGetInputName=function(){return(d._OrtGetInputName=d.asm.Va).apply(null,arguments)};d._OrtGetOutputName=function(){return(d._OrtGetOutputName=d.asm.Wa).apply(null,arguments)};d._OrtFree=function(){return(d._OrtFree=d.asm.Xa).apply(null,arguments)};d._OrtCreateTensor=function(){return(d._OrtCreateTensor=d.asm.Ya).apply(null,arguments)};d._OrtGetTensorData=function(){return(d._OrtGetTensorData=d.asm.Za).apply(null,arguments)};\r\nd._OrtReleaseTensor=function(){return(d._OrtReleaseTensor=d.asm._a).apply(null,arguments)};d._OrtCreateRunOptions=function(){return(d._OrtCreateRunOptions=d.asm.$a).apply(null,arguments)};d._OrtAddRunConfigEntry=function(){return(d._OrtAddRunConfigEntry=d.asm.ab).apply(null,arguments)};d._OrtReleaseRunOptions=function(){return(d._OrtReleaseRunOptions=d.asm.bb).apply(null,arguments)};d._OrtRun=function(){return(d._OrtRun=d.asm.cb).apply(null,arguments)};\r\nd._OrtEndProfiling=function(){return(d._OrtEndProfiling=d.asm.db).apply(null,arguments)};\r\nvar Ja=d._malloc=function(){return(Ja=d._malloc=d.asm.eb).apply(null,arguments)},Ha=d._free=function(){return(Ha=d._free=d.asm.fb).apply(null,arguments)},Za=d._fflush=function(){return(Za=d._fflush=d.asm.gb).apply(null,arguments)},Ya=d.___funcs_on_exit=function(){return(Ya=d.___funcs_on_exit=d.asm.hb).apply(null,arguments)},X=d._setThrew=function(){return(X=d._setThrew=d.asm.jb).apply(null,arguments)},Y=d.stackSave=function(){return(Y=d.stackSave=d.asm.kb).apply(null,arguments)},Z=d.stackRestore=\r\nfunction(){return(Z=d.stackRestore=d.asm.lb).apply(null,arguments)},Kb=d.stackAlloc=function(){return(Kb=d.stackAlloc=d.asm.mb).apply(null,arguments)},Xa=d.___cxa_can_catch=function(){return(Xa=d.___cxa_can_catch=d.asm.nb).apply(null,arguments)},Fa=d.___cxa_is_pointer_type=function(){return(Fa=d.___cxa_is_pointer_type=d.asm.ob).apply(null,arguments)},Lb=d.dynCall_j=function(){return(Lb=d.dynCall_j=d.asm.pb).apply(null,arguments)},Mb=d.dynCall_iiiiij=function(){return(Mb=d.dynCall_iiiiij=d.asm.qb).apply(null,\r\narguments)},Nb=d.dynCall_jii=function(){return(Nb=d.dynCall_jii=d.asm.rb).apply(null,arguments)},Ob=d.dynCall_viiiiij=function(){return(Ob=d.dynCall_viiiiij=d.asm.sb).apply(null,arguments)},Pb=d.dynCall_vjji=function(){return(Pb=d.dynCall_vjji=d.asm.tb).apply(null,arguments)},Qb=d.dynCall_viiijjjii=function(){return(Qb=d.dynCall_viiijjjii=d.asm.ub).apply(null,arguments)},Rb=d.dynCall_iij=function(){return(Rb=d.dynCall_iij=d.asm.vb).apply(null,arguments)},Sb=d.dynCall_ji=function(){return(Sb=d.dynCall_ji=\r\nd.asm.wb).apply(null,arguments)},Tb=d.dynCall_iiiiiij=function(){return(Tb=d.dynCall_iiiiiij=d.asm.xb).apply(null,arguments)},Ub=d.dynCall_iiij=function(){return(Ub=d.dynCall_iiij=d.asm.yb).apply(null,arguments)};function cb(a,b){var c=Y();try{return U(a)(b)}catch(e){Z(c);if(e!==e+0)throw e;X(1,0)}}function vb(a,b){var c=Y();try{U(a)(b)}catch(e){Z(c);if(e!==e+0)throw e;X(1,0)}}function wb(a,b,c){var e=Y();try{U(a)(b,c)}catch(f){Z(e);if(f!==f+0)throw f;X(1,0)}}\r\nfunction fb(a,b,c){var e=Y();try{return U(a)(b,c)}catch(f){Z(e);if(f!==f+0)throw f;X(1,0)}}function gb(a,b,c,e){var f=Y();try{return U(a)(b,c,e)}catch(h){Z(f);if(h!==h+0)throw h;X(1,0)}}function kb(a,b,c,e,f,h,k){var l=Y();try{return U(a)(b,c,e,f,h,k)}catch(n){Z(l);if(n!==n+0)throw n;X(1,0)}}function ub(a){var b=Y();try{U(a)()}catch(c){Z(b);if(c!==c+0)throw c;X(1,0)}}function jb(a,b,c,e,f,h){var k=Y();try{return U(a)(b,c,e,f,h)}catch(l){Z(k);if(l!==l+0)throw l;X(1,0)}}\r\nfunction hb(a,b,c,e,f){var h=Y();try{return U(a)(b,c,e,f)}catch(k){Z(h);if(k!==k+0)throw k;X(1,0)}}function yb(a,b,c,e){var f=Y();try{U(a)(b,c,e)}catch(h){Z(f);if(h!==h+0)throw h;X(1,0)}}function Ab(a,b,c,e,f,h){var k=Y();try{U(a)(b,c,e,f,h)}catch(l){Z(k);if(l!==l+0)throw l;X(1,0)}}function zb(a,b,c,e,f){var h=Y();try{U(a)(b,c,e,f)}catch(k){Z(h);if(k!==k+0)throw k;X(1,0)}}function Bb(a,b,c,e,f,h,k){var l=Y();try{U(a)(b,c,e,f,h,k)}catch(n){Z(l);if(n!==n+0)throw n;X(1,0)}}\r\nfunction Cb(a,b,c,e,f,h,k,l){var n=Y();try{U(a)(b,c,e,f,h,k,l)}catch(t){Z(n);if(t!==t+0)throw t;X(1,0)}}function eb(a,b,c){var e=Y();try{return U(a)(b,c)}catch(f){Z(e);if(f!==f+0)throw f;X(1,0)}}function db(a,b,c){var e=Y();try{return U(a)(b,c)}catch(f){Z(e);if(f!==f+0)throw f;X(1,0)}}function Db(a,b,c,e,f,h,k,l,n){var t=Y();try{U(a)(b,c,e,f,h,k,l,n)}catch(x){Z(t);if(x!==x+0)throw x;X(1,0)}}function ib(a,b,c,e,f,h){var k=Y();try{return U(a)(b,c,e,f,h)}catch(l){Z(k);if(l!==l+0)throw l;X(1,0)}}\r\nfunction lb(a,b,c,e,f,h,k,l){var n=Y();try{return U(a)(b,c,e,f,h,k,l)}catch(t){Z(n);if(t!==t+0)throw t;X(1,0)}}function mb(a,b,c,e,f,h,k,l,n,t,x,E){var C=Y();try{return U(a)(b,c,e,f,h,k,l,n,t,x,E)}catch(g){Z(C);if(g!==g+0)throw g;X(1,0)}}function Eb(a,b,c,e,f,h,k,l,n,t,x){var E=Y();try{U(a)(b,c,e,f,h,k,l,n,t,x)}catch(C){Z(E);if(C!==C+0)throw C;X(1,0)}}function Fb(a,b,c,e,f,h,k,l,n,t,x,E,C,g,u,w){var F=Y();try{U(a)(b,c,e,f,h,k,l,n,t,x,E,C,g,u,w)}catch(M){Z(F);if(M!==M+0)throw M;X(1,0)}}\r\nfunction bb(a){var b=Y();try{return U(a)()}catch(c){Z(b);if(c!==c+0)throw c;X(1,0)}}function ab(a,b,c){var e=Y();try{return U(a)(b,c)}catch(f){Z(e);if(f!==f+0)throw f;X(1,0)}}function $a(a,b,c){var e=Y();try{return U(a)(b,c)}catch(f){Z(e);if(f!==f+0)throw f;X(1,0)}}function xb(a,b,c,e){var f=Y();try{U(a)(b,c,e)}catch(h){Z(f);if(h!==h+0)throw h;X(1,0)}}function Gb(a,b,c,e,f,h,k,l){var n=Y();try{Ob(a,b,c,e,f,h,k,l)}catch(t){Z(n);if(t!==t+0)throw t;X(1,0)}}\r\nfunction Ib(a,b,c,e,f,h){var k=Y();try{Pb(a,b,c,e,f,h)}catch(l){Z(k);if(l!==l+0)throw l;X(1,0)}}function Hb(a,b,c,e,f,h,k,l,n,t,x,E){var C=Y();try{Qb(a,b,c,e,f,h,k,l,n,t,x,E)}catch(g){Z(C);if(g!==g+0)throw g;X(1,0)}}function qb(a,b,c,e){var f=Y();try{return Rb(a,b,c,e)}catch(h){Z(f);if(h!==h+0)throw h;X(1,0)}}function sb(a,b){var c=Y();try{return Sb(a,b)}catch(e){Z(c);if(e!==e+0)throw e;X(1,0)}}\r\nfunction nb(a,b,c,e,f,h,k,l){var n=Y();try{return Tb(a,b,c,e,f,h,k,l)}catch(t){Z(n);if(t!==t+0)throw t;X(1,0)}}function rb(a){var b=Y();try{return Lb(a)}catch(c){Z(b);if(c!==c+0)throw c;X(1,0)}}function ob(a,b,c,e,f,h,k){var l=Y();try{return Mb(a,b,c,e,f,h,k)}catch(n){Z(l);if(n!==n+0)throw n;X(1,0)}}function pb(a,b,c,e,f){var h=Y();try{return Ub(a,b,c,e,f)}catch(k){Z(h);if(k!==k+0)throw k;X(1,0)}}function tb(a,b,c){var e=Y();try{return Nb(a,b,c)}catch(f){Z(e);if(f!==f+0)throw f;X(1,0)}}\r\nd.UTF8ToString=pa;d.stringToUTF8=function(a,b,c){return qa(a,G,b,c)};d.lengthBytesUTF8=ra;d.stackSave=Y;d.stackRestore=Z;d.stackAlloc=Kb;var Vb;L=function Wb(){Vb||Xb();Vb||(L=Wb)};\r\nfunction Xb(){function a(){if(!Vb&&(Vb=!0,d.calledRun=!0,!D)){O(wa);aa(d);if(d.onRuntimeInitialized)d.onRuntimeInitialized();if(d.postRun)for(\"function\"==typeof d.postRun&&(d.postRun=[d.postRun]);d.postRun.length;){var b=d.postRun.shift();ya.unshift(b)}O(ya)}}if(!(0<K)){if(d.preRun)for(\"function\"==typeof d.preRun&&(d.preRun=[d.preRun]);d.preRun.length;)za();O(va);0<K||(d.setStatus?(d.setStatus(\"Running...\"),setTimeout(function(){setTimeout(function(){d.setStatus(\"\")},1);a()},1)):a())}}\r\nif(d.preInit)for(\"function\"==typeof d.preInit&&(d.preInit=[d.preInit]);0<d.preInit.length;)d.preInit.pop()();Xb();\r\n\r\n\r\n  return ortWasm.ready\r\n}\r\n);\r\n})();\r\nif (true)\r\n  module.exports = ortWasm;\r\nelse {}\r\n\n\n/***/ }),\n\n/***/ \"./lib/wasm/options-utils.ts\":\n/*!***********************************!*\\\n  !*** ./lib/wasm/options-utils.ts ***!\n  \\***********************************/\n/***/ ((__unused_webpack_module, exports) => {\n\n\"use strict\";\n\n// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.iterateExtraOptions = void 0;\nconst iterateExtraOptions = (options, prefix, seen, handler) => {\n    if (typeof options == 'object' && options !== null) {\n        if (seen.has(options)) {\n            throw new Error('Circular reference in options');\n        }\n        else {\n            seen.add(options);\n        }\n    }\n    Object.entries(options).forEach(([key, value]) => {\n        const name = (prefix) ? prefix + key : key;\n        if (typeof value === 'object') {\n            (0, exports.iterateExtraOptions)(value, name + '.', seen, handler);\n        }\n        else if (typeof value === 'string' || typeof value === 'number') {\n            handler(name, value.toString());\n        }\n        else if (typeof value === 'boolean') {\n            handler(name, (value) ? '1' : '0');\n        }\n        else {\n            throw new Error(`Can't handle extra config type: ${typeof value}`);\n        }\n    });\n};\nexports.iterateExtraOptions = iterateExtraOptions;\n\n\n/***/ }),\n\n/***/ \"./lib/wasm/run-options.ts\":\n/*!*********************************!*\\\n  !*** ./lib/wasm/run-options.ts ***!\n  \\*********************************/\n/***/ ((__unused_webpack_module, exports, __webpack_require__) => {\n\n\"use strict\";\n\n// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.setRunOptions = void 0;\nconst options_utils_1 = __webpack_require__(/*! ./options-utils */ \"./lib/wasm/options-utils.ts\");\nconst string_utils_1 = __webpack_require__(/*! ./string-utils */ \"./lib/wasm/string-utils.ts\");\nconst wasm_factory_1 = __webpack_require__(/*! ./wasm-factory */ \"./lib/wasm/wasm-factory.ts\");\nconst setRunOptions = (options) => {\n    const wasm = (0, wasm_factory_1.getInstance)();\n    let runOptionsHandle = 0;\n    const allocs = [];\n    const runOptions = options || {};\n    try {\n        if ((options === null || options === void 0 ? void 0 : options.logSeverityLevel) === undefined) {\n            runOptions.logSeverityLevel = 2; // Default to warning\n        }\n        else if (typeof options.logSeverityLevel !== 'number' || !Number.isInteger(options.logSeverityLevel) ||\n            options.logSeverityLevel < 0 || options.logSeverityLevel > 4) {\n            throw new Error(`log serverity level is not valid: ${options.logSeverityLevel}`);\n        }\n        if ((options === null || options === void 0 ? void 0 : options.logVerbosityLevel) === undefined) {\n            runOptions.logVerbosityLevel = 0; // Default to 0\n        }\n        else if (typeof options.logVerbosityLevel !== 'number' || !Number.isInteger(options.logVerbosityLevel)) {\n            throw new Error(`log verbosity level is not valid: ${options.logVerbosityLevel}`);\n        }\n        if ((options === null || options === void 0 ? void 0 : options.terminate) === undefined) {\n            runOptions.terminate = false;\n        }\n        let tagDataOffset = 0;\n        if ((options === null || options === void 0 ? void 0 : options.tag) !== undefined) {\n            tagDataOffset = (0, string_utils_1.allocWasmString)(options.tag, allocs);\n        }\n        runOptionsHandle = wasm._OrtCreateRunOptions(runOptions.logSeverityLevel, runOptions.logVerbosityLevel, !!runOptions.terminate, tagDataOffset);\n        if (runOptionsHandle === 0) {\n            throw new Error('Can\\'t create run options');\n        }\n        if ((options === null || options === void 0 ? void 0 : options.extra) !== undefined) {\n            (0, options_utils_1.iterateExtraOptions)(options.extra, '', new WeakSet(), (key, value) => {\n                const keyDataOffset = (0, string_utils_1.allocWasmString)(key, allocs);\n                const valueDataOffset = (0, string_utils_1.allocWasmString)(value, allocs);\n                if (wasm._OrtAddRunConfigEntry(runOptionsHandle, keyDataOffset, valueDataOffset) !== 0) {\n                    throw new Error(`Can't set a run config entry: ${key} - ${value}`);\n                }\n            });\n        }\n        return [runOptionsHandle, allocs];\n    }\n    catch (e) {\n        if (runOptionsHandle !== 0) {\n            wasm._OrtReleaseRunOptions(runOptionsHandle);\n        }\n        allocs.forEach(wasm._free);\n        throw e;\n    }\n};\nexports.setRunOptions = setRunOptions;\n\n\n/***/ }),\n\n/***/ \"./lib/wasm/session-options.ts\":\n/*!*************************************!*\\\n  !*** ./lib/wasm/session-options.ts ***!\n  \\*************************************/\n/***/ ((__unused_webpack_module, exports, __webpack_require__) => {\n\n\"use strict\";\n\n// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.setSessionOptions = void 0;\nconst options_utils_1 = __webpack_require__(/*! ./options-utils */ \"./lib/wasm/options-utils.ts\");\nconst string_utils_1 = __webpack_require__(/*! ./string-utils */ \"./lib/wasm/string-utils.ts\");\nconst wasm_factory_1 = __webpack_require__(/*! ./wasm-factory */ \"./lib/wasm/wasm-factory.ts\");\nconst getGraphOptimzationLevel = (graphOptimizationLevel) => {\n    switch (graphOptimizationLevel) {\n        case 'disabled':\n            return 0;\n        case 'basic':\n            return 1;\n        case 'extended':\n            return 2;\n        case 'all':\n            return 99;\n        default:\n            throw new Error(`unsupported graph optimization level: ${graphOptimizationLevel}`);\n    }\n};\nconst getExecutionMode = (executionMode) => {\n    switch (executionMode) {\n        case 'sequential':\n            return 0;\n        case 'parallel':\n            return 1;\n        default:\n            throw new Error(`unsupported execution mode: ${executionMode}`);\n    }\n};\nconst appendDefaultOptions = (options) => {\n    if (!options.extra) {\n        options.extra = {};\n    }\n    if (!options.extra.session) {\n        options.extra.session = {};\n    }\n    const session = options.extra.session;\n    if (!session.use_ort_model_bytes_directly) {\n        // eslint-disable-next-line camelcase\n        session.use_ort_model_bytes_directly = '1';\n    }\n};\nconst setExecutionProviders = (sessionOptionsHandle, executionProviders, allocs) => {\n    for (const ep of executionProviders) {\n        let epName = typeof ep === 'string' ? ep : ep.name;\n        // check EP name\n        switch (epName) {\n            case 'xnnpack':\n                epName = 'XNNPACK';\n                break;\n            case 'wasm':\n            case 'cpu':\n                continue;\n            default:\n                throw new Error(`not supported EP: ${epName}`);\n        }\n        const epNameDataOffset = (0, string_utils_1.allocWasmString)(epName, allocs);\n        if ((0, wasm_factory_1.getInstance)()._OrtAppendExecutionProvider(sessionOptionsHandle, epNameDataOffset) !== 0) {\n            throw new Error(`Can't append execution provider: ${epName}`);\n        }\n    }\n};\nconst setSessionOptions = (options) => {\n    const wasm = (0, wasm_factory_1.getInstance)();\n    let sessionOptionsHandle = 0;\n    const allocs = [];\n    const sessionOptions = options || {};\n    appendDefaultOptions(sessionOptions);\n    try {\n        if ((options === null || options === void 0 ? void 0 : options.graphOptimizationLevel) === undefined) {\n            sessionOptions.graphOptimizationLevel = 'all';\n        }\n        const graphOptimizationLevel = getGraphOptimzationLevel(sessionOptions.graphOptimizationLevel);\n        if ((options === null || options === void 0 ? void 0 : options.enableCpuMemArena) === undefined) {\n            sessionOptions.enableCpuMemArena = true;\n        }\n        if ((options === null || options === void 0 ? void 0 : options.enableMemPattern) === undefined) {\n            sessionOptions.enableMemPattern = true;\n        }\n        if ((options === null || options === void 0 ? void 0 : options.executionMode) === undefined) {\n            sessionOptions.executionMode = 'sequential';\n        }\n        const executionMode = getExecutionMode(sessionOptions.executionMode);\n        let logIdDataOffset = 0;\n        if ((options === null || options === void 0 ? void 0 : options.logId) !== undefined) {\n            logIdDataOffset = (0, string_utils_1.allocWasmString)(options.logId, allocs);\n        }\n        if ((options === null || options === void 0 ? void 0 : options.logSeverityLevel) === undefined) {\n            sessionOptions.logSeverityLevel = 2; // Default to warning\n        }\n        else if (typeof options.logSeverityLevel !== 'number' || !Number.isInteger(options.logSeverityLevel) ||\n            options.logSeverityLevel < 0 || options.logSeverityLevel > 4) {\n            throw new Error(`log serverity level is not valid: ${options.logSeverityLevel}`);\n        }\n        if ((options === null || options === void 0 ? void 0 : options.logVerbosityLevel) === undefined) {\n            sessionOptions.logVerbosityLevel = 0; // Default to 0\n        }\n        else if (typeof options.logVerbosityLevel !== 'number' || !Number.isInteger(options.logVerbosityLevel)) {\n            throw new Error(`log verbosity level is not valid: ${options.logVerbosityLevel}`);\n        }\n        if ((options === null || options === void 0 ? void 0 : options.enableProfiling) === undefined) {\n            sessionOptions.enableProfiling = false;\n        }\n        sessionOptionsHandle = wasm._OrtCreateSessionOptions(graphOptimizationLevel, !!sessionOptions.enableCpuMemArena, !!sessionOptions.enableMemPattern, executionMode, !!sessionOptions.enableProfiling, 0, logIdDataOffset, sessionOptions.logSeverityLevel, sessionOptions.logVerbosityLevel);\n        if (sessionOptionsHandle === 0) {\n            throw new Error('Can\\'t create session options');\n        }\n        if (options === null || options === void 0 ? void 0 : options.executionProviders) {\n            setExecutionProviders(sessionOptionsHandle, options.executionProviders, allocs);\n        }\n        if ((options === null || options === void 0 ? void 0 : options.extra) !== undefined) {\n            (0, options_utils_1.iterateExtraOptions)(options.extra, '', new WeakSet(), (key, value) => {\n                const keyDataOffset = (0, string_utils_1.allocWasmString)(key, allocs);\n                const valueDataOffset = (0, string_utils_1.allocWasmString)(value, allocs);\n                if (wasm._OrtAddSessionConfigEntry(sessionOptionsHandle, keyDataOffset, valueDataOffset) !== 0) {\n                    throw new Error(`Can't set a session config entry: ${key} - ${value}`);\n                }\n            });\n        }\n        return [sessionOptionsHandle, allocs];\n    }\n    catch (e) {\n        if (sessionOptionsHandle !== 0) {\n            wasm._OrtReleaseSessionOptions(sessionOptionsHandle);\n        }\n        allocs.forEach(wasm._free);\n        throw e;\n    }\n};\nexports.setSessionOptions = setSessionOptions;\n\n\n/***/ }),\n\n/***/ \"./lib/wasm/string-utils.ts\":\n/*!**********************************!*\\\n  !*** ./lib/wasm/string-utils.ts ***!\n  \\**********************************/\n/***/ ((__unused_webpack_module, exports, __webpack_require__) => {\n\n\"use strict\";\n\n// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.allocWasmString = void 0;\nconst wasm_factory_1 = __webpack_require__(/*! ./wasm-factory */ \"./lib/wasm/wasm-factory.ts\");\nconst allocWasmString = (data, allocs) => {\n    const wasm = (0, wasm_factory_1.getInstance)();\n    const dataLength = wasm.lengthBytesUTF8(data) + 1;\n    const dataOffset = wasm._malloc(dataLength);\n    wasm.stringToUTF8(data, dataOffset, dataLength);\n    allocs.push(dataOffset);\n    return dataOffset;\n};\nexports.allocWasmString = allocWasmString;\n\n\n/***/ }),\n\n/***/ \"./lib/wasm/wasm-core-impl.ts\":\n/*!************************************!*\\\n  !*** ./lib/wasm/wasm-core-impl.ts ***!\n  \\************************************/\n/***/ ((__unused_webpack_module, exports, __webpack_require__) => {\n\n\"use strict\";\n\n// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.extractTransferableBuffers = exports.endProfiling = exports.run = exports.releaseSession = exports.createSession = exports.createSessionFinalize = exports.createSessionAllocate = exports.initOrt = void 0;\nconst run_options_1 = __webpack_require__(/*! ./run-options */ \"./lib/wasm/run-options.ts\");\nconst session_options_1 = __webpack_require__(/*! ./session-options */ \"./lib/wasm/session-options.ts\");\nconst string_utils_1 = __webpack_require__(/*! ./string-utils */ \"./lib/wasm/string-utils.ts\");\nconst wasm_factory_1 = __webpack_require__(/*! ./wasm-factory */ \"./lib/wasm/wasm-factory.ts\");\n/**\n * initialize ORT environment.\n * @param numThreads SetGlobalIntraOpNumThreads(numThreads)\n * @param loggingLevel CreateEnv(static_cast<OrtLoggingLevel>(logging_level))\n */\nconst initOrt = (numThreads, loggingLevel) => {\n    const errorCode = (0, wasm_factory_1.getInstance)()._OrtInit(numThreads, loggingLevel);\n    if (errorCode !== 0) {\n        throw new Error(`Can't initialize onnxruntime. error code = ${errorCode}`);\n    }\n};\nexports.initOrt = initOrt;\nconst activeSessions = new Map();\n/**\n * create an instance of InferenceSession.\n * @returns the metadata of InferenceSession. 0-value handle for failure.\n */\nconst createSessionAllocate = (model) => {\n    const wasm = (0, wasm_factory_1.getInstance)();\n    const modelDataOffset = wasm._malloc(model.byteLength);\n    wasm.HEAPU8.set(model, modelDataOffset);\n    return [modelDataOffset, model.byteLength];\n};\nexports.createSessionAllocate = createSessionAllocate;\nconst createSessionFinalize = (modelData, options) => {\n    const wasm = (0, wasm_factory_1.getInstance)();\n    let sessionHandle = 0;\n    let sessionOptionsHandle = 0;\n    let allocs = [];\n    try {\n        [sessionOptionsHandle, allocs] = (0, session_options_1.setSessionOptions)(options);\n        sessionHandle = wasm._OrtCreateSession(modelData[0], modelData[1], sessionOptionsHandle);\n        if (sessionHandle === 0) {\n            throw new Error('Can\\'t create a session');\n        }\n    }\n    finally {\n        wasm._free(modelData[0]);\n        wasm._OrtReleaseSessionOptions(sessionOptionsHandle);\n        allocs.forEach(wasm._free);\n    }\n    const inputCount = wasm._OrtGetInputCount(sessionHandle);\n    const outputCount = wasm._OrtGetOutputCount(sessionHandle);\n    const inputNames = [];\n    const inputNamesUTF8Encoded = [];\n    const outputNames = [];\n    const outputNamesUTF8Encoded = [];\n    for (let i = 0; i < inputCount; i++) {\n        const name = wasm._OrtGetInputName(sessionHandle, i);\n        if (name === 0) {\n            throw new Error('Can\\'t get an input name');\n        }\n        inputNamesUTF8Encoded.push(name);\n        inputNames.push(wasm.UTF8ToString(name));\n    }\n    for (let i = 0; i < outputCount; i++) {\n        const name = wasm._OrtGetOutputName(sessionHandle, i);\n        if (name === 0) {\n            throw new Error('Can\\'t get an output name');\n        }\n        outputNamesUTF8Encoded.push(name);\n        outputNames.push(wasm.UTF8ToString(name));\n    }\n    activeSessions.set(sessionHandle, [sessionHandle, inputNamesUTF8Encoded, outputNamesUTF8Encoded]);\n    return [sessionHandle, inputNames, outputNames];\n};\nexports.createSessionFinalize = createSessionFinalize;\n/**\n * create an instance of InferenceSession.\n * @returns the metadata of InferenceSession. 0-value handle for failure.\n */\nconst createSession = (model, options) => {\n    const modelData = (0, exports.createSessionAllocate)(model);\n    return (0, exports.createSessionFinalize)(modelData, options);\n};\nexports.createSession = createSession;\nconst releaseSession = (sessionId) => {\n    const wasm = (0, wasm_factory_1.getInstance)();\n    const session = activeSessions.get(sessionId);\n    if (!session) {\n        throw new Error('invalid session id');\n    }\n    const sessionHandle = session[0];\n    const inputNamesUTF8Encoded = session[1];\n    const outputNamesUTF8Encoded = session[2];\n    inputNamesUTF8Encoded.forEach(wasm._OrtFree);\n    outputNamesUTF8Encoded.forEach(wasm._OrtFree);\n    wasm._OrtReleaseSession(sessionHandle);\n    activeSessions.delete(sessionId);\n};\nexports.releaseSession = releaseSession;\nconst tensorDataTypeStringToEnum = (type) => {\n    switch (type) {\n        case 'int8':\n            return 3 /* DataType.int8 */;\n        case 'uint8':\n            return 2 /* DataType.uint8 */;\n        case 'bool':\n            return 9 /* DataType.bool */;\n        case 'int16':\n            return 5 /* DataType.int16 */;\n        case 'uint16':\n            return 4 /* DataType.uint16 */;\n        case 'int32':\n            return 6 /* DataType.int32 */;\n        case 'uint32':\n            return 12 /* DataType.uint32 */;\n        case 'float32':\n            return 1 /* DataType.float */;\n        case 'float64':\n            return 11 /* DataType.double */;\n        case 'string':\n            return 8 /* DataType.string */;\n        case 'int64':\n            return 7 /* DataType.int64 */;\n        case 'uint64':\n            return 13 /* DataType.uint64 */;\n        default:\n            throw new Error(`unsupported data type: ${type}`);\n    }\n};\nconst tensorDataTypeEnumToString = (typeProto) => {\n    switch (typeProto) {\n        case 3 /* DataType.int8 */:\n            return 'int8';\n        case 2 /* DataType.uint8 */:\n            return 'uint8';\n        case 9 /* DataType.bool */:\n            return 'bool';\n        case 5 /* DataType.int16 */:\n            return 'int16';\n        case 4 /* DataType.uint16 */:\n            return 'uint16';\n        case 6 /* DataType.int32 */:\n            return 'int32';\n        case 12 /* DataType.uint32 */:\n            return 'uint32';\n        case 1 /* DataType.float */:\n            return 'float32';\n        case 11 /* DataType.double */:\n            return 'float64';\n        case 8 /* DataType.string */:\n            return 'string';\n        case 7 /* DataType.int64 */:\n            return 'int64';\n        case 13 /* DataType.uint64 */:\n            return 'uint64';\n        default:\n            throw new Error(`unsupported data type: ${typeProto}`);\n    }\n};\nconst numericTensorTypeToTypedArray = (type) => {\n    switch (type) {\n        case 'float32':\n            return Float32Array;\n        case 'uint8':\n            return Uint8Array;\n        case 'int8':\n            return Int8Array;\n        case 'uint16':\n            return Uint16Array;\n        case 'int16':\n            return Int16Array;\n        case 'int32':\n            return Int32Array;\n        case 'bool':\n            return Uint8Array;\n        case 'float64':\n            return Float64Array;\n        case 'uint32':\n            return Uint32Array;\n        case 'int64':\n            return BigInt64Array;\n        case 'uint64':\n            return BigUint64Array;\n        default:\n            throw new Error(`unsupported type: ${type}`);\n    }\n};\n/**\n * perform inference run\n */\nconst run = (sessionId, inputIndices, inputs, outputIndices, options) => {\n    const wasm = (0, wasm_factory_1.getInstance)();\n    const session = activeSessions.get(sessionId);\n    if (!session) {\n        throw new Error('invalid session id');\n    }\n    const sessionHandle = session[0];\n    const inputNamesUTF8Encoded = session[1];\n    const outputNamesUTF8Encoded = session[2];\n    const inputCount = inputIndices.length;\n    const outputCount = outputIndices.length;\n    let runOptionsHandle = 0;\n    let runOptionsAllocs = [];\n    const inputValues = [];\n    const inputAllocs = [];\n    try {\n        [runOptionsHandle, runOptionsAllocs] = (0, run_options_1.setRunOptions)(options);\n        // create input tensors\n        for (let i = 0; i < inputCount; i++) {\n            const dataType = inputs[i][0];\n            const dims = inputs[i][1];\n            const data = inputs[i][2];\n            let dataOffset;\n            let dataByteLength;\n            if (Array.isArray(data)) {\n                // string tensor\n                dataByteLength = 4 * data.length;\n                dataOffset = wasm._malloc(dataByteLength);\n                inputAllocs.push(dataOffset);\n                let dataIndex = dataOffset / 4;\n                for (let i = 0; i < data.length; i++) {\n                    if (typeof data[i] !== 'string') {\n                        throw new TypeError(`tensor data at index ${i} is not a string`);\n                    }\n                    wasm.HEAPU32[dataIndex++] = (0, string_utils_1.allocWasmString)(data[i], inputAllocs);\n                }\n            }\n            else {\n                dataByteLength = data.byteLength;\n                dataOffset = wasm._malloc(dataByteLength);\n                inputAllocs.push(dataOffset);\n                wasm.HEAPU8.set(new Uint8Array(data.buffer, data.byteOffset, dataByteLength), dataOffset);\n            }\n            const stack = wasm.stackSave();\n            const dimsOffset = wasm.stackAlloc(4 * dims.length);\n            try {\n                let dimIndex = dimsOffset / 4;\n                dims.forEach(d => wasm.HEAP32[dimIndex++] = d);\n                const tensor = wasm._OrtCreateTensor(tensorDataTypeStringToEnum(dataType), dataOffset, dataByteLength, dimsOffset, dims.length);\n                if (tensor === 0) {\n                    throw new Error('Can\\'t create a tensor');\n                }\n                inputValues.push(tensor);\n            }\n            finally {\n                wasm.stackRestore(stack);\n            }\n        }\n        const beforeRunStack = wasm.stackSave();\n        const inputValuesOffset = wasm.stackAlloc(inputCount * 4);\n        const inputNamesOffset = wasm.stackAlloc(inputCount * 4);\n        const outputValuesOffset = wasm.stackAlloc(outputCount * 4);\n        const outputNamesOffset = wasm.stackAlloc(outputCount * 4);\n        try {\n            let inputValuesIndex = inputValuesOffset / 4;\n            let inputNamesIndex = inputNamesOffset / 4;\n            let outputValuesIndex = outputValuesOffset / 4;\n            let outputNamesIndex = outputNamesOffset / 4;\n            for (let i = 0; i < inputCount; i++) {\n                wasm.HEAPU32[inputValuesIndex++] = inputValues[i];\n                wasm.HEAPU32[inputNamesIndex++] = inputNamesUTF8Encoded[inputIndices[i]];\n            }\n            for (let i = 0; i < outputCount; i++) {\n                wasm.HEAPU32[outputValuesIndex++] = 0;\n                wasm.HEAPU32[outputNamesIndex++] = outputNamesUTF8Encoded[outputIndices[i]];\n            }\n            // support RunOptions\n            let errorCode = wasm._OrtRun(sessionHandle, inputNamesOffset, inputValuesOffset, inputCount, outputNamesOffset, outputCount, outputValuesOffset, runOptionsHandle);\n            const output = [];\n            if (errorCode === 0) {\n                for (let i = 0; i < outputCount; i++) {\n                    const tensor = wasm.HEAPU32[outputValuesOffset / 4 + i];\n                    const beforeGetTensorDataStack = wasm.stackSave();\n                    // stack allocate 4 pointer value\n                    const tensorDataOffset = wasm.stackAlloc(4 * 4);\n                    let type, dataOffset = 0;\n                    try {\n                        errorCode = wasm._OrtGetTensorData(tensor, tensorDataOffset, tensorDataOffset + 4, tensorDataOffset + 8, tensorDataOffset + 12);\n                        if (errorCode !== 0) {\n                            throw new Error(`Can't access output tensor data. error code = ${errorCode}`);\n                        }\n                        let tensorDataIndex = tensorDataOffset / 4;\n                        const dataType = wasm.HEAPU32[tensorDataIndex++];\n                        dataOffset = wasm.HEAPU32[tensorDataIndex++];\n                        const dimsOffset = wasm.HEAPU32[tensorDataIndex++];\n                        const dimsLength = wasm.HEAPU32[tensorDataIndex++];\n                        const dims = [];\n                        for (let i = 0; i < dimsLength; i++) {\n                            dims.push(wasm.HEAPU32[dimsOffset / 4 + i]);\n                        }\n                        wasm._OrtFree(dimsOffset);\n                        const size = dims.length === 0 ? 1 : dims.reduce((a, b) => a * b);\n                        type = tensorDataTypeEnumToString(dataType);\n                        if (type === 'string') {\n                            const stringData = [];\n                            let dataIndex = dataOffset / 4;\n                            for (let i = 0; i < size; i++) {\n                                const offset = wasm.HEAPU32[dataIndex++];\n                                const maxBytesToRead = i === size - 1 ? undefined : wasm.HEAPU32[dataIndex] - offset;\n                                stringData.push(wasm.UTF8ToString(offset, maxBytesToRead));\n                            }\n                            output.push([type, dims, stringData]);\n                        }\n                        else {\n                            const typedArrayConstructor = numericTensorTypeToTypedArray(type);\n                            const data = new typedArrayConstructor(size);\n                            new Uint8Array(data.buffer, data.byteOffset, data.byteLength)\n                                .set(wasm.HEAPU8.subarray(dataOffset, dataOffset + data.byteLength));\n                            output.push([type, dims, data]);\n                        }\n                    }\n                    finally {\n                        wasm.stackRestore(beforeGetTensorDataStack);\n                        if (type === 'string' && dataOffset) {\n                            wasm._free(dataOffset);\n                        }\n                        wasm._OrtReleaseTensor(tensor);\n                    }\n                }\n            }\n            if (errorCode === 0) {\n                return output;\n            }\n            else {\n                throw new Error(`failed to call OrtRun(). error code = ${errorCode}.`);\n            }\n        }\n        finally {\n            wasm.stackRestore(beforeRunStack);\n        }\n    }\n    finally {\n        inputValues.forEach(wasm._OrtReleaseTensor);\n        inputAllocs.forEach(wasm._free);\n        wasm._OrtReleaseRunOptions(runOptionsHandle);\n        runOptionsAllocs.forEach(wasm._free);\n    }\n};\nexports.run = run;\n/**\n * end profiling\n */\nconst endProfiling = (sessionId) => {\n    const wasm = (0, wasm_factory_1.getInstance)();\n    const session = activeSessions.get(sessionId);\n    if (!session) {\n        throw new Error('invalid session id');\n    }\n    const sessionHandle = session[0];\n    // profile file name is not used yet, but it must be freed.\n    const profileFileName = wasm._OrtEndProfiling(sessionHandle);\n    if (profileFileName === 0) {\n        throw new Error('Can\\'t get an profile file name');\n    }\n    wasm._OrtFree(profileFileName);\n};\nexports.endProfiling = endProfiling;\nconst extractTransferableBuffers = (tensors) => {\n    const buffers = [];\n    for (const tensor of tensors) {\n        const data = tensor[2];\n        if (!Array.isArray(data) && data.buffer) {\n            buffers.push(data.buffer);\n        }\n    }\n    return buffers;\n};\nexports.extractTransferableBuffers = extractTransferableBuffers;\n\n\n/***/ }),\n\n/***/ \"./lib/wasm/wasm-factory.ts\":\n/*!**********************************!*\\\n  !*** ./lib/wasm/wasm-factory.ts ***!\n  \\**********************************/\n/***/ (function(__unused_webpack_module, exports, __webpack_require__) {\n\n\"use strict\";\nvar __dirname = \"/\";\n\n// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n    if (k2 === undefined) k2 = k;\n    var desc = Object.getOwnPropertyDescriptor(m, k);\n    if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n      desc = { enumerable: true, get: function() { return m[k]; } };\n    }\n    Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n    if (k2 === undefined) k2 = k;\n    o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n    Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n    o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n    if (mod && mod.__esModule) return mod;\n    var result = {};\n    if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n    __setModuleDefault(result, mod);\n    return result;\n};\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n    return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.dispose = exports.getInstance = exports.initializeWebAssembly = void 0;\nconst path = __importStar(__webpack_require__(/*! path */ \"?7aa5\"));\nconst ort_wasm_js_1 = __importDefault(__webpack_require__(/*! ./binding/ort-wasm.js */ \"./lib/wasm/binding/ort-wasm.js\"));\nconst ortWasmFactoryThreaded = \n// eslint-disable-next-line @typescript-eslint/no-require-imports\n true ? __webpack_require__(/*! ./binding/ort-wasm-threaded.js */ \"./lib/wasm/binding/ort-wasm-threaded.js\") : 0;\nlet wasm;\nlet initialized = false;\nlet initializing = false;\nlet aborted = false;\nconst isMultiThreadSupported = () => {\n    try {\n        // If 'SharedArrayBuffer' is not available, WebAssembly threads will not work.\n        if (typeof SharedArrayBuffer === 'undefined') {\n            return false;\n        }\n        // Test for transferability of SABs (for browsers. needed for Firefox)\n        // https://groups.google.com/forum/#!msg/mozilla.dev.platform/IHkBZlHETpA/dwsMNchWEQAJ\n        if (typeof MessageChannel !== 'undefined') {\n            new MessageChannel().port1.postMessage(new SharedArrayBuffer(1));\n        }\n        // Test for WebAssembly threads capability (for both browsers and Node.js)\n        // This typed array is a WebAssembly program containing threaded instructions.\n        return WebAssembly.validate(new Uint8Array([\n            0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 5,\n            4, 1, 3, 1, 1, 10, 11, 1, 9, 0, 65, 0, 254, 16, 2, 0, 26, 11\n        ]));\n    }\n    catch (e) {\n        return false;\n    }\n};\nconst isSimdSupported = () => {\n    try {\n        // Test for WebAssembly SIMD capability (for both browsers and Node.js)\n        // This typed array is a WebAssembly program containing SIMD instructions.\n        // The binary data is generated from the following code by wat2wasm:\n        //\n        // (module\n        //   (type $t0 (func))\n        //   (func $f0 (type $t0)\n        //     (drop\n        //       (i32x4.dot_i16x8_s\n        //         (i8x16.splat\n        //           (i32.const 0))\n        //         (v128.const i32x4 0x00000000 0x00000000 0x00000000 0x00000000)))))\n        return WebAssembly.validate(new Uint8Array([\n            0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 10, 30, 1, 28, 0, 65, 0,\n            253, 15, 253, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 253, 186, 1, 26, 11\n        ]));\n    }\n    catch (e) {\n        return false;\n    }\n};\nconst getWasmFileName = (useSimd, useThreads) => {\n    if (useThreads) {\n        return useSimd ? 'ort-wasm-simd-threaded.wasm' : 'ort-wasm-threaded.wasm';\n    }\n    else {\n        return useSimd ? 'ort-wasm-simd.wasm' : 'ort-wasm.wasm';\n    }\n};\nconst initializeWebAssembly = async (flags) => {\n    if (initialized) {\n        return Promise.resolve();\n    }\n    if (initializing) {\n        throw new Error('multiple calls to \\'initializeWebAssembly()\\' detected.');\n    }\n    if (aborted) {\n        throw new Error('previous call to \\'initializeWebAssembly()\\' failed.');\n    }\n    initializing = true;\n    // wasm flags are already initialized\n    const timeout = flags.initTimeout;\n    const numThreads = flags.numThreads;\n    const simd = flags.simd;\n    const useThreads = numThreads > 1 && isMultiThreadSupported();\n    const useSimd = simd && isSimdSupported();\n    const wasmPrefixOverride = typeof flags.wasmPaths === 'string' ? flags.wasmPaths : undefined;\n    const wasmFileName = getWasmFileName(false, useThreads);\n    const wasmOverrideFileName = getWasmFileName(useSimd, useThreads);\n    const wasmPathOverride = typeof flags.wasmPaths === 'object' ? flags.wasmPaths[wasmOverrideFileName] : undefined;\n    let isTimeout = false;\n    const tasks = [];\n    // promise for timeout\n    if (timeout > 0) {\n        tasks.push(new Promise((resolve) => {\n            setTimeout(() => {\n                isTimeout = true;\n                resolve();\n            }, timeout);\n        }));\n    }\n    // promise for module initialization\n    tasks.push(new Promise((resolve, reject) => {\n        const factory = useThreads ? ortWasmFactoryThreaded : ort_wasm_js_1.default;\n        const config = {\n            locateFile: (fileName, scriptDirectory) => {\n                if ( true && useThreads && fileName.endsWith('.worker.js') &&\n                    typeof Blob !== 'undefined') {\n                    return URL.createObjectURL(new Blob([\n                        // This require() function is handled by webpack to load file content of the corresponding .worker.js\n                        // eslint-disable-next-line @typescript-eslint/no-require-imports\n                        __webpack_require__(/*! ./binding/ort-wasm-threaded.worker.js */ \"./lib/wasm/binding/ort-wasm-threaded.worker.js\")\n                    ], { type: 'text/javascript' }));\n                }\n                if (fileName === wasmFileName) {\n                    const prefix = wasmPrefixOverride !== null && wasmPrefixOverride !== void 0 ? wasmPrefixOverride : scriptDirectory;\n                    return wasmPathOverride !== null && wasmPathOverride !== void 0 ? wasmPathOverride : prefix + wasmOverrideFileName;\n                }\n                return scriptDirectory + fileName;\n            }\n        };\n        if ( true && useThreads) {\n            if (typeof Blob === 'undefined') {\n                config.mainScriptUrlOrBlob = path.join(__dirname, 'ort-wasm-threaded.js');\n            }\n            else {\n                const scriptSourceCode = `var ortWasmThreaded=(function(){var _scriptDir;return ${factory.toString()}})();`;\n                config.mainScriptUrlOrBlob = new Blob([scriptSourceCode], { type: 'text/javascript' });\n            }\n        }\n        factory(config).then(\n        // wasm module initialized successfully\n        module => {\n            initializing = false;\n            initialized = true;\n            wasm = module;\n            resolve();\n        }, \n        // wasm module failed to initialize\n        (what) => {\n            initializing = false;\n            aborted = true;\n            reject(what);\n        });\n    }));\n    await Promise.race(tasks);\n    if (isTimeout) {\n        throw new Error(`WebAssembly backend initializing failed due to timeout: ${timeout}ms`);\n    }\n};\nexports.initializeWebAssembly = initializeWebAssembly;\nconst getInstance = () => {\n    if (initialized && wasm) {\n        return wasm;\n    }\n    throw new Error('WebAssembly is not initialized yet.');\n};\nexports.getInstance = getInstance;\nconst dispose = () => {\n    var _a;\n    if (initialized && !initializing && !aborted) {\n        initializing = true;\n        (_a = wasm.PThread) === null || _a === void 0 ? void 0 : _a.terminateAllThreads();\n        wasm = undefined;\n        initializing = false;\n        initialized = false;\n        aborted = true;\n    }\n};\nexports.dispose = dispose;\n\n\n/***/ }),\n\n/***/ \"./lib/wasm/binding/ort-wasm-threaded.worker.js\":\n/*!******************************************************!*\\\n  !*** ./lib/wasm/binding/ort-wasm-threaded.worker.js ***!\n  \\******************************************************/\n/***/ ((module) => {\n\n\"use strict\";\nmodule.exports = \"\\\"use strict\\\";var Module={};var ENVIRONMENT_IS_NODE=typeof process==\\\"object\\\"&&typeof process.versions==\\\"object\\\"&&typeof process.versions.node==\\\"string\\\";if(ENVIRONMENT_IS_NODE){var nodeWorkerThreads=require(\\\"worker_threads\\\");var parentPort=nodeWorkerThreads.parentPort;parentPort.on(\\\"message\\\",data=>onmessage({data:data}));var fs=require(\\\"fs\\\");Object.assign(global,{self:global,require:require,Module:Module,location:{href:__filename},Worker:nodeWorkerThreads.Worker,importScripts:function(f){(0,eval)(fs.readFileSync(f,\\\"utf8\\\"))},postMessage:function(msg){parentPort.postMessage(msg)},performance:global.performance||{now:function(){return Date.now()}}})}var initializedJS=false;var pendingNotifiedProxyingQueues=[];function threadPrintErr(){var text=Array.prototype.slice.call(arguments).join(\\\" \\\");if(ENVIRONMENT_IS_NODE){fs.writeSync(2,text+\\\"\\\\n\\\");return}console.error(text)}function threadAlert(){var text=Array.prototype.slice.call(arguments).join(\\\" \\\");postMessage({cmd:\\\"alert\\\",text:text,threadId:Module[\\\"_pthread_self\\\"]()})}var err=threadPrintErr;self.alert=threadAlert;Module[\\\"instantiateWasm\\\"]=(info,receiveInstance)=>{var instance=new WebAssembly.Instance(Module[\\\"wasmModule\\\"],info);receiveInstance(instance);Module[\\\"wasmModule\\\"]=null;return instance.exports};self.onunhandledrejection=e=>{throw e.reason??e};self.onmessage=e=>{try{if(e.data.cmd===\\\"load\\\"){Module[\\\"wasmModule\\\"]=e.data.wasmModule;Module[\\\"wasmMemory\\\"]=e.data.wasmMemory;Module[\\\"buffer\\\"]=Module[\\\"wasmMemory\\\"].buffer;Module[\\\"ENVIRONMENT_IS_PTHREAD\\\"]=true;if(typeof e.data.urlOrBlob==\\\"string\\\"){importScripts(e.data.urlOrBlob)}else{var objectUrl=URL.createObjectURL(e.data.urlOrBlob);importScripts(objectUrl);URL.revokeObjectURL(objectUrl)}ortWasmThreaded(Module).then(function(instance){Module=instance})}else if(e.data.cmd===\\\"run\\\"){Module[\\\"__performance_now_clock_drift\\\"]=performance.now()-e.data.time;Module[\\\"__emscripten_thread_init\\\"](e.data.pthread_ptr,/*isMainBrowserThread=*/0,/*isMainRuntimeThread=*/0,/*canBlock=*/1);Module[\\\"establishStackSpace\\\"]();Module[\\\"PThread\\\"].receiveObjectTransfer(e.data);Module[\\\"PThread\\\"].threadInitTLS();if(!initializedJS){pendingNotifiedProxyingQueues.forEach(queue=>{Module[\\\"executeNotifiedProxyingQueue\\\"](queue)});pendingNotifiedProxyingQueues=[];initializedJS=true}try{Module[\\\"invokeEntryPoint\\\"](e.data.start_routine,e.data.arg)}catch(ex){if(ex!=\\\"unwind\\\"){if(ex instanceof Module[\\\"ExitStatus\\\"]){if(Module[\\\"keepRuntimeAlive\\\"]()){}else{Module[\\\"__emscripten_thread_exit\\\"](ex.status)}}else{throw ex}}}}else if(e.data.cmd===\\\"cancel\\\"){if(Module[\\\"_pthread_self\\\"]()){Module[\\\"__emscripten_thread_exit\\\"](-1)}}else if(e.data.target===\\\"setimmediate\\\"){}else if(e.data.cmd===\\\"processProxyingQueue\\\"){if(initializedJS){Module[\\\"executeNotifiedProxyingQueue\\\"](e.data.queue)}else{pendingNotifiedProxyingQueues.push(e.data.queue)}}else{err(\\\"worker.js received unknown command \\\"+e.data.cmd);err(e.data)}}catch(ex){err(\\\"worker.js onmessage() captured an uncaught exception: \\\"+ex);if(ex&&ex.stack)err(ex.stack);if(Module[\\\"__emscripten_thread_crashed\\\"]){Module[\\\"__emscripten_thread_crashed\\\"]()}throw ex}};\\r\\n\";\n\n/***/ }),\n\n/***/ \"?63c8\":\n/*!********************!*\\\n  !*** fs (ignored) ***!\n  \\********************/\n/***/ (() => {\n\n/* (ignored) */\n\n/***/ }),\n\n/***/ \"?aedb\":\n/*!********************!*\\\n  !*** os (ignored) ***!\n  \\********************/\n/***/ (() => {\n\n/* (ignored) */\n\n/***/ }),\n\n/***/ \"?75c6\":\n/*!**********************!*\\\n  !*** path (ignored) ***!\n  \\**********************/\n/***/ (() => {\n\n/* (ignored) */\n\n/***/ }),\n\n/***/ \"?674f\":\n/*!****************************!*\\\n  !*** perf_hooks (ignored) ***!\n  \\****************************/\n/***/ (() => {\n\n/* (ignored) */\n\n/***/ }),\n\n/***/ \"?c6f7\":\n/*!********************************!*\\\n  !*** worker_threads (ignored) ***!\n  \\********************************/\n/***/ (() => {\n\n/* (ignored) */\n\n/***/ }),\n\n/***/ \"?7aa5\":\n/*!**********************!*\\\n  !*** path (ignored) ***!\n  \\**********************/\n/***/ (() => {\n\n/* (ignored) */\n\n/***/ })\n\n/******/ \t});\n/************************************************************************/\n/******/ \t// The module cache\n/******/ \tvar __webpack_module_cache__ = {};\n/******/ \t\n/******/ \t// The require function\n/******/ \tfunction __webpack_require__(moduleId) {\n/******/ \t\t// Check if module is in cache\n/******/ \t\tvar cachedModule = __webpack_module_cache__[moduleId];\n/******/ \t\tif (cachedModule !== undefined) {\n/******/ \t\t\treturn cachedModule.exports;\n/******/ \t\t}\n/******/ \t\t// Create a new module (and put it into the cache)\n/******/ \t\tvar module = __webpack_module_cache__[moduleId] = {\n/******/ \t\t\t// no module.id needed\n/******/ \t\t\t// no module.loaded needed\n/******/ \t\t\texports: {}\n/******/ \t\t};\n/******/ \t\n/******/ \t\t// Execute the module function\n/******/ \t\t__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n/******/ \t\n/******/ \t\t// Return the exports of the module\n/******/ \t\treturn module.exports;\n/******/ \t}\n/******/ \t\n/************************************************************************/\n/******/ \t/* webpack/runtime/global */\n/******/ \t(() => {\n/******/ \t\t__webpack_require__.g = (function() {\n/******/ \t\t\tif (typeof globalThis === 'object') return globalThis;\n/******/ \t\t\ttry {\n/******/ \t\t\t\treturn this || new Function('return this')();\n/******/ \t\t\t} catch (e) {\n/******/ \t\t\t\tif (typeof window === 'object') return window;\n/******/ \t\t\t}\n/******/ \t\t})();\n/******/ \t})();\n/******/ \t\n/************************************************************************/\nvar __webpack_exports__ = {};\n// This entry need to be wrapped in an IIFE because it need to be in strict mode.\n(() => {\n\"use strict\";\nvar exports = __webpack_exports__;\n/*!*****************************************************************************************************!*\\\n  !*** ./node_modules/ts-loader/index.js??ruleSet[1].rules[0].use[0]!./lib/wasm/proxy-worker/main.ts ***!\n  \\*****************************************************************************************************/\n\n// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nconst wasm_core_impl_1 = __webpack_require__(/*! ../wasm-core-impl */ \"./lib/wasm/wasm-core-impl.ts\");\nconst wasm_factory_1 = __webpack_require__(/*! ../wasm-factory */ \"./lib/wasm/wasm-factory.ts\");\nself.onmessage = (ev) => {\n    switch (ev.data.type) {\n        case 'init-wasm':\n            (0, wasm_factory_1.initializeWebAssembly)(ev.data.in)\n                .then(() => postMessage({ type: 'init-wasm' }), err => postMessage({ type: 'init-wasm', err }));\n            break;\n        case 'init-ort':\n            try {\n                const { numThreads, loggingLevel } = ev.data.in;\n                (0, wasm_core_impl_1.initOrt)(numThreads, loggingLevel);\n                postMessage({ type: 'init-ort' });\n            }\n            catch (err) {\n                postMessage({ type: 'init-ort', err });\n            }\n            break;\n        case 'create_allocate':\n            try {\n                const { model } = ev.data.in;\n                const modeldata = (0, wasm_core_impl_1.createSessionAllocate)(model);\n                postMessage({ type: 'create_allocate', out: modeldata });\n            }\n            catch (err) {\n                postMessage({ type: 'create_allocate', err });\n            }\n            break;\n        case 'create_finalize':\n            try {\n                const { modeldata, options } = ev.data.in;\n                const sessionMetadata = (0, wasm_core_impl_1.createSessionFinalize)(modeldata, options);\n                postMessage({ type: 'create_finalize', out: sessionMetadata });\n            }\n            catch (err) {\n                postMessage({ type: 'create_finalize', err });\n            }\n            break;\n        case 'create':\n            try {\n                const { model, options } = ev.data.in;\n                const sessionMetadata = (0, wasm_core_impl_1.createSession)(model, options);\n                postMessage({ type: 'create', out: sessionMetadata });\n            }\n            catch (err) {\n                postMessage({ type: 'create', err });\n            }\n            break;\n        case 'release':\n            try {\n                const handler = ev.data.in;\n                (0, wasm_core_impl_1.releaseSession)(handler);\n                postMessage({ type: 'release' });\n            }\n            catch (err) {\n                postMessage({ type: 'release', err });\n            }\n            break;\n        case 'run':\n            try {\n                const { sessionId, inputIndices, inputs, outputIndices, options } = ev.data.in;\n                const outputs = (0, wasm_core_impl_1.run)(sessionId, inputIndices, inputs, outputIndices, options);\n                postMessage({ type: 'run', out: outputs }, (0, wasm_core_impl_1.extractTransferableBuffers)(outputs));\n            }\n            catch (err) {\n                postMessage({ type: 'run', err });\n            }\n            break;\n        case 'end-profiling':\n            try {\n                const handler = ev.data.in;\n                (0, wasm_core_impl_1.endProfiling)(handler);\n                postMessage({ type: 'end-profiling' });\n            }\n            catch (err) {\n                postMessage({ type: 'end-profiling', err });\n            }\n            break;\n        default:\n    }\n};\n\n})();\n\n/******/ })()\n;\n", "Worker", undefined, undefined);
}


/***/ }),

/***/ "./node_modules/worker-loader/dist/runtime/inline.js":
/*!***********************************************************!*\
  !*** ./node_modules/worker-loader/dist/runtime/inline.js ***!
  \***********************************************************/
/***/ ((module) => {

"use strict";


/* eslint-env browser */

/* eslint-disable no-undef, no-use-before-define, new-cap */
module.exports = function (content, workerConstructor, workerOptions, url) {
  var globalScope = self || window;

  try {
    try {
      var blob;

      try {
        // New API
        blob = new globalScope.Blob([content]);
      } catch (e) {
        // BlobBuilder = Deprecated, but widely implemented
        var BlobBuilder = globalScope.BlobBuilder || globalScope.WebKitBlobBuilder || globalScope.MozBlobBuilder || globalScope.MSBlobBuilder;
        blob = new BlobBuilder();
        blob.append(content);
        blob = blob.getBlob();
      }

      var URL = globalScope.URL || globalScope.webkitURL;
      var objectURL = URL.createObjectURL(blob);
      var worker = new globalScope[workerConstructor](objectURL, workerOptions);
      URL.revokeObjectURL(objectURL);
      return worker;
    } catch (e) {
      return new globalScope[workerConstructor]("data:application/javascript,".concat(encodeURIComponent(content)), workerOptions);
    }
  } catch (e) {
    if (!url) {
      throw Error("Inline worker is not supported");
    }

    return new globalScope[workerConstructor](url, workerOptions);
  }
};

/***/ }),

/***/ "./lib/wasm/binding/ort-wasm-threaded.worker.js":
/*!******************************************************!*\
  !*** ./lib/wasm/binding/ort-wasm-threaded.worker.js ***!
  \******************************************************/
/***/ ((module) => {

"use strict";
module.exports = "\"use strict\";var Module={};var ENVIRONMENT_IS_NODE=typeof process==\"object\"&&typeof process.versions==\"object\"&&typeof process.versions.node==\"string\";if(ENVIRONMENT_IS_NODE){var nodeWorkerThreads=require(\"worker_threads\");var parentPort=nodeWorkerThreads.parentPort;parentPort.on(\"message\",data=>onmessage({data:data}));var fs=require(\"fs\");Object.assign(global,{self:global,require:require,Module:Module,location:{href:__filename},Worker:nodeWorkerThreads.Worker,importScripts:function(f){(0,eval)(fs.readFileSync(f,\"utf8\"))},postMessage:function(msg){parentPort.postMessage(msg)},performance:global.performance||{now:function(){return Date.now()}}})}var initializedJS=false;var pendingNotifiedProxyingQueues=[];function threadPrintErr(){var text=Array.prototype.slice.call(arguments).join(\" \");if(ENVIRONMENT_IS_NODE){fs.writeSync(2,text+\"\\n\");return}console.error(text)}function threadAlert(){var text=Array.prototype.slice.call(arguments).join(\" \");postMessage({cmd:\"alert\",text:text,threadId:Module[\"_pthread_self\"]()})}var err=threadPrintErr;self.alert=threadAlert;Module[\"instantiateWasm\"]=(info,receiveInstance)=>{var instance=new WebAssembly.Instance(Module[\"wasmModule\"],info);receiveInstance(instance);Module[\"wasmModule\"]=null;return instance.exports};self.onunhandledrejection=e=>{throw e.reason??e};self.onmessage=e=>{try{if(e.data.cmd===\"load\"){Module[\"wasmModule\"]=e.data.wasmModule;Module[\"wasmMemory\"]=e.data.wasmMemory;Module[\"buffer\"]=Module[\"wasmMemory\"].buffer;Module[\"ENVIRONMENT_IS_PTHREAD\"]=true;if(typeof e.data.urlOrBlob==\"string\"){importScripts(e.data.urlOrBlob)}else{var objectUrl=URL.createObjectURL(e.data.urlOrBlob);importScripts(objectUrl);URL.revokeObjectURL(objectUrl)}ortWasmThreaded(Module).then(function(instance){Module=instance})}else if(e.data.cmd===\"run\"){Module[\"__performance_now_clock_drift\"]=performance.now()-e.data.time;Module[\"__emscripten_thread_init\"](e.data.pthread_ptr,/*isMainBrowserThread=*/0,/*isMainRuntimeThread=*/0,/*canBlock=*/1);Module[\"establishStackSpace\"]();Module[\"PThread\"].receiveObjectTransfer(e.data);Module[\"PThread\"].threadInitTLS();if(!initializedJS){pendingNotifiedProxyingQueues.forEach(queue=>{Module[\"executeNotifiedProxyingQueue\"](queue)});pendingNotifiedProxyingQueues=[];initializedJS=true}try{Module[\"invokeEntryPoint\"](e.data.start_routine,e.data.arg)}catch(ex){if(ex!=\"unwind\"){if(ex instanceof Module[\"ExitStatus\"]){if(Module[\"keepRuntimeAlive\"]()){}else{Module[\"__emscripten_thread_exit\"](ex.status)}}else{throw ex}}}}else if(e.data.cmd===\"cancel\"){if(Module[\"_pthread_self\"]()){Module[\"__emscripten_thread_exit\"](-1)}}else if(e.data.target===\"setimmediate\"){}else if(e.data.cmd===\"processProxyingQueue\"){if(initializedJS){Module[\"executeNotifiedProxyingQueue\"](e.data.queue)}else{pendingNotifiedProxyingQueues.push(e.data.queue)}}else{err(\"worker.js received unknown command \"+e.data.cmd);err(e.data)}}catch(ex){err(\"worker.js onmessage() captured an uncaught exception: \"+ex);if(ex&&ex.stack)err(ex.stack);if(Module[\"__emscripten_thread_crashed\"]){Module[\"__emscripten_thread_crashed\"]()}throw ex}};\r\n";

/***/ }),

/***/ "?6c45":
/*!********************!*\
  !*** fs (ignored) ***!
  \********************/
/***/ (() => {

/* (ignored) */

/***/ }),

/***/ "?b3a2":
/*!**********************!*\
  !*** util (ignored) ***!
  \**********************/
/***/ (() => {

/* (ignored) */

/***/ }),

/***/ "?63c8":
/*!********************!*\
  !*** fs (ignored) ***!
  \********************/
/***/ (() => {

/* (ignored) */

/***/ }),

/***/ "?aedb":
/*!********************!*\
  !*** os (ignored) ***!
  \********************/
/***/ (() => {

/* (ignored) */

/***/ }),

/***/ "?75c6":
/*!**********************!*\
  !*** path (ignored) ***!
  \**********************/
/***/ (() => {

/* (ignored) */

/***/ }),

/***/ "?674f":
/*!****************************!*\
  !*** perf_hooks (ignored) ***!
  \****************************/
/***/ (() => {

/* (ignored) */

/***/ }),

/***/ "?c6f7":
/*!********************************!*\
  !*** worker_threads (ignored) ***!
  \********************************/
/***/ (() => {

/* (ignored) */

/***/ }),

/***/ "?295d":
/*!********************!*\
  !*** fs (ignored) ***!
  \********************/
/***/ (() => {

/* (ignored) */

/***/ }),

/***/ "?7aa5":
/*!**********************!*\
  !*** path (ignored) ***!
  \**********************/
/***/ (() => {

/* (ignored) */

/***/ }),

/***/ "?cf98":
/*!**********************!*\
  !*** util (ignored) ***!
  \**********************/
/***/ (() => {

/* (ignored) */

/***/ }),

/***/ "?0757":
/*!********************!*\
  !*** os (ignored) ***!
  \********************/
/***/ (() => {

/* (ignored) */

/***/ }),

/***/ "./node_modules/flatbuffers/js/flatbuffers.mjs":
/*!*****************************************************!*\
  !*** ./node_modules/flatbuffers/js/flatbuffers.mjs ***!
  \*****************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "flatbuffers": () => (/* binding */ flatbuffers)
/* harmony export */ });
/// @file
/// @addtogroup flatbuffers_javascript_api
/// @{
/// @cond FLATBUFFERS_INTERNAL

/**
 * @fileoverview
 *
 * Need to suppress 'global this' error so the Node.js export line doesn't cause
 * closure compile to error out.
 * @suppress {globalThis}
 */

/**
 * @const
 * @namespace
 */
var flatbuffers = {};

/**
 * @typedef {number}
 */
flatbuffers.Offset;

/**
 * @typedef {{
 *   bb: flatbuffers.ByteBuffer,
 *   bb_pos: number
 * }}
 */
flatbuffers.Table;

/**
 * @type {number}
 * @const
 */
flatbuffers.SIZEOF_SHORT = 2;

/**
 * @type {number}
 * @const
 */
flatbuffers.SIZEOF_INT = 4;

/**
 * @type {number}
 * @const
 */
flatbuffers.FILE_IDENTIFIER_LENGTH = 4;

/**
 * @type {number}
 * @const
 */
flatbuffers.SIZE_PREFIX_LENGTH = 4;

/**
 * @enum {number}
 */
flatbuffers.Encoding = {
  UTF8_BYTES: 1,
  UTF16_STRING: 2
};

/**
 * @type {Int32Array}
 * @const
 */
flatbuffers.int32 = new Int32Array(2);

/**
 * @type {Float32Array}
 * @const
 */
flatbuffers.float32 = new Float32Array(flatbuffers.int32.buffer);

/**
 * @type {Float64Array}
 * @const
 */
flatbuffers.float64 = new Float64Array(flatbuffers.int32.buffer);

/**
 * @type {boolean}
 * @const
 */
flatbuffers.isLittleEndian = new Uint16Array(new Uint8Array([1, 0]).buffer)[0] === 1;

////////////////////////////////////////////////////////////////////////////////

/**
 * @constructor
 * @param {number} low
 * @param {number} high
 */
flatbuffers.Long = function(low, high) {
  /**
   * @type {number}
   * @const
   */
  this.low = low | 0;

  /**
   * @type {number}
   * @const
   */
  this.high = high | 0;
};

/**
 * @param {number} low
 * @param {number} high
 * @returns {!flatbuffers.Long}
 */
flatbuffers.Long.create = function(low, high) {
  // Special-case zero to avoid GC overhead for default values
  return low == 0 && high == 0 ? flatbuffers.Long.ZERO : new flatbuffers.Long(low, high);
};

/**
 * @returns {number}
 */
flatbuffers.Long.prototype.toFloat64 = function() {
  return (this.low >>> 0) + this.high * 0x100000000;
};

/**
 * @param {flatbuffers.Long} other
 * @returns {boolean}
 */
flatbuffers.Long.prototype.equals = function(other) {
  return this.low == other.low && this.high == other.high;
};

/**
 * @type {!flatbuffers.Long}
 * @const
 */
flatbuffers.Long.ZERO = new flatbuffers.Long(0, 0);

/// @endcond
////////////////////////////////////////////////////////////////////////////////
/**
 * Create a FlatBufferBuilder.
 *
 * @constructor
 * @param {number=} opt_initial_size
 */
flatbuffers.Builder = function(opt_initial_size) {
  if (!opt_initial_size) {
    var initial_size = 1024;
  } else {
    var initial_size = opt_initial_size;
  }

  /**
   * @type {flatbuffers.ByteBuffer}
   * @private
   */
  this.bb = flatbuffers.ByteBuffer.allocate(initial_size);

  /**
   * Remaining space in the ByteBuffer.
   *
   * @type {number}
   * @private
   */
  this.space = initial_size;

  /**
   * Minimum alignment encountered so far.
   *
   * @type {number}
   * @private
   */
  this.minalign = 1;

  /**
   * The vtable for the current table.
   *
   * @type {Array.<number>}
   * @private
   */
  this.vtable = null;

  /**
   * The amount of fields we're actually using.
   *
   * @type {number}
   * @private
   */
  this.vtable_in_use = 0;

  /**
   * Whether we are currently serializing a table.
   *
   * @type {boolean}
   * @private
   */
  this.isNested = false;

  /**
   * Starting offset of the current struct/table.
   *
   * @type {number}
   * @private
   */
  this.object_start = 0;

  /**
   * List of offsets of all vtables.
   *
   * @type {Array.<number>}
   * @private
   */
  this.vtables = [];

  /**
   * For the current vector being built.
   *
   * @type {number}
   * @private
   */
  this.vector_num_elems = 0;

  /**
   * False omits default values from the serialized data
   *
   * @type {boolean}
   * @private
   */
  this.force_defaults = false;
};

flatbuffers.Builder.prototype.clear = function() {
  this.bb.clear();
  this.space = this.bb.capacity();
  this.minalign = 1;
  this.vtable = null;
  this.vtable_in_use = 0;
  this.isNested = false;
  this.object_start = 0;
  this.vtables = [];
  this.vector_num_elems = 0;
  this.force_defaults = false;
};

/**
 * In order to save space, fields that are set to their default value
 * don't get serialized into the buffer. Forcing defaults provides a
 * way to manually disable this optimization.
 *
 * @param {boolean} forceDefaults true always serializes default values
 */
flatbuffers.Builder.prototype.forceDefaults = function(forceDefaults) {
  this.force_defaults = forceDefaults;
};

/**
 * Get the ByteBuffer representing the FlatBuffer. Only call this after you've
 * called finish(). The actual data starts at the ByteBuffer's current position,
 * not necessarily at 0.
 *
 * @returns {flatbuffers.ByteBuffer}
 */
flatbuffers.Builder.prototype.dataBuffer = function() {
  return this.bb;
};

/**
 * Get the bytes representing the FlatBuffer. Only call this after you've
 * called finish().
 *
 * @returns {!Uint8Array}
 */
flatbuffers.Builder.prototype.asUint8Array = function() {
  return this.bb.bytes().subarray(this.bb.position(), this.bb.position() + this.offset());
};

/// @cond FLATBUFFERS_INTERNAL
/**
 * Prepare to write an element of `size` after `additional_bytes` have been
 * written, e.g. if you write a string, you need to align such the int length
 * field is aligned to 4 bytes, and the string data follows it directly. If all
 * you need to do is alignment, `additional_bytes` will be 0.
 *
 * @param {number} size This is the of the new element to write
 * @param {number} additional_bytes The padding size
 */
flatbuffers.Builder.prototype.prep = function(size, additional_bytes) {
  // Track the biggest thing we've ever aligned to.
  if (size > this.minalign) {
    this.minalign = size;
  }

  // Find the amount of alignment needed such that `size` is properly
  // aligned after `additional_bytes`
  var align_size = ((~(this.bb.capacity() - this.space + additional_bytes)) + 1) & (size - 1);

  // Reallocate the buffer if needed.
  while (this.space < align_size + size + additional_bytes) {
    var old_buf_size = this.bb.capacity();
    this.bb = flatbuffers.Builder.growByteBuffer(this.bb);
    this.space += this.bb.capacity() - old_buf_size;
  }

  this.pad(align_size);
};

/**
 * @param {number} byte_size
 */
flatbuffers.Builder.prototype.pad = function(byte_size) {
  for (var i = 0; i < byte_size; i++) {
    this.bb.writeInt8(--this.space, 0);
  }
};

/**
 * @param {number} value
 */
flatbuffers.Builder.prototype.writeInt8 = function(value) {
  this.bb.writeInt8(this.space -= 1, value);
};

/**
 * @param {number} value
 */
flatbuffers.Builder.prototype.writeInt16 = function(value) {
  this.bb.writeInt16(this.space -= 2, value);
};

/**
 * @param {number} value
 */
flatbuffers.Builder.prototype.writeInt32 = function(value) {
  this.bb.writeInt32(this.space -= 4, value);
};

/**
 * @param {flatbuffers.Long} value
 */
flatbuffers.Builder.prototype.writeInt64 = function(value) {
  this.bb.writeInt64(this.space -= 8, value);
};

/**
 * @param {number} value
 */
flatbuffers.Builder.prototype.writeFloat32 = function(value) {
  this.bb.writeFloat32(this.space -= 4, value);
};

/**
 * @param {number} value
 */
flatbuffers.Builder.prototype.writeFloat64 = function(value) {
  this.bb.writeFloat64(this.space -= 8, value);
};
/// @endcond

/**
 * Add an `int8` to the buffer, properly aligned, and grows the buffer (if necessary).
 * @param {number} value The `int8` to add the the buffer.
 */
flatbuffers.Builder.prototype.addInt8 = function(value) {
  this.prep(1, 0);
  this.writeInt8(value);
};

/**
 * Add an `int16` to the buffer, properly aligned, and grows the buffer (if necessary).
 * @param {number} value The `int16` to add the the buffer.
 */
flatbuffers.Builder.prototype.addInt16 = function(value) {
  this.prep(2, 0);
  this.writeInt16(value);
};

/**
 * Add an `int32` to the buffer, properly aligned, and grows the buffer (if necessary).
 * @param {number} value The `int32` to add the the buffer.
 */
flatbuffers.Builder.prototype.addInt32 = function(value) {
  this.prep(4, 0);
  this.writeInt32(value);
};

/**
 * Add an `int64` to the buffer, properly aligned, and grows the buffer (if necessary).
 * @param {flatbuffers.Long} value The `int64` to add the the buffer.
 */
flatbuffers.Builder.prototype.addInt64 = function(value) {
  this.prep(8, 0);
  this.writeInt64(value);
};

/**
 * Add a `float32` to the buffer, properly aligned, and grows the buffer (if necessary).
 * @param {number} value The `float32` to add the the buffer.
 */
flatbuffers.Builder.prototype.addFloat32 = function(value) {
  this.prep(4, 0);
  this.writeFloat32(value);
};

/**
 * Add a `float64` to the buffer, properly aligned, and grows the buffer (if necessary).
 * @param {number} value The `float64` to add the the buffer.
 */
flatbuffers.Builder.prototype.addFloat64 = function(value) {
  this.prep(8, 0);
  this.writeFloat64(value);
};

/// @cond FLATBUFFERS_INTERNAL
/**
 * @param {number} voffset
 * @param {number} value
 * @param {number} defaultValue
 */
flatbuffers.Builder.prototype.addFieldInt8 = function(voffset, value, defaultValue) {
  if (this.force_defaults || value != defaultValue) {
    this.addInt8(value);
    this.slot(voffset);
  }
};

/**
 * @param {number} voffset
 * @param {number} value
 * @param {number} defaultValue
 */
flatbuffers.Builder.prototype.addFieldInt16 = function(voffset, value, defaultValue) {
  if (this.force_defaults || value != defaultValue) {
    this.addInt16(value);
    this.slot(voffset);
  }
};

/**
 * @param {number} voffset
 * @param {number} value
 * @param {number} defaultValue
 */
flatbuffers.Builder.prototype.addFieldInt32 = function(voffset, value, defaultValue) {
  if (this.force_defaults || value != defaultValue) {
    this.addInt32(value);
    this.slot(voffset);
  }
};

/**
 * @param {number} voffset
 * @param {flatbuffers.Long} value
 * @param {flatbuffers.Long} defaultValue
 */
flatbuffers.Builder.prototype.addFieldInt64 = function(voffset, value, defaultValue) {
  if (this.force_defaults || !value.equals(defaultValue)) {
    this.addInt64(value);
    this.slot(voffset);
  }
};

/**
 * @param {number} voffset
 * @param {number} value
 * @param {number} defaultValue
 */
flatbuffers.Builder.prototype.addFieldFloat32 = function(voffset, value, defaultValue) {
  if (this.force_defaults || value != defaultValue) {
    this.addFloat32(value);
    this.slot(voffset);
  }
};

/**
 * @param {number} voffset
 * @param {number} value
 * @param {number} defaultValue
 */
flatbuffers.Builder.prototype.addFieldFloat64 = function(voffset, value, defaultValue) {
  if (this.force_defaults || value != defaultValue) {
    this.addFloat64(value);
    this.slot(voffset);
  }
};

/**
 * @param {number} voffset
 * @param {flatbuffers.Offset} value
 * @param {flatbuffers.Offset} defaultValue
 */
flatbuffers.Builder.prototype.addFieldOffset = function(voffset, value, defaultValue) {
  if (this.force_defaults || value != defaultValue) {
    this.addOffset(value);
    this.slot(voffset);
  }
};

/**
 * Structs are stored inline, so nothing additional is being added. `d` is always 0.
 *
 * @param {number} voffset
 * @param {flatbuffers.Offset} value
 * @param {flatbuffers.Offset} defaultValue
 */
flatbuffers.Builder.prototype.addFieldStruct = function(voffset, value, defaultValue) {
  if (value != defaultValue) {
    this.nested(value);
    this.slot(voffset);
  }
};

/**
 * Structures are always stored inline, they need to be created right
 * where they're used.  You'll get this assertion failure if you
 * created it elsewhere.
 *
 * @param {flatbuffers.Offset} obj The offset of the created object
 */
flatbuffers.Builder.prototype.nested = function(obj) {
  if (obj != this.offset()) {
    throw new Error('FlatBuffers: struct must be serialized inline.');
  }
};

/**
 * Should not be creating any other object, string or vector
 * while an object is being constructed
 */
flatbuffers.Builder.prototype.notNested = function() {
  if (this.isNested) {
    throw new Error('FlatBuffers: object serialization must not be nested.');
  }
};

/**
 * Set the current vtable at `voffset` to the current location in the buffer.
 *
 * @param {number} voffset
 */
flatbuffers.Builder.prototype.slot = function(voffset) {
  this.vtable[voffset] = this.offset();
};

/**
 * @returns {flatbuffers.Offset} Offset relative to the end of the buffer.
 */
flatbuffers.Builder.prototype.offset = function() {
  return this.bb.capacity() - this.space;
};

/**
 * Doubles the size of the backing ByteBuffer and copies the old data towards
 * the end of the new buffer (since we build the buffer backwards).
 *
 * @param {flatbuffers.ByteBuffer} bb The current buffer with the existing data
 * @returns {!flatbuffers.ByteBuffer} A new byte buffer with the old data copied
 * to it. The data is located at the end of the buffer.
 *
 * uint8Array.set() formally takes {Array<number>|ArrayBufferView}, so to pass
 * it a uint8Array we need to suppress the type check:
 * @suppress {checkTypes}
 */
flatbuffers.Builder.growByteBuffer = function(bb) {
  var old_buf_size = bb.capacity();

  // Ensure we don't grow beyond what fits in an int.
  if (old_buf_size & 0xC0000000) {
    throw new Error('FlatBuffers: cannot grow buffer beyond 2 gigabytes.');
  }

  var new_buf_size = old_buf_size << 1;
  var nbb = flatbuffers.ByteBuffer.allocate(new_buf_size);
  nbb.setPosition(new_buf_size - old_buf_size);
  nbb.bytes().set(bb.bytes(), new_buf_size - old_buf_size);
  return nbb;
};
/// @endcond

/**
 * Adds on offset, relative to where it will be written.
 *
 * @param {flatbuffers.Offset} offset The offset to add.
 */
flatbuffers.Builder.prototype.addOffset = function(offset) {
  this.prep(flatbuffers.SIZEOF_INT, 0); // Ensure alignment is already done.
  this.writeInt32(this.offset() - offset + flatbuffers.SIZEOF_INT);
};

/// @cond FLATBUFFERS_INTERNAL
/**
 * Start encoding a new object in the buffer.  Users will not usually need to
 * call this directly. The FlatBuffers compiler will generate helper methods
 * that call this method internally.
 *
 * @param {number} numfields
 */
flatbuffers.Builder.prototype.startObject = function(numfields) {
  this.notNested();
  if (this.vtable == null) {
    this.vtable = [];
  }
  this.vtable_in_use = numfields;
  for (var i = 0; i < numfields; i++) {
    this.vtable[i] = 0; // This will push additional elements as needed
  }
  this.isNested = true;
  this.object_start = this.offset();
};

/**
 * Finish off writing the object that is under construction.
 *
 * @returns {flatbuffers.Offset} The offset to the object inside `dataBuffer`
 */
flatbuffers.Builder.prototype.endObject = function() {
  if (this.vtable == null || !this.isNested) {
    throw new Error('FlatBuffers: endObject called without startObject');
  }

  this.addInt32(0);
  var vtableloc = this.offset();

  // Trim trailing zeroes.
  var i = this.vtable_in_use - 1;
  for (; i >= 0 && this.vtable[i] == 0; i--) {}
  var trimmed_size = i + 1;

  // Write out the current vtable.
  for (; i >= 0; i--) {
    // Offset relative to the start of the table.
    this.addInt16(this.vtable[i] != 0 ? vtableloc - this.vtable[i] : 0);
  }

  var standard_fields = 2; // The fields below:
  this.addInt16(vtableloc - this.object_start);
  var len = (trimmed_size + standard_fields) * flatbuffers.SIZEOF_SHORT;
  this.addInt16(len);

  // Search for an existing vtable that matches the current one.
  var existing_vtable = 0;
  var vt1 = this.space;
outer_loop:
  for (i = 0; i < this.vtables.length; i++) {
    var vt2 = this.bb.capacity() - this.vtables[i];
    if (len == this.bb.readInt16(vt2)) {
      for (var j = flatbuffers.SIZEOF_SHORT; j < len; j += flatbuffers.SIZEOF_SHORT) {
        if (this.bb.readInt16(vt1 + j) != this.bb.readInt16(vt2 + j)) {
          continue outer_loop;
        }
      }
      existing_vtable = this.vtables[i];
      break;
    }
  }

  if (existing_vtable) {
    // Found a match:
    // Remove the current vtable.
    this.space = this.bb.capacity() - vtableloc;

    // Point table to existing vtable.
    this.bb.writeInt32(this.space, existing_vtable - vtableloc);
  } else {
    // No match:
    // Add the location of the current vtable to the list of vtables.
    this.vtables.push(this.offset());

    // Point table to current vtable.
    this.bb.writeInt32(this.bb.capacity() - vtableloc, this.offset() - vtableloc);
  }

  this.isNested = false;
  return vtableloc;
};
/// @endcond

/**
 * Finalize a buffer, poiting to the given `root_table`.
 *
 * @param {flatbuffers.Offset} root_table
 * @param {string=} opt_file_identifier
 * @param {boolean=} opt_size_prefix
 */
flatbuffers.Builder.prototype.finish = function(root_table, opt_file_identifier, opt_size_prefix) {
  var size_prefix = opt_size_prefix ? flatbuffers.SIZE_PREFIX_LENGTH : 0;
  if (opt_file_identifier) {
    var file_identifier = opt_file_identifier;
    this.prep(this.minalign, flatbuffers.SIZEOF_INT +
      flatbuffers.FILE_IDENTIFIER_LENGTH + size_prefix);
    if (file_identifier.length != flatbuffers.FILE_IDENTIFIER_LENGTH) {
      throw new Error('FlatBuffers: file identifier must be length ' +
        flatbuffers.FILE_IDENTIFIER_LENGTH);
    }
    for (var i = flatbuffers.FILE_IDENTIFIER_LENGTH - 1; i >= 0; i--) {
      this.writeInt8(file_identifier.charCodeAt(i));
    }
  }
  this.prep(this.minalign, flatbuffers.SIZEOF_INT + size_prefix);
  this.addOffset(root_table);
  if (size_prefix) {
    this.addInt32(this.bb.capacity() - this.space);
  }
  this.bb.setPosition(this.space);
};

/**
 * Finalize a size prefixed buffer, pointing to the given `root_table`.
 *
 * @param {flatbuffers.Offset} root_table
 * @param {string=} opt_file_identifier
 */
flatbuffers.Builder.prototype.finishSizePrefixed = function (root_table, opt_file_identifier) {
  this.finish(root_table, opt_file_identifier, true);
};

/// @cond FLATBUFFERS_INTERNAL
/**
 * This checks a required field has been set in a given table that has
 * just been constructed.
 *
 * @param {flatbuffers.Offset} table
 * @param {number} field
 */
flatbuffers.Builder.prototype.requiredField = function(table, field) {
  var table_start = this.bb.capacity() - table;
  var vtable_start = table_start - this.bb.readInt32(table_start);
  var ok = this.bb.readInt16(vtable_start + field) != 0;

  // If this fails, the caller will show what field needs to be set.
  if (!ok) {
    throw new Error('FlatBuffers: field ' + field + ' must be set');
  }
};

/**
 * Start a new array/vector of objects.  Users usually will not call
 * this directly. The FlatBuffers compiler will create a start/end
 * method for vector types in generated code.
 *
 * @param {number} elem_size The size of each element in the array
 * @param {number} num_elems The number of elements in the array
 * @param {number} alignment The alignment of the array
 */
flatbuffers.Builder.prototype.startVector = function(elem_size, num_elems, alignment) {
  this.notNested();
  this.vector_num_elems = num_elems;
  this.prep(flatbuffers.SIZEOF_INT, elem_size * num_elems);
  this.prep(alignment, elem_size * num_elems); // Just in case alignment > int.
};

/**
 * Finish off the creation of an array and all its elements. The array must be
 * created with `startVector`.
 *
 * @returns {flatbuffers.Offset} The offset at which the newly created array
 * starts.
 */
flatbuffers.Builder.prototype.endVector = function() {
  this.writeInt32(this.vector_num_elems);
  return this.offset();
};
/// @endcond

/**
 * Encode the string `s` in the buffer using UTF-8. If a Uint8Array is passed
 * instead of a string, it is assumed to contain valid UTF-8 encoded data.
 *
 * @param {string|Uint8Array} s The string to encode
 * @return {flatbuffers.Offset} The offset in the buffer where the encoded string starts
 */
flatbuffers.Builder.prototype.createString = function(s) {
  if (s instanceof Uint8Array) {
    var utf8 = s;
  } else {
    var utf8 = [];
    var i = 0;

    while (i < s.length) {
      var codePoint;

      // Decode UTF-16
      var a = s.charCodeAt(i++);
      if (a < 0xD800 || a >= 0xDC00) {
        codePoint = a;
      } else {
        var b = s.charCodeAt(i++);
        codePoint = (a << 10) + b + (0x10000 - (0xD800 << 10) - 0xDC00);
      }

      // Encode UTF-8
      if (codePoint < 0x80) {
        utf8.push(codePoint);
      } else {
        if (codePoint < 0x800) {
          utf8.push(((codePoint >> 6) & 0x1F) | 0xC0);
        } else {
          if (codePoint < 0x10000) {
            utf8.push(((codePoint >> 12) & 0x0F) | 0xE0);
          } else {
            utf8.push(
              ((codePoint >> 18) & 0x07) | 0xF0,
              ((codePoint >> 12) & 0x3F) | 0x80);
          }
          utf8.push(((codePoint >> 6) & 0x3F) | 0x80);
        }
        utf8.push((codePoint & 0x3F) | 0x80);
      }
    }
  }

  this.addInt8(0);
  this.startVector(1, utf8.length, 1);
  this.bb.setPosition(this.space -= utf8.length);
  for (var i = 0, offset = this.space, bytes = this.bb.bytes(); i < utf8.length; i++) {
    bytes[offset++] = utf8[i];
  }
  return this.endVector();
};

/**
 * A helper function to avoid generated code depending on this file directly.
 *
 * @param {number} low
 * @param {number} high
 * @returns {!flatbuffers.Long}
 */
flatbuffers.Builder.prototype.createLong = function(low, high) {
  return flatbuffers.Long.create(low, high);
};
////////////////////////////////////////////////////////////////////////////////
/// @cond FLATBUFFERS_INTERNAL
/**
 * Create a new ByteBuffer with a given array of bytes (`Uint8Array`).
 *
 * @constructor
 * @param {Uint8Array} bytes
 */
flatbuffers.ByteBuffer = function(bytes) {
  /**
   * @type {Uint8Array}
   * @private
   */
  this.bytes_ = bytes;

  /**
   * @type {number}
   * @private
   */
  this.position_ = 0;
};

/**
 * Create and allocate a new ByteBuffer with a given size.
 *
 * @param {number} byte_size
 * @returns {!flatbuffers.ByteBuffer}
 */
flatbuffers.ByteBuffer.allocate = function(byte_size) {
  return new flatbuffers.ByteBuffer(new Uint8Array(byte_size));
};

flatbuffers.ByteBuffer.prototype.clear = function() {
  this.position_ = 0;
};

/**
 * Get the underlying `Uint8Array`.
 *
 * @returns {Uint8Array}
 */
flatbuffers.ByteBuffer.prototype.bytes = function() {
  return this.bytes_;
};

/**
 * Get the buffer's position.
 *
 * @returns {number}
 */
flatbuffers.ByteBuffer.prototype.position = function() {
  return this.position_;
};

/**
 * Set the buffer's position.
 *
 * @param {number} position
 */
flatbuffers.ByteBuffer.prototype.setPosition = function(position) {
  this.position_ = position;
};

/**
 * Get the buffer's capacity.
 *
 * @returns {number}
 */
flatbuffers.ByteBuffer.prototype.capacity = function() {
  return this.bytes_.length;
};

/**
 * @param {number} offset
 * @returns {number}
 */
flatbuffers.ByteBuffer.prototype.readInt8 = function(offset) {
  return this.readUint8(offset) << 24 >> 24;
};

/**
 * @param {number} offset
 * @returns {number}
 */
flatbuffers.ByteBuffer.prototype.readUint8 = function(offset) {
  return this.bytes_[offset];
};

/**
 * @param {number} offset
 * @returns {number}
 */
flatbuffers.ByteBuffer.prototype.readInt16 = function(offset) {
  return this.readUint16(offset) << 16 >> 16;
};

/**
 * @param {number} offset
 * @returns {number}
 */
flatbuffers.ByteBuffer.prototype.readUint16 = function(offset) {
  return this.bytes_[offset] | this.bytes_[offset + 1] << 8;
};

/**
 * @param {number} offset
 * @returns {number}
 */
flatbuffers.ByteBuffer.prototype.readInt32 = function(offset) {
  return this.bytes_[offset] | this.bytes_[offset + 1] << 8 | this.bytes_[offset + 2] << 16 | this.bytes_[offset + 3] << 24;
};

/**
 * @param {number} offset
 * @returns {number}
 */
flatbuffers.ByteBuffer.prototype.readUint32 = function(offset) {
  return this.readInt32(offset) >>> 0;
};

/**
 * @param {number} offset
 * @returns {!flatbuffers.Long}
 */
flatbuffers.ByteBuffer.prototype.readInt64 = function(offset) {
  return new flatbuffers.Long(this.readInt32(offset), this.readInt32(offset + 4));
};

/**
 * @param {number} offset
 * @returns {!flatbuffers.Long}
 */
flatbuffers.ByteBuffer.prototype.readUint64 = function(offset) {
  return new flatbuffers.Long(this.readUint32(offset), this.readUint32(offset + 4));
};

/**
 * @param {number} offset
 * @returns {number}
 */
flatbuffers.ByteBuffer.prototype.readFloat32 = function(offset) {
  flatbuffers.int32[0] = this.readInt32(offset);
  return flatbuffers.float32[0];
};

/**
 * @param {number} offset
 * @returns {number}
 */
flatbuffers.ByteBuffer.prototype.readFloat64 = function(offset) {
  flatbuffers.int32[flatbuffers.isLittleEndian ? 0 : 1] = this.readInt32(offset);
  flatbuffers.int32[flatbuffers.isLittleEndian ? 1 : 0] = this.readInt32(offset + 4);
  return flatbuffers.float64[0];
};

/**
 * @param {number} offset
 * @param {number|boolean} value
 */
flatbuffers.ByteBuffer.prototype.writeInt8 = function(offset, value) {
  this.bytes_[offset] = /** @type {number} */(value);
};

/**
 * @param {number} offset
 * @param {number} value
 */
flatbuffers.ByteBuffer.prototype.writeUint8 = function(offset, value) {
  this.bytes_[offset] = value;
};

/**
 * @param {number} offset
 * @param {number} value
 */
flatbuffers.ByteBuffer.prototype.writeInt16 = function(offset, value) {
  this.bytes_[offset] = value;
  this.bytes_[offset + 1] = value >> 8;
};

/**
 * @param {number} offset
 * @param {number} value
 */
flatbuffers.ByteBuffer.prototype.writeUint16 = function(offset, value) {
    this.bytes_[offset] = value;
    this.bytes_[offset + 1] = value >> 8;
};

/**
 * @param {number} offset
 * @param {number} value
 */
flatbuffers.ByteBuffer.prototype.writeInt32 = function(offset, value) {
  this.bytes_[offset] = value;
  this.bytes_[offset + 1] = value >> 8;
  this.bytes_[offset + 2] = value >> 16;
  this.bytes_[offset + 3] = value >> 24;
};

/**
 * @param {number} offset
 * @param {number} value
 */
flatbuffers.ByteBuffer.prototype.writeUint32 = function(offset, value) {
    this.bytes_[offset] = value;
    this.bytes_[offset + 1] = value >> 8;
    this.bytes_[offset + 2] = value >> 16;
    this.bytes_[offset + 3] = value >> 24;
};

/**
 * @param {number} offset
 * @param {flatbuffers.Long} value
 */
flatbuffers.ByteBuffer.prototype.writeInt64 = function(offset, value) {
  this.writeInt32(offset, value.low);
  this.writeInt32(offset + 4, value.high);
};

/**
 * @param {number} offset
 * @param {flatbuffers.Long} value
 */
flatbuffers.ByteBuffer.prototype.writeUint64 = function(offset, value) {
    this.writeUint32(offset, value.low);
    this.writeUint32(offset + 4, value.high);
};

/**
 * @param {number} offset
 * @param {number} value
 */
flatbuffers.ByteBuffer.prototype.writeFloat32 = function(offset, value) {
  flatbuffers.float32[0] = value;
  this.writeInt32(offset, flatbuffers.int32[0]);
};

/**
 * @param {number} offset
 * @param {number} value
 */
flatbuffers.ByteBuffer.prototype.writeFloat64 = function(offset, value) {
  flatbuffers.float64[0] = value;
  this.writeInt32(offset, flatbuffers.int32[flatbuffers.isLittleEndian ? 0 : 1]);
  this.writeInt32(offset + 4, flatbuffers.int32[flatbuffers.isLittleEndian ? 1 : 0]);
};

/**
 * Return the file identifier.   Behavior is undefined for FlatBuffers whose
 * schema does not include a file_identifier (likely points at padding or the
 * start of a the root vtable).
 * @returns {string}
 */
flatbuffers.ByteBuffer.prototype.getBufferIdentifier = function() {
  if (this.bytes_.length < this.position_ + flatbuffers.SIZEOF_INT +
      flatbuffers.FILE_IDENTIFIER_LENGTH) {
    throw new Error(
        'FlatBuffers: ByteBuffer is too short to contain an identifier.');
  }
  var result = "";
  for (var i = 0; i < flatbuffers.FILE_IDENTIFIER_LENGTH; i++) {
    result += String.fromCharCode(
        this.readInt8(this.position_ + flatbuffers.SIZEOF_INT + i));
  }
  return result;
};

/**
 * Look up a field in the vtable, return an offset into the object, or 0 if the
 * field is not present.
 *
 * @param {number} bb_pos
 * @param {number} vtable_offset
 * @returns {number}
 */
flatbuffers.ByteBuffer.prototype.__offset = function(bb_pos, vtable_offset) {
  var vtable = bb_pos - this.readInt32(bb_pos);
  return vtable_offset < this.readInt16(vtable) ? this.readInt16(vtable + vtable_offset) : 0;
};

/**
 * Initialize any Table-derived type to point to the union at the given offset.
 *
 * @param {flatbuffers.Table} t
 * @param {number} offset
 * @returns {flatbuffers.Table}
 */
flatbuffers.ByteBuffer.prototype.__union = function(t, offset) {
  t.bb_pos = offset + this.readInt32(offset);
  t.bb = this;
  return t;
};

/**
 * Create a JavaScript string from UTF-8 data stored inside the FlatBuffer.
 * This allocates a new string and converts to wide chars upon each access.
 *
 * To avoid the conversion to UTF-16, pass flatbuffers.Encoding.UTF8_BYTES as
 * the "optionalEncoding" argument. This is useful for avoiding conversion to
 * and from UTF-16 when the data will just be packaged back up in another
 * FlatBuffer later on.
 *
 * @param {number} offset
 * @param {flatbuffers.Encoding=} opt_encoding Defaults to UTF16_STRING
 * @returns {string|!Uint8Array}
 */
flatbuffers.ByteBuffer.prototype.__string = function(offset, opt_encoding) {
  offset += this.readInt32(offset);

  var length = this.readInt32(offset);
  var result = '';
  var i = 0;

  offset += flatbuffers.SIZEOF_INT;

  if (opt_encoding === flatbuffers.Encoding.UTF8_BYTES) {
    return this.bytes_.subarray(offset, offset + length);
  }

  while (i < length) {
    var codePoint;

    // Decode UTF-8
    var a = this.readUint8(offset + i++);
    if (a < 0xC0) {
      codePoint = a;
    } else {
      var b = this.readUint8(offset + i++);
      if (a < 0xE0) {
        codePoint =
          ((a & 0x1F) << 6) |
          (b & 0x3F);
      } else {
        var c = this.readUint8(offset + i++);
        if (a < 0xF0) {
          codePoint =
            ((a & 0x0F) << 12) |
            ((b & 0x3F) << 6) |
            (c & 0x3F);
        } else {
          var d = this.readUint8(offset + i++);
          codePoint =
            ((a & 0x07) << 18) |
            ((b & 0x3F) << 12) |
            ((c & 0x3F) << 6) |
            (d & 0x3F);
        }
      }
    }

    // Encode UTF-16
    if (codePoint < 0x10000) {
      result += String.fromCharCode(codePoint);
    } else {
      codePoint -= 0x10000;
      result += String.fromCharCode(
        (codePoint >> 10) + 0xD800,
        (codePoint & ((1 << 10) - 1)) + 0xDC00);
    }
  }

  return result;
};

/**
 * Retrieve the relative offset stored at "offset"
 * @param {number} offset
 * @returns {number}
 */
flatbuffers.ByteBuffer.prototype.__indirect = function(offset) {
  return offset + this.readInt32(offset);
};

/**
 * Get the start of data of a vector whose offset is stored at "offset" in this object.
 *
 * @param {number} offset
 * @returns {number}
 */
flatbuffers.ByteBuffer.prototype.__vector = function(offset) {
  return offset + this.readInt32(offset) + flatbuffers.SIZEOF_INT; // data starts after the length
};

/**
 * Get the length of a vector whose offset is stored at "offset" in this object.
 *
 * @param {number} offset
 * @returns {number}
 */
flatbuffers.ByteBuffer.prototype.__vector_len = function(offset) {
  return this.readInt32(offset + this.readInt32(offset));
};

/**
 * @param {string} ident
 * @returns {boolean}
 */
flatbuffers.ByteBuffer.prototype.__has_identifier = function(ident) {
  if (ident.length != flatbuffers.FILE_IDENTIFIER_LENGTH) {
    throw new Error('FlatBuffers: file identifier must be length ' +
                    flatbuffers.FILE_IDENTIFIER_LENGTH);
  }
  for (var i = 0; i < flatbuffers.FILE_IDENTIFIER_LENGTH; i++) {
    if (ident.charCodeAt(i) != this.readInt8(this.position_ + flatbuffers.SIZEOF_INT + i)) {
      return false;
    }
  }
  return true;
};

/**
 * A helper function to avoid generated code depending on this file directly.
 *
 * @param {number} low
 * @param {number} high
 * @returns {!flatbuffers.Long}
 */
flatbuffers.ByteBuffer.prototype.createLong = function(low, high) {
  return flatbuffers.Long.create(low, high);
};

// Exports for Node.js and RequireJS


/// @endcond
/// @}


/***/ })

/******/ 	});
/************************************************************************/
/******/ 	// The module cache
/******/ 	var __webpack_module_cache__ = {};
/******/ 	
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/ 		// Check if module is in cache
/******/ 		var cachedModule = __webpack_module_cache__[moduleId];
/******/ 		if (cachedModule !== undefined) {
/******/ 			return cachedModule.exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = __webpack_module_cache__[moduleId] = {
/******/ 			// no module.id needed
/******/ 			// no module.loaded needed
/******/ 			exports: {}
/******/ 		};
/******/ 	
/******/ 		// Execute the module function
/******/ 		__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ 	
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/ 	
/************************************************************************/
/******/ 	/* webpack/runtime/compat get default export */
/******/ 	(() => {
/******/ 		// getDefaultExport function for compatibility with non-harmony modules
/******/ 		__webpack_require__.n = (module) => {
/******/ 			var getter = module && module.__esModule ?
/******/ 				() => (module['default']) :
/******/ 				() => (module);
/******/ 			__webpack_require__.d(getter, { a: getter });
/******/ 			return getter;
/******/ 		};
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/define property getters */
/******/ 	(() => {
/******/ 		// define getter functions for harmony exports
/******/ 		__webpack_require__.d = (exports, definition) => {
/******/ 			for(var key in definition) {
/******/ 				if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
/******/ 					Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ 				}
/******/ 			}
/******/ 		};
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/global */
/******/ 	(() => {
/******/ 		__webpack_require__.g = (function() {
/******/ 			if (typeof globalThis === 'object') return globalThis;
/******/ 			try {
/******/ 				return this || new Function('return this')();
/******/ 			} catch (e) {
/******/ 				if (typeof window === 'object') return window;
/******/ 			}
/******/ 		})();
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/hasOwnProperty shorthand */
/******/ 	(() => {
/******/ 		__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/make namespace object */
/******/ 	(() => {
/******/ 		// define __esModule on exports
/******/ 		__webpack_require__.r = (exports) => {
/******/ 			if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ 				Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ 			}
/******/ 			Object.defineProperty(exports, '__esModule', { value: true });
/******/ 		};
/******/ 	})();
/******/ 	
/************************************************************************/
/******/ 	
/******/ 	// startup
/******/ 	// Load entry module and return exports
/******/ 	// This entry module is referenced by other modules so it can't be inlined
/******/ 	var __webpack_exports__ = __webpack_require__("./lib/index.ts");
/******/ 	
/******/ 	return __webpack_exports__;
/******/ })()
;
});