summaryrefslogtreecommitdiff
path: root/frontend-old/node_modules/@firebase/ai/dist/index.cjs.js
blob: 83ab94e0c2a15a10f6a63d0af66533058e14e973 (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
'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var app = require('@firebase/app');
var component = require('@firebase/component');
var util = require('@firebase/util');
var logger$1 = require('@firebase/logger');

var name = "@firebase/ai";
var version = "2.5.0";

/**
 * @license
 * Copyright 2024 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
const AI_TYPE = 'AI';
const DEFAULT_LOCATION = 'us-central1';
const DEFAULT_DOMAIN = 'firebasevertexai.googleapis.com';
const DEFAULT_API_VERSION = 'v1beta';
const PACKAGE_VERSION = version;
const LANGUAGE_TAG = 'gl-js';
const DEFAULT_FETCH_TIMEOUT_MS = 180 * 1000;
/**
 * Defines the name of the default in-cloud model to use for hybrid inference.
 */
const DEFAULT_HYBRID_IN_CLOUD_MODEL = 'gemini-2.0-flash-lite';

/**
 * @license
 * Copyright 2024 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Error class for the Firebase AI SDK.
 *
 * @public
 */
class AIError extends util.FirebaseError {
    /**
     * Constructs a new instance of the `AIError` class.
     *
     * @param code - The error code from {@link (AIErrorCode:type)}.
     * @param message - A human-readable message describing the error.
     * @param customErrorData - Optional error data.
     */
    constructor(code, message, customErrorData) {
        // Match error format used by FirebaseError from ErrorFactory
        const service = AI_TYPE;
        const fullCode = `${service}/${code}`;
        const fullMessage = `${service}: ${message} (${fullCode})`;
        super(code, fullMessage);
        this.code = code;
        this.customErrorData = customErrorData;
        // FirebaseError initializes a stack trace, but it assumes the error is created from the error
        // factory. Since we break this assumption, we set the stack trace to be originating from this
        // constructor.
        // This is only supported in V8.
        if (Error.captureStackTrace) {
            // Allows us to initialize the stack trace without including the constructor itself at the
            // top level of the stack trace.
            Error.captureStackTrace(this, AIError);
        }
        // Allows instanceof AIError in ES5/ES6
        // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work
        // TODO(dlarocque): Replace this with `new.target`: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#support-for-newtarget
        //                   which we can now use since we no longer target ES5.
        Object.setPrototypeOf(this, AIError.prototype);
        // Since Error is an interface, we don't inherit toString and so we define it ourselves.
        this.toString = () => fullMessage;
    }
}

/**
 * @license
 * Copyright 2024 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Possible roles.
 * @public
 */
const POSSIBLE_ROLES = ['user', 'model', 'function', 'system'];
/**
 * Harm categories that would cause prompts or candidates to be blocked.
 * @public
 */
const HarmCategory = {
    HARM_CATEGORY_HATE_SPEECH: 'HARM_CATEGORY_HATE_SPEECH',
    HARM_CATEGORY_SEXUALLY_EXPLICIT: 'HARM_CATEGORY_SEXUALLY_EXPLICIT',
    HARM_CATEGORY_HARASSMENT: 'HARM_CATEGORY_HARASSMENT',
    HARM_CATEGORY_DANGEROUS_CONTENT: 'HARM_CATEGORY_DANGEROUS_CONTENT'
};
/**
 * Threshold above which a prompt or candidate will be blocked.
 * @public
 */
const HarmBlockThreshold = {
    /**
     * Content with `NEGLIGIBLE` will be allowed.
     */
    BLOCK_LOW_AND_ABOVE: 'BLOCK_LOW_AND_ABOVE',
    /**
     * Content with `NEGLIGIBLE` and `LOW` will be allowed.
     */
    BLOCK_MEDIUM_AND_ABOVE: 'BLOCK_MEDIUM_AND_ABOVE',
    /**
     * Content with `NEGLIGIBLE`, `LOW`, and `MEDIUM` will be allowed.
     */
    BLOCK_ONLY_HIGH: 'BLOCK_ONLY_HIGH',
    /**
     * All content will be allowed.
     */
    BLOCK_NONE: 'BLOCK_NONE',
    /**
     * All content will be allowed. This is the same as `BLOCK_NONE`, but the metadata corresponding
     * to the {@link (HarmCategory:type)} will not be present in the response.
     */
    OFF: 'OFF'
};
/**
 * This property is not supported in the Gemini Developer API ({@link GoogleAIBackend}).
 *
 * @public
 */
const HarmBlockMethod = {
    /**
     * The harm block method uses both probability and severity scores.
     */
    SEVERITY: 'SEVERITY',
    /**
     * The harm block method uses the probability score.
     */
    PROBABILITY: 'PROBABILITY'
};
/**
 * Probability that a prompt or candidate matches a harm category.
 * @public
 */
const HarmProbability = {
    /**
     * Content has a negligible chance of being unsafe.
     */
    NEGLIGIBLE: 'NEGLIGIBLE',
    /**
     * Content has a low chance of being unsafe.
     */
    LOW: 'LOW',
    /**
     * Content has a medium chance of being unsafe.
     */
    MEDIUM: 'MEDIUM',
    /**
     * Content has a high chance of being unsafe.
     */
    HIGH: 'HIGH'
};
/**
 * Harm severity levels.
 * @public
 */
const HarmSeverity = {
    /**
     * Negligible level of harm severity.
     */
    HARM_SEVERITY_NEGLIGIBLE: 'HARM_SEVERITY_NEGLIGIBLE',
    /**
     * Low level of harm severity.
     */
    HARM_SEVERITY_LOW: 'HARM_SEVERITY_LOW',
    /**
     * Medium level of harm severity.
     */
    HARM_SEVERITY_MEDIUM: 'HARM_SEVERITY_MEDIUM',
    /**
     * High level of harm severity.
     */
    HARM_SEVERITY_HIGH: 'HARM_SEVERITY_HIGH',
    /**
     * Harm severity is not supported.
     *
     * @remarks
     * The GoogleAI backend does not support `HarmSeverity`, so this value is used as a fallback.
     */
    HARM_SEVERITY_UNSUPPORTED: 'HARM_SEVERITY_UNSUPPORTED'
};
/**
 * Reason that a prompt was blocked.
 * @public
 */
const BlockReason = {
    /**
     * Content was blocked by safety settings.
     */
    SAFETY: 'SAFETY',
    /**
     * Content was blocked, but the reason is uncategorized.
     */
    OTHER: 'OTHER',
    /**
     * Content was blocked because it contained terms from the terminology blocklist.
     */
    BLOCKLIST: 'BLOCKLIST',
    /**
     * Content was blocked due to prohibited content.
     */
    PROHIBITED_CONTENT: 'PROHIBITED_CONTENT'
};
/**
 * Reason that a candidate finished.
 * @public
 */
const FinishReason = {
    /**
     * Natural stop point of the model or provided stop sequence.
     */
    STOP: 'STOP',
    /**
     * The maximum number of tokens as specified in the request was reached.
     */
    MAX_TOKENS: 'MAX_TOKENS',
    /**
     * The candidate content was flagged for safety reasons.
     */
    SAFETY: 'SAFETY',
    /**
     * The candidate content was flagged for recitation reasons.
     */
    RECITATION: 'RECITATION',
    /**
     * Unknown reason.
     */
    OTHER: 'OTHER',
    /**
     * The candidate content contained forbidden terms.
     */
    BLOCKLIST: 'BLOCKLIST',
    /**
     * The candidate content potentially contained prohibited content.
     */
    PROHIBITED_CONTENT: 'PROHIBITED_CONTENT',
    /**
     * The candidate content potentially contained Sensitive Personally Identifiable Information (SPII).
     */
    SPII: 'SPII',
    /**
     * The function call generated by the model was invalid.
     */
    MALFORMED_FUNCTION_CALL: 'MALFORMED_FUNCTION_CALL'
};
/**
 * @public
 */
const FunctionCallingMode = {
    /**
     * Default model behavior; model decides to predict either a function call
     * or a natural language response.
     */
    AUTO: 'AUTO',
    /**
     * Model is constrained to always predicting a function call only.
     * If `allowed_function_names` is set, the predicted function call will be
     * limited to any one of `allowed_function_names`, else the predicted
     * function call will be any one of the provided `function_declarations`.
     */
    ANY: 'ANY',
    /**
     * Model will not predict any function call. Model behavior is same as when
     * not passing any function declarations.
     */
    NONE: 'NONE'
};
/**
 * Content part modality.
 * @public
 */
const Modality = {
    /**
     * Unspecified modality.
     */
    MODALITY_UNSPECIFIED: 'MODALITY_UNSPECIFIED',
    /**
     * Plain text.
     */
    TEXT: 'TEXT',
    /**
     * Image.
     */
    IMAGE: 'IMAGE',
    /**
     * Video.
     */
    VIDEO: 'VIDEO',
    /**
     * Audio.
     */
    AUDIO: 'AUDIO',
    /**
     * Document (for example, PDF).
     */
    DOCUMENT: 'DOCUMENT'
};
/**
 * Generation modalities to be returned in generation responses.
 *
 * @beta
 */
const ResponseModality = {
    /**
     * Text.
     * @beta
     */
    TEXT: 'TEXT',
    /**
     * Image.
     * @beta
     */
    IMAGE: 'IMAGE',
    /**
     * Audio.
     * @beta
     */
    AUDIO: 'AUDIO'
};
/**
 * Determines whether inference happens on-device or in-cloud.
 *
 * @remarks
 * <b>PREFER_ON_DEVICE:</b> Attempt to make inference calls using an
 * on-device model. If on-device inference is not available, the SDK
 * will fall back to using a cloud-hosted model.
 * <br/>
 * <b>ONLY_ON_DEVICE:</b> Only attempt to make inference calls using an
 * on-device model. The SDK will not fall back to a cloud-hosted model.
 * If on-device inference is not available, inference methods will throw.
 * <br/>
 * <b>ONLY_IN_CLOUD:</b> Only attempt to make inference calls using a
 * cloud-hosted model. The SDK will not fall back to an on-device model.
 * <br/>
 * <b>PREFER_IN_CLOUD:</b> Attempt to make inference calls to a
 * cloud-hosted model. If not available, the SDK will fall back to an
 * on-device model.
 *
 * @beta
 */
const InferenceMode = {
    'PREFER_ON_DEVICE': 'prefer_on_device',
    'ONLY_ON_DEVICE': 'only_on_device',
    'ONLY_IN_CLOUD': 'only_in_cloud',
    'PREFER_IN_CLOUD': 'prefer_in_cloud'
};
/**
 * Indicates whether inference happened on-device or in-cloud.
 *
 * @beta
 */
const InferenceSource = {
    'ON_DEVICE': 'on_device',
    'IN_CLOUD': 'in_cloud'
};
/**
 * Represents the result of the code execution.
 *
 * @beta
 */
const Outcome = {
    UNSPECIFIED: 'OUTCOME_UNSPECIFIED',
    OK: 'OUTCOME_OK',
    FAILED: 'OUTCOME_FAILED',
    DEADLINE_EXCEEDED: 'OUTCOME_DEADLINE_EXCEEDED'
};
/**
 * The programming language of the code.
 *
 * @beta
 */
const Language = {
    UNSPECIFIED: 'LANGUAGE_UNSPECIFIED',
    PYTHON: 'PYTHON'
};

/**
 * @license
 * Copyright 2024 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * The status of a URL retrieval.
 *
 * @remarks
 * <b>URL_RETRIEVAL_STATUS_UNSPECIFIED:</b> Unspecified retrieval status.
 * <br/>
 * <b>URL_RETRIEVAL_STATUS_SUCCESS:</b> The URL retrieval was successful.
 * <br/>
 * <b>URL_RETRIEVAL_STATUS_ERROR:</b> The URL retrieval failed.
 * <br/>
 * <b>URL_RETRIEVAL_STATUS_PAYWALL:</b> The URL retrieval failed because the content is behind a paywall.
 * <br/>
 * <b>URL_RETRIEVAL_STATUS_UNSAFE:</b> The URL retrieval failed because the content is unsafe.
 * <br/>
 *
 * @beta
 */
const URLRetrievalStatus = {
    /**
     * Unspecified retrieval status.
     */
    URL_RETRIEVAL_STATUS_UNSPECIFIED: 'URL_RETRIEVAL_STATUS_UNSPECIFIED',
    /**
     * The URL retrieval was successful.
     */
    URL_RETRIEVAL_STATUS_SUCCESS: 'URL_RETRIEVAL_STATUS_SUCCESS',
    /**
     * The URL retrieval failed.
     */
    URL_RETRIEVAL_STATUS_ERROR: 'URL_RETRIEVAL_STATUS_ERROR',
    /**
     * The URL retrieval failed because the content is behind a paywall.
     */
    URL_RETRIEVAL_STATUS_PAYWALL: 'URL_RETRIEVAL_STATUS_PAYWALL',
    /**
     * The URL retrieval failed because the content is unsafe.
     */
    URL_RETRIEVAL_STATUS_UNSAFE: 'URL_RETRIEVAL_STATUS_UNSAFE'
};
/**
 * The types of responses that can be returned by {@link LiveSession.receive}.
 *
 * @beta
 */
const LiveResponseType = {
    SERVER_CONTENT: 'serverContent',
    TOOL_CALL: 'toolCall',
    TOOL_CALL_CANCELLATION: 'toolCallCancellation'
};

/**
 * @license
 * Copyright 2024 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Standardized error codes that {@link AIError} can have.
 *
 * @public
 */
const AIErrorCode = {
    /** A generic error occurred. */
    ERROR: 'error',
    /** An error occurred in a request. */
    REQUEST_ERROR: 'request-error',
    /** An error occurred in a response. */
    RESPONSE_ERROR: 'response-error',
    /** An error occurred while performing a fetch. */
    FETCH_ERROR: 'fetch-error',
    /** An error occurred because an operation was attempted on a closed session. */
    SESSION_CLOSED: 'session-closed',
    /** An error associated with a Content object.  */
    INVALID_CONTENT: 'invalid-content',
    /** An error due to the Firebase API not being enabled in the Console. */
    API_NOT_ENABLED: 'api-not-enabled',
    /** An error due to invalid Schema input.  */
    INVALID_SCHEMA: 'invalid-schema',
    /** An error occurred due to a missing Firebase API key. */
    NO_API_KEY: 'no-api-key',
    /** An error occurred due to a missing Firebase app ID. */
    NO_APP_ID: 'no-app-id',
    /** An error occurred due to a model name not being specified during initialization. */
    NO_MODEL: 'no-model',
    /** An error occurred due to a missing project ID. */
    NO_PROJECT_ID: 'no-project-id',
    /** An error occurred while parsing. */
    PARSE_FAILED: 'parse-failed',
    /** An error occurred due an attempt to use an unsupported feature. */
    UNSUPPORTED: 'unsupported'
};

/**
 * @license
 * Copyright 2024 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Contains the list of OpenAPI data types
 * as defined by the
 * {@link https://swagger.io/docs/specification/data-models/data-types/ | OpenAPI specification}
 * @public
 */
const SchemaType = {
    /** String type. */
    STRING: 'string',
    /** Number type. */
    NUMBER: 'number',
    /** Integer type. */
    INTEGER: 'integer',
    /** Boolean type. */
    BOOLEAN: 'boolean',
    /** Array type. */
    ARRAY: 'array',
    /** Object type. */
    OBJECT: 'object'
};

/**
 * @license
 * Copyright 2025 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * A filter level controlling how aggressively to filter sensitive content.
 *
 * Text prompts provided as inputs and images (generated or uploaded) through Imagen on Vertex AI
 * are assessed against a list of safety filters, which include 'harmful categories' (for example,
 * `violence`, `sexual`, `derogatory`, and `toxic`). This filter level controls how aggressively to
 * filter out potentially harmful content from responses. See the {@link http://firebase.google.com/docs/vertex-ai/generate-images | documentation }
 * and the {@link https://cloud.google.com/vertex-ai/generative-ai/docs/image/responsible-ai-imagen#safety-filters | Responsible AI and usage guidelines}
 * for more details.
 *
 * @public
 */
const ImagenSafetyFilterLevel = {
    /**
     * The most aggressive filtering level; most strict blocking.
     */
    BLOCK_LOW_AND_ABOVE: 'block_low_and_above',
    /**
     * Blocks some sensitive prompts and responses.
     */
    BLOCK_MEDIUM_AND_ABOVE: 'block_medium_and_above',
    /**
     * Blocks few sensitive prompts and responses.
     */
    BLOCK_ONLY_HIGH: 'block_only_high',
    /**
     * The least aggressive filtering level; blocks very few sensitive prompts and responses.
     *
     * Access to this feature is restricted and may require your case to be reviewed and approved by
     * Cloud support.
     */
    BLOCK_NONE: 'block_none'
};
/**
 * A filter level controlling whether generation of images containing people or faces is allowed.
 *
 * See the <a href="http://firebase.google.com/docs/vertex-ai/generate-images">personGeneration</a>
 * documentation for more details.
 *
 * @public
 */
const ImagenPersonFilterLevel = {
    /**
     * Disallow generation of images containing people or faces; images of people are filtered out.
     */
    BLOCK_ALL: 'dont_allow',
    /**
     * Allow generation of images containing adults only; images of children are filtered out.
     *
     * Generation of images containing people or faces may require your use case to be
     * reviewed and approved by Cloud support; see the {@link https://cloud.google.com/vertex-ai/generative-ai/docs/image/responsible-ai-imagen#person-face-gen | Responsible AI and usage guidelines}
     * for more details.
     */
    ALLOW_ADULT: 'allow_adult',
    /**
     * Allow generation of images containing adults only; images of children are filtered out.
     *
     * Generation of images containing people or faces may require your use case to be
     * reviewed and approved by Cloud support; see the {@link https://cloud.google.com/vertex-ai/generative-ai/docs/image/responsible-ai-imagen#person-face-gen | Responsible AI and usage guidelines}
     * for more details.
     */
    ALLOW_ALL: 'allow_all'
};
/**
 * Aspect ratios for Imagen images.
 *
 * To specify an aspect ratio for generated images, set the `aspectRatio` property in your
 * {@link ImagenGenerationConfig}.
 *
 * See the {@link http://firebase.google.com/docs/vertex-ai/generate-images | documentation }
 * for more details and examples of the supported aspect ratios.
 *
 * @public
 */
const ImagenAspectRatio = {
    /**
     * Square (1:1) aspect ratio.
     */
    'SQUARE': '1:1',
    /**
     * Landscape (3:4) aspect ratio.
     */
    'LANDSCAPE_3x4': '3:4',
    /**
     * Portrait (4:3) aspect ratio.
     */
    'PORTRAIT_4x3': '4:3',
    /**
     * Landscape (16:9) aspect ratio.
     */
    'LANDSCAPE_16x9': '16:9',
    /**
     * Portrait (9:16) aspect ratio.
     */
    'PORTRAIT_9x16': '9:16'
};

/**
 * @license
 * Copyright 2024 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * An enum-like object containing constants that represent the supported backends
 * for the Firebase AI SDK.
 * This determines which backend service (Vertex AI Gemini API or Gemini Developer API)
 * the SDK will communicate with.
 *
 * These values are assigned to the `backendType` property within the specific backend
 * configuration objects ({@link GoogleAIBackend} or {@link VertexAIBackend}) to identify
 * which service to target.
 *
 * @public
 */
const BackendType = {
    /**
     * Identifies the backend service for the Vertex AI Gemini API provided through Google Cloud.
     * Use this constant when creating a {@link VertexAIBackend} configuration.
     */
    VERTEX_AI: 'VERTEX_AI',
    /**
     * Identifies the backend service for the Gemini Developer API ({@link https://ai.google/ | Google AI}).
     * Use this constant when creating a {@link GoogleAIBackend} configuration.
     */
    GOOGLE_AI: 'GOOGLE_AI'
}; // Using 'as const' makes the string values literal types

/**
 * @license
 * Copyright 2025 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Abstract base class representing the configuration for an AI service backend.
 * This class should not be instantiated directly. Use its subclasses; {@link GoogleAIBackend} for
 * the Gemini Developer API (via {@link https://ai.google/ | Google AI}), and
 * {@link VertexAIBackend} for the Vertex AI Gemini API.
 *
 * @public
 */
class Backend {
    /**
     * Protected constructor for use by subclasses.
     * @param type - The backend type.
     */
    constructor(type) {
        this.backendType = type;
    }
}
/**
 * Configuration class for the Gemini Developer API.
 *
 * Use this with {@link AIOptions} when initializing the AI service via
 * {@link getAI | getAI()} to specify the Gemini Developer API as the backend.
 *
 * @public
 */
class GoogleAIBackend extends Backend {
    /**
     * Creates a configuration object for the Gemini Developer API backend.
     */
    constructor() {
        super(BackendType.GOOGLE_AI);
    }
}
/**
 * Configuration class for the Vertex AI Gemini API.
 *
 * Use this with {@link AIOptions} when initializing the AI service via
 * {@link getAI | getAI()} to specify the Vertex AI Gemini API as the backend.
 *
 * @public
 */
class VertexAIBackend extends Backend {
    /**
     * Creates a configuration object for the Vertex AI backend.
     *
     * @param location - The region identifier, defaulting to `us-central1`;
     * see {@link https://firebase.google.com/docs/vertex-ai/locations#available-locations | Vertex AI locations}
     * for a list of supported locations.
     */
    constructor(location = DEFAULT_LOCATION) {
        super(BackendType.VERTEX_AI);
        if (!location) {
            this.location = DEFAULT_LOCATION;
        }
        else {
            this.location = location;
        }
    }
}

/**
 * @license
 * Copyright 2025 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Encodes a {@link Backend} into a string that will be used to uniquely identify {@link AI}
 * instances by backend type.
 *
 * @internal
 */
function encodeInstanceIdentifier(backend) {
    if (backend instanceof GoogleAIBackend) {
        return `${AI_TYPE}/googleai`;
    }
    else if (backend instanceof VertexAIBackend) {
        return `${AI_TYPE}/vertexai/${backend.location}`;
    }
    else {
        throw new AIError(AIErrorCode.ERROR, `Invalid backend: ${JSON.stringify(backend.backendType)}`);
    }
}
/**
 * Decodes an instance identifier string into a {@link Backend}.
 *
 * @internal
 */
function decodeInstanceIdentifier(instanceIdentifier) {
    const identifierParts = instanceIdentifier.split('/');
    if (identifierParts[0] !== AI_TYPE) {
        throw new AIError(AIErrorCode.ERROR, `Invalid instance identifier, unknown prefix '${identifierParts[0]}'`);
    }
    const backendType = identifierParts[1];
    switch (backendType) {
        case 'vertexai':
            const location = identifierParts[2];
            if (!location) {
                throw new AIError(AIErrorCode.ERROR, `Invalid instance identifier, unknown location '${instanceIdentifier}'`);
            }
            return new VertexAIBackend(location);
        case 'googleai':
            return new GoogleAIBackend();
        default:
            throw new AIError(AIErrorCode.ERROR, `Invalid instance identifier string: '${instanceIdentifier}'`);
    }
}

/**
 * @license
 * Copyright 2024 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
const logger = new logger$1.Logger('@firebase/vertexai');

/**
 * @internal
 */
var Availability;
(function (Availability) {
    Availability["UNAVAILABLE"] = "unavailable";
    Availability["DOWNLOADABLE"] = "downloadable";
    Availability["DOWNLOADING"] = "downloading";
    Availability["AVAILABLE"] = "available";
})(Availability || (Availability = {}));

/**
 * @license
 * Copyright 2025 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
// Defaults to support image inputs for convenience.
const defaultExpectedInputs = [{ type: 'image' }];
/**
 * Defines an inference "backend" that uses Chrome's on-device model,
 * and encapsulates logic for detecting when on-device inference is
 * possible.
 */
class ChromeAdapterImpl {
    constructor(languageModelProvider, mode, onDeviceParams) {
        this.languageModelProvider = languageModelProvider;
        this.mode = mode;
        this.isDownloading = false;
        this.onDeviceParams = {
            createOptions: {
                expectedInputs: defaultExpectedInputs
            }
        };
        if (onDeviceParams) {
            this.onDeviceParams = onDeviceParams;
            if (!this.onDeviceParams.createOptions) {
                this.onDeviceParams.createOptions = {
                    expectedInputs: defaultExpectedInputs
                };
            }
            else if (!this.onDeviceParams.createOptions.expectedInputs) {
                this.onDeviceParams.createOptions.expectedInputs =
                    defaultExpectedInputs;
            }
        }
    }
    /**
     * Checks if a given request can be made on-device.
     *
     * Encapsulates a few concerns:
     *   the mode
     *   API existence
     *   prompt formatting
     *   model availability, including triggering download if necessary
     *
     *
     * Pros: callers needn't be concerned with details of on-device availability.</p>
     * Cons: this method spans a few concerns and splits request validation from usage.
     * If instance variables weren't already part of the API, we could consider a better
     * separation of concerns.
     */
    async isAvailable(request) {
        if (!this.mode) {
            logger.debug(`On-device inference unavailable because mode is undefined.`);
            return false;
        }
        if (this.mode === InferenceMode.ONLY_IN_CLOUD) {
            logger.debug(`On-device inference unavailable because mode is "only_in_cloud".`);
            return false;
        }
        // Triggers out-of-band download so model will eventually become available.
        const availability = await this.downloadIfAvailable();
        if (this.mode === InferenceMode.ONLY_ON_DEVICE) {
            // If it will never be available due to API inavailability, throw.
            if (availability === Availability.UNAVAILABLE) {
                throw new AIError(AIErrorCode.API_NOT_ENABLED, 'Local LanguageModel API not available in this environment.');
            }
            else if (availability === Availability.DOWNLOADABLE ||
                availability === Availability.DOWNLOADING) {
                // TODO(chholland): Better user experience during download - progress?
                logger.debug(`Waiting for download of LanguageModel to complete.`);
                await this.downloadPromise;
                return true;
            }
            return true;
        }
        // Applies prefer_on_device logic.
        if (availability !== Availability.AVAILABLE) {
            logger.debug(`On-device inference unavailable because availability is "${availability}".`);
            return false;
        }
        if (!ChromeAdapterImpl.isOnDeviceRequest(request)) {
            logger.debug(`On-device inference unavailable because request is incompatible.`);
            return false;
        }
        return true;
    }
    /**
     * Generates content on device.
     *
     * @remarks
     * This is comparable to {@link GenerativeModel.generateContent} for generating content in
     * Cloud.
     * @param request - a standard Firebase AI {@link GenerateContentRequest}
     * @returns {@link Response}, so we can reuse common response formatting.
     */
    async generateContent(request) {
        const session = await this.createSession();
        const contents = await Promise.all(request.contents.map(ChromeAdapterImpl.toLanguageModelMessage));
        const text = await session.prompt(contents, this.onDeviceParams.promptOptions);
        return ChromeAdapterImpl.toResponse(text);
    }
    /**
     * Generates content stream on device.
     *
     * @remarks
     * This is comparable to {@link GenerativeModel.generateContentStream} for generating content in
     * Cloud.
     * @param request - a standard Firebase AI {@link GenerateContentRequest}
     * @returns {@link Response}, so we can reuse common response formatting.
     */
    async generateContentStream(request) {
        const session = await this.createSession();
        const contents = await Promise.all(request.contents.map(ChromeAdapterImpl.toLanguageModelMessage));
        const stream = session.promptStreaming(contents, this.onDeviceParams.promptOptions);
        return ChromeAdapterImpl.toStreamResponse(stream);
    }
    async countTokens(_request) {
        throw new AIError(AIErrorCode.REQUEST_ERROR, 'Count Tokens is not yet available for on-device model.');
    }
    /**
     * Asserts inference for the given request can be performed by an on-device model.
     */
    static isOnDeviceRequest(request) {
        // Returns false if the prompt is empty.
        if (request.contents.length === 0) {
            logger.debug('Empty prompt rejected for on-device inference.');
            return false;
        }
        for (const content of request.contents) {
            if (content.role === 'function') {
                logger.debug(`"Function" role rejected for on-device inference.`);
                return false;
            }
            // Returns false if request contains an image with an unsupported mime type.
            for (const part of content.parts) {
                if (part.inlineData &&
                    ChromeAdapterImpl.SUPPORTED_MIME_TYPES.indexOf(part.inlineData.mimeType) === -1) {
                    logger.debug(`Unsupported mime type "${part.inlineData.mimeType}" rejected for on-device inference.`);
                    return false;
                }
            }
        }
        return true;
    }
    /**
     * Encapsulates logic to get availability and download a model if one is downloadable.
     */
    async downloadIfAvailable() {
        const availability = await this.languageModelProvider?.availability(this.onDeviceParams.createOptions);
        if (availability === Availability.DOWNLOADABLE) {
            this.download();
        }
        return availability;
    }
    /**
     * Triggers out-of-band download of an on-device model.
     *
     * Chrome only downloads models as needed. Chrome knows a model is needed when code calls
     * LanguageModel.create.
     *
     * Since Chrome manages the download, the SDK can only avoid redundant download requests by
     * tracking if a download has previously been requested.
     */
    download() {
        if (this.isDownloading) {
            return;
        }
        this.isDownloading = true;
        this.downloadPromise = this.languageModelProvider
            ?.create(this.onDeviceParams.createOptions)
            .finally(() => {
            this.isDownloading = false;
        });
    }
    /**
     * Converts Firebase AI {@link Content} object to a Chrome {@link LanguageModelMessage} object.
     */
    static async toLanguageModelMessage(content) {
        const languageModelMessageContents = await Promise.all(content.parts.map(ChromeAdapterImpl.toLanguageModelMessageContent));
        return {
            role: ChromeAdapterImpl.toLanguageModelMessageRole(content.role),
            content: languageModelMessageContents
        };
    }
    /**
     * Converts a Firebase AI Part object to a Chrome LanguageModelMessageContent object.
     */
    static async toLanguageModelMessageContent(part) {
        if (part.text) {
            return {
                type: 'text',
                value: part.text
            };
        }
        else if (part.inlineData) {
            const formattedImageContent = await fetch(`data:${part.inlineData.mimeType};base64,${part.inlineData.data}`);
            const imageBlob = await formattedImageContent.blob();
            const imageBitmap = await createImageBitmap(imageBlob);
            return {
                type: 'image',
                value: imageBitmap
            };
        }
        throw new AIError(AIErrorCode.REQUEST_ERROR, `Processing of this Part type is not currently supported.`);
    }
    /**
     * Converts a Firebase AI {@link Role} string to a {@link LanguageModelMessageRole} string.
     */
    static toLanguageModelMessageRole(role) {
        // Assumes 'function' rule has been filtered by isOnDeviceRequest
        return role === 'model' ? 'assistant' : 'user';
    }
    /**
     * Abstracts Chrome session creation.
     *
     * Chrome uses a multi-turn session for all inference. Firebase AI uses single-turn for all
     * inference. To map the Firebase AI API to Chrome's API, the SDK creates a new session for all
     * inference.
     *
     * Chrome will remove a model from memory if it's no longer in use, so this method ensures a
     * new session is created before an old session is destroyed.
     */
    async createSession() {
        if (!this.languageModelProvider) {
            throw new AIError(AIErrorCode.UNSUPPORTED, 'Chrome AI requested for unsupported browser version.');
        }
        const newSession = await this.languageModelProvider.create(this.onDeviceParams.createOptions);
        if (this.oldSession) {
            this.oldSession.destroy();
        }
        // Holds session reference, so model isn't unloaded from memory.
        this.oldSession = newSession;
        return newSession;
    }
    /**
     * Formats string returned by Chrome as a {@link Response} returned by Firebase AI.
     */
    static toResponse(text) {
        return {
            json: async () => ({
                candidates: [
                    {
                        content: {
                            parts: [{ text }]
                        }
                    }
                ]
            })
        };
    }
    /**
     * Formats string stream returned by Chrome as SSE returned by Firebase AI.
     */
    static toStreamResponse(stream) {
        const encoder = new TextEncoder();
        return {
            body: stream.pipeThrough(new TransformStream({
                transform(chunk, controller) {
                    const json = JSON.stringify({
                        candidates: [
                            {
                                content: {
                                    role: 'model',
                                    parts: [{ text: chunk }]
                                }
                            }
                        ]
                    });
                    controller.enqueue(encoder.encode(`data: ${json}\n\n`));
                }
            }))
        };
    }
}
// Visible for testing
ChromeAdapterImpl.SUPPORTED_MIME_TYPES = ['image/jpeg', 'image/png'];
/**
 * Creates a ChromeAdapterImpl on demand.
 */
function chromeAdapterFactory(mode, window, params) {
    // Do not initialize a ChromeAdapter if we are not in hybrid mode.
    if (typeof window !== 'undefined' && mode) {
        return new ChromeAdapterImpl(window.LanguageModel, mode, params);
    }
}

/**
 * @license
 * Copyright 2024 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
class AIService {
    constructor(app, backend, authProvider, appCheckProvider, chromeAdapterFactory) {
        this.app = app;
        this.backend = backend;
        this.chromeAdapterFactory = chromeAdapterFactory;
        const appCheck = appCheckProvider?.getImmediate({ optional: true });
        const auth = authProvider?.getImmediate({ optional: true });
        this.auth = auth || null;
        this.appCheck = appCheck || null;
        if (backend instanceof VertexAIBackend) {
            this.location = backend.location;
        }
        else {
            this.location = '';
        }
    }
    _delete() {
        return Promise.resolve();
    }
    set options(optionsToSet) {
        this._options = optionsToSet;
    }
    get options() {
        return this._options;
    }
}

/**
 * @license
 * Copyright 2025 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
function factory(container, { instanceIdentifier }) {
    if (!instanceIdentifier) {
        throw new AIError(AIErrorCode.ERROR, 'AIService instance identifier is undefined.');
    }
    const backend = decodeInstanceIdentifier(instanceIdentifier);
    // getImmediate for FirebaseApp will always succeed
    const app = container.getProvider('app').getImmediate();
    const auth = container.getProvider('auth-internal');
    const appCheckProvider = container.getProvider('app-check-internal');
    return new AIService(app, backend, auth, appCheckProvider, chromeAdapterFactory);
}

/**
 * @license
 * Copyright 2025 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Base class for Firebase AI model APIs.
 *
 * Instances of this class are associated with a specific Firebase AI {@link Backend}
 * and provide methods for interacting with the configured generative model.
 *
 * @public
 */
class AIModel {
    /**
     * Constructs a new instance of the {@link AIModel} class.
     *
     * This constructor should only be called from subclasses that provide
     * a model API.
     *
     * @param ai - an {@link AI} instance.
     * @param modelName - The name of the model being used. It can be in one of the following formats:
     * - `my-model` (short name, will resolve to `publishers/google/models/my-model`)
     * - `models/my-model` (will resolve to `publishers/google/models/my-model`)
     * - `publishers/my-publisher/models/my-model` (fully qualified model name)
     *
     * @throws If the `apiKey` or `projectId` fields are missing in your
     * Firebase config.
     *
     * @internal
     */
    constructor(ai, modelName) {
        if (!ai.app?.options?.apiKey) {
            throw new AIError(AIErrorCode.NO_API_KEY, `The "apiKey" field is empty in the local Firebase config. Firebase AI requires this field to contain a valid API key.`);
        }
        else if (!ai.app?.options?.projectId) {
            throw new AIError(AIErrorCode.NO_PROJECT_ID, `The "projectId" field is empty in the local Firebase config. Firebase AI requires this field to contain a valid project ID.`);
        }
        else if (!ai.app?.options?.appId) {
            throw new AIError(AIErrorCode.NO_APP_ID, `The "appId" field is empty in the local Firebase config. Firebase AI requires this field to contain a valid app ID.`);
        }
        else {
            this._apiSettings = {
                apiKey: ai.app.options.apiKey,
                project: ai.app.options.projectId,
                appId: ai.app.options.appId,
                automaticDataCollectionEnabled: ai.app.automaticDataCollectionEnabled,
                location: ai.location,
                backend: ai.backend
            };
            if (app._isFirebaseServerApp(ai.app) && ai.app.settings.appCheckToken) {
                const token = ai.app.settings.appCheckToken;
                this._apiSettings.getAppCheckToken = () => {
                    return Promise.resolve({ token });
                };
            }
            else if (ai.appCheck) {
                if (ai.options?.useLimitedUseAppCheckTokens) {
                    this._apiSettings.getAppCheckToken = () => ai.appCheck.getLimitedUseToken();
                }
                else {
                    this._apiSettings.getAppCheckToken = () => ai.appCheck.getToken();
                }
            }
            if (ai.auth) {
                this._apiSettings.getAuthToken = () => ai.auth.getToken();
            }
            this.model = AIModel.normalizeModelName(modelName, this._apiSettings.backend.backendType);
        }
    }
    /**
     * Normalizes the given model name to a fully qualified model resource name.
     *
     * @param modelName - The model name to normalize.
     * @returns The fully qualified model resource name.
     *
     * @internal
     */
    static normalizeModelName(modelName, backendType) {
        if (backendType === BackendType.GOOGLE_AI) {
            return AIModel.normalizeGoogleAIModelName(modelName);
        }
        else {
            return AIModel.normalizeVertexAIModelName(modelName);
        }
    }
    /**
     * @internal
     */
    static normalizeGoogleAIModelName(modelName) {
        return `models/${modelName}`;
    }
    /**
     * @internal
     */
    static normalizeVertexAIModelName(modelName) {
        let model;
        if (modelName.includes('/')) {
            if (modelName.startsWith('models/')) {
                // Add 'publishers/google' if the user is only passing in 'models/model-name'.
                model = `publishers/google/${modelName}`;
            }
            else {
                // Any other custom format (e.g. tuned models) must be passed in correctly.
                model = modelName;
            }
        }
        else {
            // If path is not included, assume it's a non-tuned model.
            model = `publishers/google/models/${modelName}`;
        }
        return model;
    }
}

/**
 * @license
 * Copyright 2024 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
var Task;
(function (Task) {
    Task["GENERATE_CONTENT"] = "generateContent";
    Task["STREAM_GENERATE_CONTENT"] = "streamGenerateContent";
    Task["COUNT_TOKENS"] = "countTokens";
    Task["PREDICT"] = "predict";
})(Task || (Task = {}));
class RequestUrl {
    constructor(model, task, apiSettings, stream, requestOptions) {
        this.model = model;
        this.task = task;
        this.apiSettings = apiSettings;
        this.stream = stream;
        this.requestOptions = requestOptions;
    }
    toString() {
        const url = new URL(this.baseUrl); // Throws if the URL is invalid
        url.pathname = `/${this.apiVersion}/${this.modelPath}:${this.task}`;
        url.search = this.queryParams.toString();
        return url.toString();
    }
    get baseUrl() {
        return this.requestOptions?.baseUrl || `https://${DEFAULT_DOMAIN}`;
    }
    get apiVersion() {
        return DEFAULT_API_VERSION; // TODO: allow user-set options if that feature becomes available
    }
    get modelPath() {
        if (this.apiSettings.backend instanceof GoogleAIBackend) {
            return `projects/${this.apiSettings.project}/${this.model}`;
        }
        else if (this.apiSettings.backend instanceof VertexAIBackend) {
            return `projects/${this.apiSettings.project}/locations/${this.apiSettings.backend.location}/${this.model}`;
        }
        else {
            throw new AIError(AIErrorCode.ERROR, `Invalid backend: ${JSON.stringify(this.apiSettings.backend)}`);
        }
    }
    get queryParams() {
        const params = new URLSearchParams();
        if (this.stream) {
            params.set('alt', 'sse');
        }
        return params;
    }
}
class WebSocketUrl {
    constructor(apiSettings) {
        this.apiSettings = apiSettings;
    }
    toString() {
        const url = new URL(`wss://${DEFAULT_DOMAIN}`);
        url.pathname = this.pathname;
        const queryParams = new URLSearchParams();
        queryParams.set('key', this.apiSettings.apiKey);
        url.search = queryParams.toString();
        return url.toString();
    }
    get pathname() {
        if (this.apiSettings.backend.backendType === BackendType.GOOGLE_AI) {
            return 'ws/google.firebase.vertexai.v1beta.GenerativeService/BidiGenerateContent';
        }
        else {
            return `ws/google.firebase.vertexai.v1beta.LlmBidiService/BidiGenerateContent/locations/${this.apiSettings.location}`;
        }
    }
}
/**
 * Log language and "fire/version" to x-goog-api-client
 */
function getClientHeaders() {
    const loggingTags = [];
    loggingTags.push(`${LANGUAGE_TAG}/${PACKAGE_VERSION}`);
    loggingTags.push(`fire/${PACKAGE_VERSION}`);
    return loggingTags.join(' ');
}
async function getHeaders(url) {
    const headers = new Headers();
    headers.append('Content-Type', 'application/json');
    headers.append('x-goog-api-client', getClientHeaders());
    headers.append('x-goog-api-key', url.apiSettings.apiKey);
    if (url.apiSettings.automaticDataCollectionEnabled) {
        headers.append('X-Firebase-Appid', url.apiSettings.appId);
    }
    if (url.apiSettings.getAppCheckToken) {
        const appCheckToken = await url.apiSettings.getAppCheckToken();
        if (appCheckToken) {
            headers.append('X-Firebase-AppCheck', appCheckToken.token);
            if (appCheckToken.error) {
                logger.warn(`Unable to obtain a valid App Check token: ${appCheckToken.error.message}`);
            }
        }
    }
    if (url.apiSettings.getAuthToken) {
        const authToken = await url.apiSettings.getAuthToken();
        if (authToken) {
            headers.append('Authorization', `Firebase ${authToken.accessToken}`);
        }
    }
    return headers;
}
async function constructRequest(model, task, apiSettings, stream, body, requestOptions) {
    const url = new RequestUrl(model, task, apiSettings, stream, requestOptions);
    return {
        url: url.toString(),
        fetchOptions: {
            method: 'POST',
            headers: await getHeaders(url),
            body
        }
    };
}
async function makeRequest(model, task, apiSettings, stream, body, requestOptions) {
    const url = new RequestUrl(model, task, apiSettings, stream, requestOptions);
    let response;
    let fetchTimeoutId;
    try {
        const request = await constructRequest(model, task, apiSettings, stream, body, requestOptions);
        // Timeout is 180s by default
        const timeoutMillis = requestOptions?.timeout != null && requestOptions.timeout >= 0
            ? requestOptions.timeout
            : DEFAULT_FETCH_TIMEOUT_MS;
        const abortController = new AbortController();
        fetchTimeoutId = setTimeout(() => abortController.abort(), timeoutMillis);
        request.fetchOptions.signal = abortController.signal;
        response = await fetch(request.url, request.fetchOptions);
        if (!response.ok) {
            let message = '';
            let errorDetails;
            try {
                const json = await response.json();
                message = json.error.message;
                if (json.error.details) {
                    message += ` ${JSON.stringify(json.error.details)}`;
                    errorDetails = json.error.details;
                }
            }
            catch (e) {
                // ignored
            }
            if (response.status === 403 &&
                errorDetails &&
                errorDetails.some((detail) => detail.reason === 'SERVICE_DISABLED') &&
                errorDetails.some((detail) => detail.links?.[0]?.description.includes('Google developers console API activation'))) {
                throw new AIError(AIErrorCode.API_NOT_ENABLED, `The Firebase AI SDK requires the Firebase AI ` +
                    `API ('firebasevertexai.googleapis.com') to be enabled in your ` +
                    `Firebase project. Enable this API by visiting the Firebase Console ` +
                    `at https://console.firebase.google.com/project/${url.apiSettings.project}/genai/ ` +
                    `and clicking "Get started". If you enabled this API recently, ` +
                    `wait a few minutes for the action to propagate to our systems and ` +
                    `then retry.`, {
                    status: response.status,
                    statusText: response.statusText,
                    errorDetails
                });
            }
            throw new AIError(AIErrorCode.FETCH_ERROR, `Error fetching from ${url}: [${response.status} ${response.statusText}] ${message}`, {
                status: response.status,
                statusText: response.statusText,
                errorDetails
            });
        }
    }
    catch (e) {
        let err = e;
        if (e.code !== AIErrorCode.FETCH_ERROR &&
            e.code !== AIErrorCode.API_NOT_ENABLED &&
            e instanceof Error) {
            err = new AIError(AIErrorCode.ERROR, `Error fetching from ${url.toString()}: ${e.message}`);
            err.stack = e.stack;
        }
        throw err;
    }
    finally {
        if (fetchTimeoutId) {
            clearTimeout(fetchTimeoutId);
        }
    }
    return response;
}

/**
 * @license
 * Copyright 2024 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Check that at least one candidate exists and does not have a bad
 * finish reason. Warns if multiple candidates exist.
 */
function hasValidCandidates(response) {
    if (response.candidates && response.candidates.length > 0) {
        if (response.candidates.length > 1) {
            logger.warn(`This response had ${response.candidates.length} ` +
                `candidates. Returning text from the first candidate only. ` +
                `Access response.candidates directly to use the other candidates.`);
        }
        if (hadBadFinishReason(response.candidates[0])) {
            throw new AIError(AIErrorCode.RESPONSE_ERROR, `Response error: ${formatBlockErrorMessage(response)}. Response body stored in error.response`, {
                response
            });
        }
        return true;
    }
    else {
        return false;
    }
}
/**
 * Creates an EnhancedGenerateContentResponse object that has helper functions and
 * other modifications that improve usability.
 */
function createEnhancedContentResponse(response, inferenceSource = InferenceSource.IN_CLOUD) {
    /**
     * The Vertex AI backend omits default values.
     * This causes the `index` property to be omitted from the first candidate in the
     * response, since it has index 0, and 0 is a default value.
     * See: https://github.com/firebase/firebase-js-sdk/issues/8566
     */
    if (response.candidates && !response.candidates[0].hasOwnProperty('index')) {
        response.candidates[0].index = 0;
    }
    const responseWithHelpers = addHelpers(response);
    responseWithHelpers.inferenceSource = inferenceSource;
    return responseWithHelpers;
}
/**
 * Adds convenience helper methods to a response object, including stream
 * chunks (as long as each chunk is a complete GenerateContentResponse JSON).
 */
function addHelpers(response) {
    response.text = () => {
        if (hasValidCandidates(response)) {
            return getText(response, part => !part.thought);
        }
        else if (response.promptFeedback) {
            throw new AIError(AIErrorCode.RESPONSE_ERROR, `Text not available. ${formatBlockErrorMessage(response)}`, {
                response
            });
        }
        return '';
    };
    response.thoughtSummary = () => {
        if (hasValidCandidates(response)) {
            const result = getText(response, part => !!part.thought);
            return result === '' ? undefined : result;
        }
        else if (response.promptFeedback) {
            throw new AIError(AIErrorCode.RESPONSE_ERROR, `Thought summary not available. ${formatBlockErrorMessage(response)}`, {
                response
            });
        }
        return undefined;
    };
    response.inlineDataParts = () => {
        if (hasValidCandidates(response)) {
            return getInlineDataParts(response);
        }
        else if (response.promptFeedback) {
            throw new AIError(AIErrorCode.RESPONSE_ERROR, `Data not available. ${formatBlockErrorMessage(response)}`, {
                response
            });
        }
        return undefined;
    };
    response.functionCalls = () => {
        if (hasValidCandidates(response)) {
            return getFunctionCalls(response);
        }
        else if (response.promptFeedback) {
            throw new AIError(AIErrorCode.RESPONSE_ERROR, `Function call not available. ${formatBlockErrorMessage(response)}`, {
                response
            });
        }
        return undefined;
    };
    return response;
}
/**
 * Returns all text from the first candidate's parts, filtering by whether
 * `partFilter()` returns true.
 *
 * @param response - The `GenerateContentResponse` from which to extract text.
 * @param partFilter - Only return `Part`s for which this returns true
 */
function getText(response, partFilter) {
    const textStrings = [];
    if (response.candidates?.[0].content?.parts) {
        for (const part of response.candidates?.[0].content?.parts) {
            if (part.text && partFilter(part)) {
                textStrings.push(part.text);
            }
        }
    }
    if (textStrings.length > 0) {
        return textStrings.join('');
    }
    else {
        return '';
    }
}
/**
 * Returns every {@link FunctionCall} associated with first candidate.
 */
function getFunctionCalls(response) {
    const functionCalls = [];
    if (response.candidates?.[0].content?.parts) {
        for (const part of response.candidates?.[0].content?.parts) {
            if (part.functionCall) {
                functionCalls.push(part.functionCall);
            }
        }
    }
    if (functionCalls.length > 0) {
        return functionCalls;
    }
    else {
        return undefined;
    }
}
/**
 * Returns every {@link InlineDataPart} in the first candidate if present.
 *
 * @internal
 */
function getInlineDataParts(response) {
    const data = [];
    if (response.candidates?.[0].content?.parts) {
        for (const part of response.candidates?.[0].content?.parts) {
            if (part.inlineData) {
                data.push(part);
            }
        }
    }
    if (data.length > 0) {
        return data;
    }
    else {
        return undefined;
    }
}
const badFinishReasons = [FinishReason.RECITATION, FinishReason.SAFETY];
function hadBadFinishReason(candidate) {
    return (!!candidate.finishReason &&
        badFinishReasons.some(reason => reason === candidate.finishReason));
}
function formatBlockErrorMessage(response) {
    let message = '';
    if ((!response.candidates || response.candidates.length === 0) &&
        response.promptFeedback) {
        message += 'Response was blocked';
        if (response.promptFeedback?.blockReason) {
            message += ` due to ${response.promptFeedback.blockReason}`;
        }
        if (response.promptFeedback?.blockReasonMessage) {
            message += `: ${response.promptFeedback.blockReasonMessage}`;
        }
    }
    else if (response.candidates?.[0]) {
        const firstCandidate = response.candidates[0];
        if (hadBadFinishReason(firstCandidate)) {
            message += `Candidate was blocked due to ${firstCandidate.finishReason}`;
            if (firstCandidate.finishMessage) {
                message += `: ${firstCandidate.finishMessage}`;
            }
        }
    }
    return message;
}
/**
 * Convert a generic successful fetch response body to an Imagen response object
 * that can be returned to the user. This converts the REST APIs response format to our
 * APIs representation of a response.
 *
 * @internal
 */
async function handlePredictResponse(response) {
    const responseJson = await response.json();
    const images = [];
    let filteredReason = undefined;
    // The backend should always send a non-empty array of predictions if the response was successful.
    if (!responseJson.predictions || responseJson.predictions?.length === 0) {
        throw new AIError(AIErrorCode.RESPONSE_ERROR, 'No predictions or filtered reason received from Vertex AI. Please report this issue with the full error details at https://github.com/firebase/firebase-js-sdk/issues.');
    }
    for (const prediction of responseJson.predictions) {
        if (prediction.raiFilteredReason) {
            filteredReason = prediction.raiFilteredReason;
        }
        else if (prediction.mimeType && prediction.bytesBase64Encoded) {
            images.push({
                mimeType: prediction.mimeType,
                bytesBase64Encoded: prediction.bytesBase64Encoded
            });
        }
        else if (prediction.mimeType && prediction.gcsUri) {
            images.push({
                mimeType: prediction.mimeType,
                gcsURI: prediction.gcsUri
            });
        }
        else if (prediction.safetyAttributes) ;
        else {
            throw new AIError(AIErrorCode.RESPONSE_ERROR, `Unexpected element in 'predictions' array in response: '${JSON.stringify(prediction)}'`);
        }
    }
    return { images, filteredReason };
}

/**
 * @license
 * Copyright 2025 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * This SDK supports both the Vertex AI Gemini API and the Gemini Developer API (using Google AI).
 * The public API prioritizes the format used by the Vertex AI Gemini API.
 * We avoid having two sets of types by translating requests and responses between the two API formats.
 * This translation allows developers to switch between the Vertex AI Gemini API and the Gemini Developer API
 * with minimal code changes.
 *
 * In here are functions that map requests and responses between the two API formats.
 * Requests in the Vertex AI format are mapped to the Google AI format before being sent.
 * Responses from the Google AI backend are mapped back to the Vertex AI format before being returned to the user.
 */
/**
 * Maps a Vertex AI {@link GenerateContentRequest} to a format that can be sent to Google AI.
 *
 * @param generateContentRequest The {@link GenerateContentRequest} to map.
 * @returns A {@link GenerateContentResponse} that conforms to the Google AI format.
 *
 * @throws If the request contains properties that are unsupported by Google AI.
 *
 * @internal
 */
function mapGenerateContentRequest(generateContentRequest) {
    generateContentRequest.safetySettings?.forEach(safetySetting => {
        if (safetySetting.method) {
            throw new AIError(AIErrorCode.UNSUPPORTED, 'SafetySetting.method is not supported in the the Gemini Developer API. Please remove this property.');
        }
    });
    if (generateContentRequest.generationConfig?.topK) {
        const roundedTopK = Math.round(generateContentRequest.generationConfig.topK);
        if (roundedTopK !== generateContentRequest.generationConfig.topK) {
            logger.warn('topK in GenerationConfig has been rounded to the nearest integer to match the format for requests to the Gemini Developer API.');
            generateContentRequest.generationConfig.topK = roundedTopK;
        }
    }
    return generateContentRequest;
}
/**
 * Maps a {@link GenerateContentResponse} from Google AI to the format of the
 * {@link GenerateContentResponse} that we get from VertexAI that is exposed in the public API.
 *
 * @param googleAIResponse The {@link GenerateContentResponse} from Google AI.
 * @returns A {@link GenerateContentResponse} that conforms to the public API's format.
 *
 * @internal
 */
function mapGenerateContentResponse(googleAIResponse) {
    const generateContentResponse = {
        candidates: googleAIResponse.candidates
            ? mapGenerateContentCandidates(googleAIResponse.candidates)
            : undefined,
        prompt: googleAIResponse.promptFeedback
            ? mapPromptFeedback(googleAIResponse.promptFeedback)
            : undefined,
        usageMetadata: googleAIResponse.usageMetadata
    };
    return generateContentResponse;
}
/**
 * Maps a Vertex AI {@link CountTokensRequest} to a format that can be sent to Google AI.
 *
 * @param countTokensRequest The {@link CountTokensRequest} to map.
 * @param model The model to count tokens with.
 * @returns A {@link CountTokensRequest} that conforms to the Google AI format.
 *
 * @internal
 */
function mapCountTokensRequest(countTokensRequest, model) {
    const mappedCountTokensRequest = {
        generateContentRequest: {
            model,
            ...countTokensRequest
        }
    };
    return mappedCountTokensRequest;
}
/**
 * Maps a Google AI {@link GoogleAIGenerateContentCandidate} to a format that conforms
 * to the Vertex AI API format.
 *
 * @param candidates The {@link GoogleAIGenerateContentCandidate} to map.
 * @returns A {@link GenerateContentCandidate} that conforms to the Vertex AI format.
 *
 * @throws If any {@link Part} in the candidates has a `videoMetadata` property.
 *
 * @internal
 */
function mapGenerateContentCandidates(candidates) {
    const mappedCandidates = [];
    let mappedSafetyRatings;
    if (mappedCandidates) {
        candidates.forEach(candidate => {
            // Map citationSources to citations.
            let citationMetadata;
            if (candidate.citationMetadata) {
                citationMetadata = {
                    citations: candidate.citationMetadata.citationSources
                };
            }
            // Assign missing candidate SafetyRatings properties to their defaults if undefined.
            if (candidate.safetyRatings) {
                mappedSafetyRatings = candidate.safetyRatings.map(safetyRating => {
                    return {
                        ...safetyRating,
                        severity: safetyRating.severity ?? HarmSeverity.HARM_SEVERITY_UNSUPPORTED,
                        probabilityScore: safetyRating.probabilityScore ?? 0,
                        severityScore: safetyRating.severityScore ?? 0
                    };
                });
            }
            // videoMetadata is not supported.
            // Throw early since developers may send a long video as input and only expect to pay
            // for inference on a small portion of the video.
            if (candidate.content?.parts?.some(part => part?.videoMetadata)) {
                throw new AIError(AIErrorCode.UNSUPPORTED, 'Part.videoMetadata is not supported in the Gemini Developer API. Please remove this property.');
            }
            const mappedCandidate = {
                index: candidate.index,
                content: candidate.content,
                finishReason: candidate.finishReason,
                finishMessage: candidate.finishMessage,
                safetyRatings: mappedSafetyRatings,
                citationMetadata,
                groundingMetadata: candidate.groundingMetadata,
                urlContextMetadata: candidate.urlContextMetadata
            };
            mappedCandidates.push(mappedCandidate);
        });
    }
    return mappedCandidates;
}
function mapPromptFeedback(promptFeedback) {
    // Assign missing SafetyRating properties to their defaults if undefined.
    const mappedSafetyRatings = [];
    promptFeedback.safetyRatings.forEach(safetyRating => {
        mappedSafetyRatings.push({
            category: safetyRating.category,
            probability: safetyRating.probability,
            severity: safetyRating.severity ?? HarmSeverity.HARM_SEVERITY_UNSUPPORTED,
            probabilityScore: safetyRating.probabilityScore ?? 0,
            severityScore: safetyRating.severityScore ?? 0,
            blocked: safetyRating.blocked
        });
    });
    const mappedPromptFeedback = {
        blockReason: promptFeedback.blockReason,
        safetyRatings: mappedSafetyRatings,
        blockReasonMessage: promptFeedback.blockReasonMessage
    };
    return mappedPromptFeedback;
}

/**
 * @license
 * Copyright 2024 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
const responseLineRE = /^data\: (.*)(?:\n\n|\r\r|\r\n\r\n)/;
/**
 * Process a response.body stream from the backend and return an
 * iterator that provides one complete GenerateContentResponse at a time
 * and a promise that resolves with a single aggregated
 * GenerateContentResponse.
 *
 * @param response - Response from a fetch call
 */
function processStream(response, apiSettings, inferenceSource) {
    const inputStream = response.body.pipeThrough(new TextDecoderStream('utf8', { fatal: true }));
    const responseStream = getResponseStream(inputStream);
    const [stream1, stream2] = responseStream.tee();
    return {
        stream: generateResponseSequence(stream1, apiSettings, inferenceSource),
        response: getResponsePromise(stream2, apiSettings, inferenceSource)
    };
}
async function getResponsePromise(stream, apiSettings, inferenceSource) {
    const allResponses = [];
    const reader = stream.getReader();
    while (true) {
        const { done, value } = await reader.read();
        if (done) {
            let generateContentResponse = aggregateResponses(allResponses);
            if (apiSettings.backend.backendType === BackendType.GOOGLE_AI) {
                generateContentResponse = mapGenerateContentResponse(generateContentResponse);
            }
            return createEnhancedContentResponse(generateContentResponse, inferenceSource);
        }
        allResponses.push(value);
    }
}
async function* generateResponseSequence(stream, apiSettings, inferenceSource) {
    const reader = stream.getReader();
    while (true) {
        const { value, done } = await reader.read();
        if (done) {
            break;
        }
        let enhancedResponse;
        if (apiSettings.backend.backendType === BackendType.GOOGLE_AI) {
            enhancedResponse = createEnhancedContentResponse(mapGenerateContentResponse(value), inferenceSource);
        }
        else {
            enhancedResponse = createEnhancedContentResponse(value, inferenceSource);
        }
        const firstCandidate = enhancedResponse.candidates?.[0];
        // Don't yield a response with no useful data for the developer.
        if (!firstCandidate?.content?.parts &&
            !firstCandidate?.finishReason &&
            !firstCandidate?.citationMetadata &&
            !firstCandidate?.urlContextMetadata) {
            continue;
        }
        yield enhancedResponse;
    }
}
/**
 * Reads a raw stream from the fetch response and join incomplete
 * chunks, returning a new stream that provides a single complete
 * GenerateContentResponse in each iteration.
 */
function getResponseStream(inputStream) {
    const reader = inputStream.getReader();
    const stream = new ReadableStream({
        start(controller) {
            let currentText = '';
            return pump();
            function pump() {
                return reader.read().then(({ value, done }) => {
                    if (done) {
                        if (currentText.trim()) {
                            controller.error(new AIError(AIErrorCode.PARSE_FAILED, 'Failed to parse stream'));
                            return;
                        }
                        controller.close();
                        return;
                    }
                    currentText += value;
                    let match = currentText.match(responseLineRE);
                    let parsedResponse;
                    while (match) {
                        try {
                            parsedResponse = JSON.parse(match[1]);
                        }
                        catch (e) {
                            controller.error(new AIError(AIErrorCode.PARSE_FAILED, `Error parsing JSON response: "${match[1]}`));
                            return;
                        }
                        controller.enqueue(parsedResponse);
                        currentText = currentText.substring(match[0].length);
                        match = currentText.match(responseLineRE);
                    }
                    return pump();
                });
            }
        }
    });
    return stream;
}
/**
 * Aggregates an array of `GenerateContentResponse`s into a single
 * GenerateContentResponse.
 */
function aggregateResponses(responses) {
    const lastResponse = responses[responses.length - 1];
    const aggregatedResponse = {
        promptFeedback: lastResponse?.promptFeedback
    };
    for (const response of responses) {
        if (response.candidates) {
            for (const candidate of response.candidates) {
                // Index will be undefined if it's the first index (0), so we should use 0 if it's undefined.
                // See: https://github.com/firebase/firebase-js-sdk/issues/8566
                const i = candidate.index || 0;
                if (!aggregatedResponse.candidates) {
                    aggregatedResponse.candidates = [];
                }
                if (!aggregatedResponse.candidates[i]) {
                    aggregatedResponse.candidates[i] = {
                        index: candidate.index
                    };
                }
                // Keep overwriting, the last one will be final
                aggregatedResponse.candidates[i].citationMetadata =
                    candidate.citationMetadata;
                aggregatedResponse.candidates[i].finishReason = candidate.finishReason;
                aggregatedResponse.candidates[i].finishMessage =
                    candidate.finishMessage;
                aggregatedResponse.candidates[i].safetyRatings =
                    candidate.safetyRatings;
                aggregatedResponse.candidates[i].groundingMetadata =
                    candidate.groundingMetadata;
                // The urlContextMetadata object is defined in the first chunk of the response stream.
                // In all subsequent chunks, the urlContextMetadata object will be undefined. We need to
                // make sure that we don't overwrite the first value urlContextMetadata object with undefined.
                // FIXME: What happens if we receive a second, valid urlContextMetadata object?
                const urlContextMetadata = candidate.urlContextMetadata;
                if (typeof urlContextMetadata === 'object' &&
                    urlContextMetadata !== null &&
                    Object.keys(urlContextMetadata).length > 0) {
                    aggregatedResponse.candidates[i].urlContextMetadata =
                        urlContextMetadata;
                }
                /**
                 * Candidates should always have content and parts, but this handles
                 * possible malformed responses.
                 */
                if (candidate.content) {
                    // Skip a candidate without parts.
                    if (!candidate.content.parts) {
                        continue;
                    }
                    if (!aggregatedResponse.candidates[i].content) {
                        aggregatedResponse.candidates[i].content = {
                            role: candidate.content.role || 'user',
                            parts: []
                        };
                    }
                    for (const part of candidate.content.parts) {
                        const newPart = { ...part };
                        // The backend can send empty text parts. If these are sent back
                        // (e.g. in chat history), the backend will respond with an error.
                        // To prevent this, ignore empty text parts.
                        if (part.text === '') {
                            continue;
                        }
                        if (Object.keys(newPart).length > 0) {
                            aggregatedResponse.candidates[i].content.parts.push(newPart);
                        }
                    }
                }
            }
        }
    }
    return aggregatedResponse;
}

/**
 * @license
 * Copyright 2025 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
const errorsCausingFallback = [
    // most network errors
    AIErrorCode.FETCH_ERROR,
    // fallback code for all other errors in makeRequest
    AIErrorCode.ERROR,
    // error due to API not being enabled in project
    AIErrorCode.API_NOT_ENABLED
];
/**
 * Dispatches a request to the appropriate backend (on-device or in-cloud)
 * based on the inference mode.
 *
 * @param request - The request to be sent.
 * @param chromeAdapter - The on-device model adapter.
 * @param onDeviceCall - The function to call for on-device inference.
 * @param inCloudCall - The function to call for in-cloud inference.
 * @returns The response from the backend.
 */
async function callCloudOrDevice(request, chromeAdapter, onDeviceCall, inCloudCall) {
    if (!chromeAdapter) {
        return {
            response: await inCloudCall(),
            inferenceSource: InferenceSource.IN_CLOUD
        };
    }
    switch (chromeAdapter.mode) {
        case InferenceMode.ONLY_ON_DEVICE:
            if (await chromeAdapter.isAvailable(request)) {
                return {
                    response: await onDeviceCall(),
                    inferenceSource: InferenceSource.ON_DEVICE
                };
            }
            throw new AIError(AIErrorCode.UNSUPPORTED, 'Inference mode is ONLY_ON_DEVICE, but an on-device model is not available.');
        case InferenceMode.ONLY_IN_CLOUD:
            return {
                response: await inCloudCall(),
                inferenceSource: InferenceSource.IN_CLOUD
            };
        case InferenceMode.PREFER_IN_CLOUD:
            try {
                return {
                    response: await inCloudCall(),
                    inferenceSource: InferenceSource.IN_CLOUD
                };
            }
            catch (e) {
                if (e instanceof AIError && errorsCausingFallback.includes(e.code)) {
                    return {
                        response: await onDeviceCall(),
                        inferenceSource: InferenceSource.ON_DEVICE
                    };
                }
                throw e;
            }
        case InferenceMode.PREFER_ON_DEVICE:
            if (await chromeAdapter.isAvailable(request)) {
                return {
                    response: await onDeviceCall(),
                    inferenceSource: InferenceSource.ON_DEVICE
                };
            }
            return {
                response: await inCloudCall(),
                inferenceSource: InferenceSource.IN_CLOUD
            };
        default:
            throw new AIError(AIErrorCode.ERROR, `Unexpected infererence mode: ${chromeAdapter.mode}`);
    }
}

/**
 * @license
 * Copyright 2024 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
async function generateContentStreamOnCloud(apiSettings, model, params, requestOptions) {
    if (apiSettings.backend.backendType === BackendType.GOOGLE_AI) {
        params = mapGenerateContentRequest(params);
    }
    return makeRequest(model, Task.STREAM_GENERATE_CONTENT, apiSettings, 
    /* stream */ true, JSON.stringify(params), requestOptions);
}
async function generateContentStream(apiSettings, model, params, chromeAdapter, requestOptions) {
    const callResult = await callCloudOrDevice(params, chromeAdapter, () => chromeAdapter.generateContentStream(params), () => generateContentStreamOnCloud(apiSettings, model, params, requestOptions));
    return processStream(callResult.response, apiSettings); // TODO: Map streaming responses
}
async function generateContentOnCloud(apiSettings, model, params, requestOptions) {
    if (apiSettings.backend.backendType === BackendType.GOOGLE_AI) {
        params = mapGenerateContentRequest(params);
    }
    return makeRequest(model, Task.GENERATE_CONTENT, apiSettings, 
    /* stream */ false, JSON.stringify(params), requestOptions);
}
async function generateContent(apiSettings, model, params, chromeAdapter, requestOptions) {
    const callResult = await callCloudOrDevice(params, chromeAdapter, () => chromeAdapter.generateContent(params), () => generateContentOnCloud(apiSettings, model, params, requestOptions));
    const generateContentResponse = await processGenerateContentResponse(callResult.response, apiSettings);
    const enhancedResponse = createEnhancedContentResponse(generateContentResponse, callResult.inferenceSource);
    return {
        response: enhancedResponse
    };
}
async function processGenerateContentResponse(response, apiSettings) {
    const responseJson = await response.json();
    if (apiSettings.backend.backendType === BackendType.GOOGLE_AI) {
        return mapGenerateContentResponse(responseJson);
    }
    else {
        return responseJson;
    }
}

/**
 * @license
 * Copyright 2024 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
function formatSystemInstruction(input) {
    // null or undefined
    if (input == null) {
        return undefined;
    }
    else if (typeof input === 'string') {
        return { role: 'system', parts: [{ text: input }] };
    }
    else if (input.text) {
        return { role: 'system', parts: [input] };
    }
    else if (input.parts) {
        if (!input.role) {
            return { role: 'system', parts: input.parts };
        }
        else {
            return input;
        }
    }
}
function formatNewContent(request) {
    let newParts = [];
    if (typeof request === 'string') {
        newParts = [{ text: request }];
    }
    else {
        for (const partOrString of request) {
            if (typeof partOrString === 'string') {
                newParts.push({ text: partOrString });
            }
            else {
                newParts.push(partOrString);
            }
        }
    }
    return assignRoleToPartsAndValidateSendMessageRequest(newParts);
}
/**
 * When multiple Part types (i.e. FunctionResponsePart and TextPart) are
 * passed in a single Part array, we may need to assign different roles to each
 * part. Currently only FunctionResponsePart requires a role other than 'user'.
 * @private
 * @param parts Array of parts to pass to the model
 * @returns Array of content items
 */
function assignRoleToPartsAndValidateSendMessageRequest(parts) {
    const userContent = { role: 'user', parts: [] };
    const functionContent = { role: 'function', parts: [] };
    let hasUserContent = false;
    let hasFunctionContent = false;
    for (const part of parts) {
        if ('functionResponse' in part) {
            functionContent.parts.push(part);
            hasFunctionContent = true;
        }
        else {
            userContent.parts.push(part);
            hasUserContent = true;
        }
    }
    if (hasUserContent && hasFunctionContent) {
        throw new AIError(AIErrorCode.INVALID_CONTENT, 'Within a single message, FunctionResponse cannot be mixed with other type of Part in the request for sending chat message.');
    }
    if (!hasUserContent && !hasFunctionContent) {
        throw new AIError(AIErrorCode.INVALID_CONTENT, 'No Content is provided for sending chat message.');
    }
    if (hasUserContent) {
        return userContent;
    }
    return functionContent;
}
function formatGenerateContentInput(params) {
    let formattedRequest;
    if (params.contents) {
        formattedRequest = params;
    }
    else {
        // Array or string
        const content = formatNewContent(params);
        formattedRequest = { contents: [content] };
    }
    if (params.systemInstruction) {
        formattedRequest.systemInstruction = formatSystemInstruction(params.systemInstruction);
    }
    return formattedRequest;
}
/**
 * Convert the user-defined parameters in {@link ImagenGenerationParams} to the format
 * that is expected from the REST API.
 *
 * @internal
 */
function createPredictRequestBody(prompt, { gcsURI, imageFormat, addWatermark, numberOfImages = 1, negativePrompt, aspectRatio, safetyFilterLevel, personFilterLevel }) {
    // Properties that are undefined will be omitted from the JSON string that is sent in the request.
    const body = {
        instances: [
            {
                prompt
            }
        ],
        parameters: {
            storageUri: gcsURI,
            negativePrompt,
            sampleCount: numberOfImages,
            aspectRatio,
            outputOptions: imageFormat,
            addWatermark,
            safetyFilterLevel,
            personGeneration: personFilterLevel,
            includeRaiReason: true,
            includeSafetyAttributes: true
        }
    };
    return body;
}

/**
 * @license
 * Copyright 2024 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
// https://ai.google.dev/api/rest/v1beta/Content#part
const VALID_PART_FIELDS = [
    'text',
    'inlineData',
    'functionCall',
    'functionResponse',
    'thought',
    'thoughtSignature'
];
const VALID_PARTS_PER_ROLE = {
    user: ['text', 'inlineData'],
    function: ['functionResponse'],
    model: ['text', 'functionCall', 'thought', 'thoughtSignature'],
    // System instructions shouldn't be in history anyway.
    system: ['text']
};
const VALID_PREVIOUS_CONTENT_ROLES = {
    user: ['model'],
    function: ['model'],
    model: ['user', 'function'],
    // System instructions shouldn't be in history.
    system: []
};
function validateChatHistory(history) {
    let prevContent = null;
    for (const currContent of history) {
        const { role, parts } = currContent;
        if (!prevContent && role !== 'user') {
            throw new AIError(AIErrorCode.INVALID_CONTENT, `First Content should be with role 'user', got ${role}`);
        }
        if (!POSSIBLE_ROLES.includes(role)) {
            throw new AIError(AIErrorCode.INVALID_CONTENT, `Each item should include role field. Got ${role} but valid roles are: ${JSON.stringify(POSSIBLE_ROLES)}`);
        }
        if (!Array.isArray(parts)) {
            throw new AIError(AIErrorCode.INVALID_CONTENT, `Content should have 'parts' property with an array of Parts`);
        }
        if (parts.length === 0) {
            throw new AIError(AIErrorCode.INVALID_CONTENT, `Each Content should have at least one part`);
        }
        const countFields = {
            text: 0,
            inlineData: 0,
            functionCall: 0,
            functionResponse: 0,
            thought: 0,
            thoughtSignature: 0,
            executableCode: 0,
            codeExecutionResult: 0
        };
        for (const part of parts) {
            for (const key of VALID_PART_FIELDS) {
                if (key in part) {
                    countFields[key] += 1;
                }
            }
        }
        const validParts = VALID_PARTS_PER_ROLE[role];
        for (const key of VALID_PART_FIELDS) {
            if (!validParts.includes(key) && countFields[key] > 0) {
                throw new AIError(AIErrorCode.INVALID_CONTENT, `Content with role '${role}' can't contain '${key}' part`);
            }
        }
        if (prevContent) {
            const validPreviousContentRoles = VALID_PREVIOUS_CONTENT_ROLES[role];
            if (!validPreviousContentRoles.includes(prevContent.role)) {
                throw new AIError(AIErrorCode.INVALID_CONTENT, `Content with role '${role}' can't follow '${prevContent.role}'. Valid previous roles: ${JSON.stringify(VALID_PREVIOUS_CONTENT_ROLES)}`);
            }
        }
        prevContent = currContent;
    }
}

/**
 * @license
 * Copyright 2024 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Do not log a message for this error.
 */
const SILENT_ERROR = 'SILENT_ERROR';
/**
 * ChatSession class that enables sending chat messages and stores
 * history of sent and received messages so far.
 *
 * @public
 */
class ChatSession {
    constructor(apiSettings, model, chromeAdapter, params, requestOptions) {
        this.model = model;
        this.chromeAdapter = chromeAdapter;
        this.params = params;
        this.requestOptions = requestOptions;
        this._history = [];
        this._sendPromise = Promise.resolve();
        this._apiSettings = apiSettings;
        if (params?.history) {
            validateChatHistory(params.history);
            this._history = params.history;
        }
    }
    /**
     * Gets the chat history so far. Blocked prompts are not added to history.
     * Neither blocked candidates nor the prompts that generated them are added
     * to history.
     */
    async getHistory() {
        await this._sendPromise;
        return this._history;
    }
    /**
     * Sends a chat message and receives a non-streaming
     * {@link GenerateContentResult}
     */
    async sendMessage(request) {
        await this._sendPromise;
        const newContent = formatNewContent(request);
        const generateContentRequest = {
            safetySettings: this.params?.safetySettings,
            generationConfig: this.params?.generationConfig,
            tools: this.params?.tools,
            toolConfig: this.params?.toolConfig,
            systemInstruction: this.params?.systemInstruction,
            contents: [...this._history, newContent]
        };
        let finalResult = {};
        // Add onto the chain.
        this._sendPromise = this._sendPromise
            .then(() => generateContent(this._apiSettings, this.model, generateContentRequest, this.chromeAdapter, this.requestOptions))
            .then(result => {
            if (result.response.candidates &&
                result.response.candidates.length > 0) {
                this._history.push(newContent);
                const responseContent = {
                    parts: result.response.candidates?.[0].content.parts || [],
                    // Response seems to come back without a role set.
                    role: result.response.candidates?.[0].content.role || 'model'
                };
                this._history.push(responseContent);
            }
            else {
                const blockErrorMessage = formatBlockErrorMessage(result.response);
                if (blockErrorMessage) {
                    logger.warn(`sendMessage() was unsuccessful. ${blockErrorMessage}. Inspect response object for details.`);
                }
            }
            finalResult = result;
        });
        await this._sendPromise;
        return finalResult;
    }
    /**
     * Sends a chat message and receives the response as a
     * {@link GenerateContentStreamResult} containing an iterable stream
     * and a response promise.
     */
    async sendMessageStream(request) {
        await this._sendPromise;
        const newContent = formatNewContent(request);
        const generateContentRequest = {
            safetySettings: this.params?.safetySettings,
            generationConfig: this.params?.generationConfig,
            tools: this.params?.tools,
            toolConfig: this.params?.toolConfig,
            systemInstruction: this.params?.systemInstruction,
            contents: [...this._history, newContent]
        };
        const streamPromise = generateContentStream(this._apiSettings, this.model, generateContentRequest, this.chromeAdapter, this.requestOptions);
        // Add onto the chain.
        this._sendPromise = this._sendPromise
            .then(() => streamPromise)
            // This must be handled to avoid unhandled rejection, but jump
            // to the final catch block with a label to not log this error.
            .catch(_ignored => {
            throw new Error(SILENT_ERROR);
        })
            .then(streamResult => streamResult.response)
            .then(response => {
            if (response.candidates && response.candidates.length > 0) {
                this._history.push(newContent);
                const responseContent = { ...response.candidates[0].content };
                // Response seems to come back without a role set.
                if (!responseContent.role) {
                    responseContent.role = 'model';
                }
                this._history.push(responseContent);
            }
            else {
                const blockErrorMessage = formatBlockErrorMessage(response);
                if (blockErrorMessage) {
                    logger.warn(`sendMessageStream() was unsuccessful. ${blockErrorMessage}. Inspect response object for details.`);
                }
            }
        })
            .catch(e => {
            // Errors in streamPromise are already catchable by the user as
            // streamPromise is returned.
            // Avoid duplicating the error message in logs.
            if (e.message !== SILENT_ERROR) {
                // Users do not have access to _sendPromise to catch errors
                // downstream from streamPromise, so they should not throw.
                logger.error(e);
            }
        });
        return streamPromise;
    }
}

/**
 * @license
 * Copyright 2024 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
async function countTokensOnCloud(apiSettings, model, params, requestOptions) {
    let body = '';
    if (apiSettings.backend.backendType === BackendType.GOOGLE_AI) {
        const mappedParams = mapCountTokensRequest(params, model);
        body = JSON.stringify(mappedParams);
    }
    else {
        body = JSON.stringify(params);
    }
    const response = await makeRequest(model, Task.COUNT_TOKENS, apiSettings, false, body, requestOptions);
    return response.json();
}
async function countTokens(apiSettings, model, params, chromeAdapter, requestOptions) {
    if (chromeAdapter?.mode === InferenceMode.ONLY_ON_DEVICE) {
        throw new AIError(AIErrorCode.UNSUPPORTED, 'countTokens() is not supported for on-device models.');
    }
    return countTokensOnCloud(apiSettings, model, params, requestOptions);
}

/**
 * @license
 * Copyright 2024 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Class for generative model APIs.
 * @public
 */
class GenerativeModel extends AIModel {
    constructor(ai, modelParams, requestOptions, chromeAdapter) {
        super(ai, modelParams.model);
        this.chromeAdapter = chromeAdapter;
        this.generationConfig = modelParams.generationConfig || {};
        this.safetySettings = modelParams.safetySettings || [];
        this.tools = modelParams.tools;
        this.toolConfig = modelParams.toolConfig;
        this.systemInstruction = formatSystemInstruction(modelParams.systemInstruction);
        this.requestOptions = requestOptions || {};
    }
    /**
     * Makes a single non-streaming call to the model
     * and returns an object containing a single {@link GenerateContentResponse}.
     */
    async generateContent(request) {
        const formattedParams = formatGenerateContentInput(request);
        return generateContent(this._apiSettings, this.model, {
            generationConfig: this.generationConfig,
            safetySettings: this.safetySettings,
            tools: this.tools,
            toolConfig: this.toolConfig,
            systemInstruction: this.systemInstruction,
            ...formattedParams
        }, this.chromeAdapter, this.requestOptions);
    }
    /**
     * Makes a single streaming call to the model
     * and returns an object containing an iterable stream that iterates
     * over all chunks in the streaming response as well as
     * a promise that returns the final aggregated response.
     */
    async generateContentStream(request) {
        const formattedParams = formatGenerateContentInput(request);
        return generateContentStream(this._apiSettings, this.model, {
            generationConfig: this.generationConfig,
            safetySettings: this.safetySettings,
            tools: this.tools,
            toolConfig: this.toolConfig,
            systemInstruction: this.systemInstruction,
            ...formattedParams
        }, this.chromeAdapter, this.requestOptions);
    }
    /**
     * Gets a new {@link ChatSession} instance which can be used for
     * multi-turn chats.
     */
    startChat(startChatParams) {
        return new ChatSession(this._apiSettings, this.model, this.chromeAdapter, {
            tools: this.tools,
            toolConfig: this.toolConfig,
            systemInstruction: this.systemInstruction,
            generationConfig: this.generationConfig,
            safetySettings: this.safetySettings,
            /**
             * Overrides params inherited from GenerativeModel with those explicitly set in the
             * StartChatParams. For example, if startChatParams.generationConfig is set, it'll override
             * this.generationConfig.
             */
            ...startChatParams
        }, this.requestOptions);
    }
    /**
     * Counts the tokens in the provided request.
     */
    async countTokens(request) {
        const formattedParams = formatGenerateContentInput(request);
        return countTokens(this._apiSettings, this.model, formattedParams, this.chromeAdapter);
    }
}

/**
 * @license
 * Copyright 2025 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Represents an active, real-time, bidirectional conversation with the model.
 *
 * This class should only be instantiated by calling {@link LiveGenerativeModel.connect}.
 *
 * @beta
 */
class LiveSession {
    /**
     * @internal
     */
    constructor(webSocketHandler, serverMessages) {
        this.webSocketHandler = webSocketHandler;
        this.serverMessages = serverMessages;
        /**
         * Indicates whether this Live session is closed.
         *
         * @beta
         */
        this.isClosed = false;
        /**
         * Indicates whether this Live session is being controlled by an `AudioConversationController`.
         *
         * @beta
         */
        this.inConversation = false;
    }
    /**
     * Sends content to the server.
     *
     * @param request - The message to send to the model.
     * @param turnComplete - Indicates if the turn is complete. Defaults to false.
     * @throws If this session has been closed.
     *
     * @beta
     */
    async send(request, turnComplete = true) {
        if (this.isClosed) {
            throw new AIError(AIErrorCode.REQUEST_ERROR, 'This LiveSession has been closed and cannot be used.');
        }
        const newContent = formatNewContent(request);
        const message = {
            clientContent: {
                turns: [newContent],
                turnComplete
            }
        };
        this.webSocketHandler.send(JSON.stringify(message));
    }
    /**
     * Sends text to the server in realtime.
     *
     * @example
     * ```javascript
     * liveSession.sendTextRealtime("Hello, how are you?");
     * ```
     *
     * @param text - The text data to send.
     * @throws If this session has been closed.
     *
     * @beta
     */
    async sendTextRealtime(text) {
        if (this.isClosed) {
            throw new AIError(AIErrorCode.REQUEST_ERROR, 'This LiveSession has been closed and cannot be used.');
        }
        const message = {
            realtimeInput: {
                text
            }
        };
        this.webSocketHandler.send(JSON.stringify(message));
    }
    /**
     * Sends audio data to the server in realtime.
     *
     * @remarks The server requires that the audio data is base64-encoded 16-bit PCM at 16kHz
     * little-endian.
     *
     * @example
     * ```javascript
     * // const pcmData = ... base64-encoded 16-bit PCM at 16kHz little-endian.
     * const blob = { mimeType: "audio/pcm", data: pcmData };
     * liveSession.sendAudioRealtime(blob);
     * ```
     *
     * @param blob - The base64-encoded PCM data to send to the server in realtime.
     * @throws If this session has been closed.
     *
     * @beta
     */
    async sendAudioRealtime(blob) {
        if (this.isClosed) {
            throw new AIError(AIErrorCode.REQUEST_ERROR, 'This LiveSession has been closed and cannot be used.');
        }
        const message = {
            realtimeInput: {
                audio: blob
            }
        };
        this.webSocketHandler.send(JSON.stringify(message));
    }
    /**
     * Sends video data to the server in realtime.
     *
     * @remarks The server requires that the video is sent as individual video frames at 1 FPS. It
     * is recommended to set `mimeType` to `image/jpeg`.
     *
     * @example
     * ```javascript
     * // const videoFrame = ... base64-encoded JPEG data
     * const blob = { mimeType: "image/jpeg", data: videoFrame };
     * liveSession.sendVideoRealtime(blob);
     * ```
     * @param blob - The base64-encoded video data to send to the server in realtime.
     * @throws If this session has been closed.
     *
     * @beta
     */
    async sendVideoRealtime(blob) {
        if (this.isClosed) {
            throw new AIError(AIErrorCode.REQUEST_ERROR, 'This LiveSession has been closed and cannot be used.');
        }
        const message = {
            realtimeInput: {
                video: blob
            }
        };
        this.webSocketHandler.send(JSON.stringify(message));
    }
    /**
     * Sends function responses to the server.
     *
     * @param functionResponses - The function responses to send.
     * @throws If this session has been closed.
     *
     * @beta
     */
    async sendFunctionResponses(functionResponses) {
        if (this.isClosed) {
            throw new AIError(AIErrorCode.REQUEST_ERROR, 'This LiveSession has been closed and cannot be used.');
        }
        const message = {
            toolResponse: {
                functionResponses
            }
        };
        this.webSocketHandler.send(JSON.stringify(message));
    }
    /**
     * Yields messages received from the server.
     * This can only be used by one consumer at a time.
     *
     * @returns An `AsyncGenerator` that yields server messages as they arrive.
     * @throws If the session is already closed, or if we receive a response that we don't support.
     *
     * @beta
     */
    async *receive() {
        if (this.isClosed) {
            throw new AIError(AIErrorCode.SESSION_CLOSED, 'Cannot read from a Live session that is closed. Try starting a new Live session.');
        }
        for await (const message of this.serverMessages) {
            if (message && typeof message === 'object') {
                if (LiveResponseType.SERVER_CONTENT in message) {
                    yield {
                        type: 'serverContent',
                        ...message
                            .serverContent
                    };
                }
                else if (LiveResponseType.TOOL_CALL in message) {
                    yield {
                        type: 'toolCall',
                        ...message
                            .toolCall
                    };
                }
                else if (LiveResponseType.TOOL_CALL_CANCELLATION in message) {
                    yield {
                        type: 'toolCallCancellation',
                        ...message.toolCallCancellation
                    };
                }
                else {
                    logger.warn(`Received an unknown message type from the server: ${JSON.stringify(message)}`);
                }
            }
            else {
                logger.warn(`Received an invalid message from the server: ${JSON.stringify(message)}`);
            }
        }
    }
    /**
     * Closes this session.
     * All methods on this session will throw an error once this resolves.
     *
     * @beta
     */
    async close() {
        if (!this.isClosed) {
            this.isClosed = true;
            await this.webSocketHandler.close(1000, 'Client closed session.');
        }
    }
    /**
     * Sends realtime input to the server.
     *
     * @deprecated Use `sendTextRealtime()`, `sendAudioRealtime()`, and `sendVideoRealtime()` instead.
     *
     * @param mediaChunks - The media chunks to send.
     * @throws If this session has been closed.
     *
     * @beta
     */
    async sendMediaChunks(mediaChunks) {
        if (this.isClosed) {
            throw new AIError(AIErrorCode.REQUEST_ERROR, 'This LiveSession has been closed and cannot be used.');
        }
        // The backend does not support sending more than one mediaChunk in one message.
        // Work around this limitation by sending mediaChunks in separate messages.
        mediaChunks.forEach(mediaChunk => {
            const message = {
                realtimeInput: { mediaChunks: [mediaChunk] }
            };
            this.webSocketHandler.send(JSON.stringify(message));
        });
    }
    /**
     * @deprecated Use `sendTextRealtime()`, `sendAudioRealtime()`, and `sendVideoRealtime()` instead.
     *
     * Sends a stream of {@link GenerativeContentBlob}.
     *
     * @param mediaChunkStream - The stream of {@link GenerativeContentBlob} to send.
     * @throws If this session has been closed.
     *
     * @beta
     */
    async sendMediaStream(mediaChunkStream) {
        if (this.isClosed) {
            throw new AIError(AIErrorCode.REQUEST_ERROR, 'This LiveSession has been closed and cannot be used.');
        }
        const reader = mediaChunkStream.getReader();
        while (true) {
            try {
                const { done, value } = await reader.read();
                if (done) {
                    break;
                }
                else if (!value) {
                    throw new Error('Missing chunk in reader, but reader is not done.');
                }
                await this.sendMediaChunks([value]);
            }
            catch (e) {
                // Re-throw any errors that occur during stream consumption or sending.
                const message = e instanceof Error ? e.message : 'Error processing media stream.';
                throw new AIError(AIErrorCode.REQUEST_ERROR, message);
            }
        }
    }
}

/**
 * @license
 * Copyright 2025 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Class for Live generative model APIs. The Live API enables low-latency, two-way multimodal
 * interactions with Gemini.
 *
 * This class should only be instantiated with {@link getLiveGenerativeModel}.
 *
 * @beta
 */
class LiveGenerativeModel extends AIModel {
    /**
     * @internal
     */
    constructor(ai, modelParams, 
    /**
     * @internal
     */
    _webSocketHandler) {
        super(ai, modelParams.model);
        this._webSocketHandler = _webSocketHandler;
        this.generationConfig = modelParams.generationConfig || {};
        this.tools = modelParams.tools;
        this.toolConfig = modelParams.toolConfig;
        this.systemInstruction = formatSystemInstruction(modelParams.systemInstruction);
    }
    /**
     * Starts a {@link LiveSession}.
     *
     * @returns A {@link LiveSession}.
     * @throws If the connection failed to be established with the server.
     *
     * @beta
     */
    async connect() {
        const url = new WebSocketUrl(this._apiSettings);
        await this._webSocketHandler.connect(url.toString());
        let fullModelPath;
        if (this._apiSettings.backend.backendType === BackendType.GOOGLE_AI) {
            fullModelPath = `projects/${this._apiSettings.project}/${this.model}`;
        }
        else {
            fullModelPath = `projects/${this._apiSettings.project}/locations/${this._apiSettings.location}/${this.model}`;
        }
        // inputAudioTranscription and outputAudioTranscription are on the generation config in the public API,
        // but the backend expects them to be in the `setup` message.
        const { inputAudioTranscription, outputAudioTranscription, ...generationConfig } = this.generationConfig;
        const setupMessage = {
            setup: {
                model: fullModelPath,
                generationConfig,
                tools: this.tools,
                toolConfig: this.toolConfig,
                systemInstruction: this.systemInstruction,
                inputAudioTranscription,
                outputAudioTranscription
            }
        };
        try {
            // Begin listening for server messages, and begin the handshake by sending the 'setupMessage'
            const serverMessages = this._webSocketHandler.listen();
            this._webSocketHandler.send(JSON.stringify(setupMessage));
            // Verify we received the handshake response 'setupComplete'
            const firstMessage = (await serverMessages.next()).value;
            if (!firstMessage ||
                !(typeof firstMessage === 'object') ||
                !('setupComplete' in firstMessage)) {
                await this._webSocketHandler.close(1011, 'Handshake failure');
                throw new AIError(AIErrorCode.RESPONSE_ERROR, 'Server connection handshake failed. The server did not respond with a setupComplete message.');
            }
            return new LiveSession(this._webSocketHandler, serverMessages);
        }
        catch (e) {
            // Ensure connection is closed on any setup error
            await this._webSocketHandler.close();
            throw e;
        }
    }
}

/**
 * @license
 * Copyright 2025 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Class for Imagen model APIs.
 *
 * This class provides methods for generating images using the Imagen model.
 *
 * @example
 * ```javascript
 * const imagen = new ImagenModel(
 *   ai,
 *   {
 *     model: 'imagen-3.0-generate-002'
 *   }
 * );
 *
 * const response = await imagen.generateImages('A photo of a cat');
 * if (response.images.length > 0) {
 *   console.log(response.images[0].bytesBase64Encoded);
 * }
 * ```
 *
 * @public
 */
class ImagenModel extends AIModel {
    /**
     * Constructs a new instance of the {@link ImagenModel} class.
     *
     * @param ai - an {@link AI} instance.
     * @param modelParams - Parameters to use when making requests to Imagen.
     * @param requestOptions - Additional options to use when making requests.
     *
     * @throws If the `apiKey` or `projectId` fields are missing in your
     * Firebase config.
     */
    constructor(ai, modelParams, requestOptions) {
        const { model, generationConfig, safetySettings } = modelParams;
        super(ai, model);
        this.requestOptions = requestOptions;
        this.generationConfig = generationConfig;
        this.safetySettings = safetySettings;
    }
    /**
     * Generates images using the Imagen model and returns them as
     * base64-encoded strings.
     *
     * @param prompt - A text prompt describing the image(s) to generate.
     * @returns A promise that resolves to an {@link ImagenGenerationResponse}
     * object containing the generated images.
     *
     * @throws If the request to generate images fails. This happens if the
     * prompt is blocked.
     *
     * @remarks
     * If the prompt was not blocked, but one or more of the generated images were filtered, the
     * returned object will have a `filteredReason` property.
     * If all images are filtered, the `images` array will be empty.
     *
     * @public
     */
    async generateImages(prompt) {
        const body = createPredictRequestBody(prompt, {
            ...this.generationConfig,
            ...this.safetySettings
        });
        const response = await makeRequest(this.model, Task.PREDICT, this._apiSettings, 
        /* stream */ false, JSON.stringify(body), this.requestOptions);
        return handlePredictResponse(response);
    }
    /**
     * Generates images to Cloud Storage for Firebase using the Imagen model.
     *
     * @internal This method is temporarily internal.
     *
     * @param prompt - A text prompt describing the image(s) to generate.
     * @param gcsURI - The URI of file stored in a Cloud Storage for Firebase bucket.
     * This should be a directory. For example, `gs://my-bucket/my-directory/`.
     * @returns A promise that resolves to an {@link ImagenGenerationResponse}
     * object containing the URLs of the generated images.
     *
     * @throws If the request fails to generate images fails. This happens if
     * the prompt is blocked.
     *
     * @remarks
     * If the prompt was not blocked, but one or more of the generated images were filtered, the
     * returned object will have a `filteredReason` property.
     * If all images are filtered, the `images` array will be empty.
     */
    async generateImagesGCS(prompt, gcsURI) {
        const body = createPredictRequestBody(prompt, {
            gcsURI,
            ...this.generationConfig,
            ...this.safetySettings
        });
        const response = await makeRequest(this.model, Task.PREDICT, this._apiSettings, 
        /* stream */ false, JSON.stringify(body), this.requestOptions);
        return handlePredictResponse(response);
    }
}

/**
 * @license
 * Copyright 2025 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * A wrapper for the native `WebSocket` available in both Browsers and Node >= 22.
 *
 * @internal
 */
class WebSocketHandlerImpl {
    constructor() {
        if (typeof WebSocket === 'undefined') {
            throw new AIError(AIErrorCode.UNSUPPORTED, 'The WebSocket API is not available in this environment. ' +
                'The "Live" feature is not supported here. It is supported in ' +
                'modern browser windows, Web Workers with WebSocket support, and Node >= 22.');
        }
    }
    connect(url) {
        return new Promise((resolve, reject) => {
            this.ws = new WebSocket(url);
            this.ws.binaryType = 'blob'; // Only important to set in Node
            this.ws.addEventListener('open', () => resolve(), { once: true });
            this.ws.addEventListener('error', () => reject(new AIError(AIErrorCode.FETCH_ERROR, `Error event raised on WebSocket`)), { once: true });
            this.ws.addEventListener('close', (closeEvent) => {
                if (closeEvent.reason) {
                    logger.warn(`WebSocket connection closed by server. Reason: '${closeEvent.reason}'`);
                }
            });
        });
    }
    send(data) {
        if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
            throw new AIError(AIErrorCode.REQUEST_ERROR, 'WebSocket is not open.');
        }
        this.ws.send(data);
    }
    async *listen() {
        if (!this.ws) {
            throw new AIError(AIErrorCode.REQUEST_ERROR, 'WebSocket is not connected.');
        }
        const messageQueue = [];
        const errorQueue = [];
        let resolvePromise = null;
        let isClosed = false;
        const messageListener = async (event) => {
            let data;
            if (event.data instanceof Blob) {
                data = await event.data.text();
            }
            else if (typeof event.data === 'string') {
                data = event.data;
            }
            else {
                errorQueue.push(new AIError(AIErrorCode.PARSE_FAILED, `Failed to parse WebSocket response. Expected data to be a Blob or string, but was ${typeof event.data}.`));
                if (resolvePromise) {
                    resolvePromise();
                    resolvePromise = null;
                }
                return;
            }
            try {
                const obj = JSON.parse(data);
                messageQueue.push(obj);
            }
            catch (e) {
                const err = e;
                errorQueue.push(new AIError(AIErrorCode.PARSE_FAILED, `Error parsing WebSocket message to JSON: ${err.message}`));
            }
            if (resolvePromise) {
                resolvePromise();
                resolvePromise = null;
            }
        };
        const errorListener = () => {
            errorQueue.push(new AIError(AIErrorCode.FETCH_ERROR, 'WebSocket connection error.'));
            if (resolvePromise) {
                resolvePromise();
                resolvePromise = null;
            }
        };
        const closeListener = (event) => {
            if (event.reason) {
                logger.warn(`WebSocket connection closed by the server with reason: ${event.reason}`);
            }
            isClosed = true;
            if (resolvePromise) {
                resolvePromise();
                resolvePromise = null;
            }
            // Clean up listeners to prevent memory leaks
            this.ws?.removeEventListener('message', messageListener);
            this.ws?.removeEventListener('close', closeListener);
            this.ws?.removeEventListener('error', errorListener);
        };
        this.ws.addEventListener('message', messageListener);
        this.ws.addEventListener('close', closeListener);
        this.ws.addEventListener('error', errorListener);
        while (!isClosed) {
            if (errorQueue.length > 0) {
                const error = errorQueue.shift();
                throw error;
            }
            if (messageQueue.length > 0) {
                yield messageQueue.shift();
            }
            else {
                await new Promise(resolve => {
                    resolvePromise = resolve;
                });
            }
        }
        // If the loop terminated because isClosed is true, check for any final errors
        if (errorQueue.length > 0) {
            const error = errorQueue.shift();
            throw error;
        }
    }
    close(code, reason) {
        return new Promise(resolve => {
            if (!this.ws) {
                return resolve();
            }
            this.ws.addEventListener('close', () => resolve(), { once: true });
            // Calling 'close' during these states results in an error.
            if (this.ws.readyState === WebSocket.CLOSED ||
                this.ws.readyState === WebSocket.CONNECTING) {
                return resolve();
            }
            if (this.ws.readyState !== WebSocket.CLOSING) {
                this.ws.close(code, reason);
            }
        });
    }
}

/**
 * @license
 * Copyright 2024 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Parent class encompassing all Schema types, with static methods that
 * allow building specific Schema types. This class can be converted with
 * `JSON.stringify()` into a JSON string accepted by Vertex AI REST endpoints.
 * (This string conversion is automatically done when calling SDK methods.)
 * @public
 */
class Schema {
    constructor(schemaParams) {
        // TODO(dlarocque): Enforce this with union types
        if (!schemaParams.type && !schemaParams.anyOf) {
            throw new AIError(AIErrorCode.INVALID_SCHEMA, "A schema must have either a 'type' or an 'anyOf' array of sub-schemas.");
        }
        // eslint-disable-next-line guard-for-in
        for (const paramKey in schemaParams) {
            this[paramKey] = schemaParams[paramKey];
        }
        // Ensure these are explicitly set to avoid TS errors.
        this.type = schemaParams.type;
        this.format = schemaParams.hasOwnProperty('format')
            ? schemaParams.format
            : undefined;
        this.nullable = schemaParams.hasOwnProperty('nullable')
            ? !!schemaParams.nullable
            : false;
    }
    /**
     * Defines how this Schema should be serialized as JSON.
     * See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#tojson_behavior
     * @internal
     */
    toJSON() {
        const obj = {
            type: this.type
        };
        for (const prop in this) {
            if (this.hasOwnProperty(prop) && this[prop] !== undefined) {
                if (prop !== 'required' || this.type === SchemaType.OBJECT) {
                    obj[prop] = this[prop];
                }
            }
        }
        return obj;
    }
    static array(arrayParams) {
        return new ArraySchema(arrayParams, arrayParams.items);
    }
    static object(objectParams) {
        return new ObjectSchema(objectParams, objectParams.properties, objectParams.optionalProperties);
    }
    // eslint-disable-next-line id-blacklist
    static string(stringParams) {
        return new StringSchema(stringParams);
    }
    static enumString(stringParams) {
        return new StringSchema(stringParams, stringParams.enum);
    }
    static integer(integerParams) {
        return new IntegerSchema(integerParams);
    }
    // eslint-disable-next-line id-blacklist
    static number(numberParams) {
        return new NumberSchema(numberParams);
    }
    // eslint-disable-next-line id-blacklist
    static boolean(booleanParams) {
        return new BooleanSchema(booleanParams);
    }
    static anyOf(anyOfParams) {
        return new AnyOfSchema(anyOfParams);
    }
}
/**
 * Schema class for "integer" types.
 * @public
 */
class IntegerSchema extends Schema {
    constructor(schemaParams) {
        super({
            type: SchemaType.INTEGER,
            ...schemaParams
        });
    }
}
/**
 * Schema class for "number" types.
 * @public
 */
class NumberSchema extends Schema {
    constructor(schemaParams) {
        super({
            type: SchemaType.NUMBER,
            ...schemaParams
        });
    }
}
/**
 * Schema class for "boolean" types.
 * @public
 */
class BooleanSchema extends Schema {
    constructor(schemaParams) {
        super({
            type: SchemaType.BOOLEAN,
            ...schemaParams
        });
    }
}
/**
 * Schema class for "string" types. Can be used with or without
 * enum values.
 * @public
 */
class StringSchema extends Schema {
    constructor(schemaParams, enumValues) {
        super({
            type: SchemaType.STRING,
            ...schemaParams
        });
        this.enum = enumValues;
    }
    /**
     * @internal
     */
    toJSON() {
        const obj = super.toJSON();
        if (this.enum) {
            obj['enum'] = this.enum;
        }
        return obj;
    }
}
/**
 * Schema class for "array" types.
 * The `items` param should refer to the type of item that can be a member
 * of the array.
 * @public
 */
class ArraySchema extends Schema {
    constructor(schemaParams, items) {
        super({
            type: SchemaType.ARRAY,
            ...schemaParams
        });
        this.items = items;
    }
    /**
     * @internal
     */
    toJSON() {
        const obj = super.toJSON();
        obj.items = this.items.toJSON();
        return obj;
    }
}
/**
 * Schema class for "object" types.
 * The `properties` param must be a map of `Schema` objects.
 * @public
 */
class ObjectSchema extends Schema {
    constructor(schemaParams, properties, optionalProperties = []) {
        super({
            type: SchemaType.OBJECT,
            ...schemaParams
        });
        this.properties = properties;
        this.optionalProperties = optionalProperties;
    }
    /**
     * @internal
     */
    toJSON() {
        const obj = super.toJSON();
        obj.properties = { ...this.properties };
        const required = [];
        if (this.optionalProperties) {
            for (const propertyKey of this.optionalProperties) {
                if (!this.properties.hasOwnProperty(propertyKey)) {
                    throw new AIError(AIErrorCode.INVALID_SCHEMA, `Property "${propertyKey}" specified in "optionalProperties" does not exist.`);
                }
            }
        }
        for (const propertyKey in this.properties) {
            if (this.properties.hasOwnProperty(propertyKey)) {
                obj.properties[propertyKey] = this.properties[propertyKey].toJSON();
                if (!this.optionalProperties.includes(propertyKey)) {
                    required.push(propertyKey);
                }
            }
        }
        if (required.length > 0) {
            obj.required = required;
        }
        delete obj.optionalProperties;
        return obj;
    }
}
/**
 * Schema class representing a value that can conform to any of the provided sub-schemas. This is
 * useful when a field can accept multiple distinct types or structures.
 * @public
 */
class AnyOfSchema extends Schema {
    constructor(schemaParams) {
        if (schemaParams.anyOf.length === 0) {
            throw new AIError(AIErrorCode.INVALID_SCHEMA, "The 'anyOf' array must not be empty.");
        }
        super({
            ...schemaParams,
            type: undefined // anyOf schemas do not have an explicit type
        });
        this.anyOf = schemaParams.anyOf;
    }
    /**
     * @internal
     */
    toJSON() {
        const obj = super.toJSON();
        // Ensure the 'anyOf' property contains serialized SchemaRequest objects.
        if (this.anyOf && Array.isArray(this.anyOf)) {
            obj.anyOf = this.anyOf.map(s => s.toJSON());
        }
        return obj;
    }
}

/**
 * @license
 * Copyright 2025 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Defines the image format for images generated by Imagen.
 *
 * Use this class to specify the desired format (JPEG or PNG) and compression quality
 * for images generated by Imagen. This is typically included as part of
 * {@link ImagenModelParams}.
 *
 * @example
 * ```javascript
 * const imagenModelParams = {
 *   // ... other ImagenModelParams
 *   imageFormat: ImagenImageFormat.jpeg(75) // JPEG with a compression level of 75.
 * }
 * ```
 *
 * @public
 */
class ImagenImageFormat {
    constructor() {
        this.mimeType = 'image/png';
    }
    /**
     * Creates an {@link ImagenImageFormat} for a JPEG image.
     *
     * @param compressionQuality - The level of compression (a number between 0 and 100).
     * @returns An {@link ImagenImageFormat} object for a JPEG image.
     *
     * @public
     */
    static jpeg(compressionQuality) {
        if (compressionQuality &&
            (compressionQuality < 0 || compressionQuality > 100)) {
            logger.warn(`Invalid JPEG compression quality of ${compressionQuality} specified; the supported range is [0, 100].`);
        }
        return { mimeType: 'image/jpeg', compressionQuality };
    }
    /**
     * Creates an {@link ImagenImageFormat} for a PNG image.
     *
     * @returns An {@link ImagenImageFormat} object for a PNG image.
     *
     * @public
     */
    static png() {
        return { mimeType: 'image/png' };
    }
}

/**
 * @license
 * Copyright 2025 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
const SERVER_INPUT_SAMPLE_RATE = 16000;
const SERVER_OUTPUT_SAMPLE_RATE = 24000;
const AUDIO_PROCESSOR_NAME = 'audio-processor';
/**
 * The JS for an `AudioWorkletProcessor`.
 * This processor is responsible for taking raw audio from the microphone,
 * converting it to the required 16-bit 16kHz PCM, and posting it back to the main thread.
 *
 * See: https://developer.mozilla.org/en-US/docs/Web/API/AudioWorkletProcessor
 *
 * It is defined as a string here so that it can be converted into a `Blob`
 * and loaded at runtime.
 */
const audioProcessorWorkletString = `
  class AudioProcessor extends AudioWorkletProcessor {
    constructor(options) {
      super();
      this.targetSampleRate = options.processorOptions.targetSampleRate;
      // 'sampleRate' is a global variable available inside the AudioWorkletGlobalScope,
      // representing the native sample rate of the AudioContext.
      this.inputSampleRate = sampleRate;
    }

    /**
     * This method is called by the browser's audio engine for each block of audio data.
     * Input is a single input, with a single channel (input[0][0]).
     */
    process(inputs) {
      const input = inputs[0];
      if (input && input.length > 0 && input[0].length > 0) {
        const pcmData = input[0]; // Float32Array of raw audio samples.
        
        // Simple linear interpolation for resampling.
        const resampled = new Float32Array(Math.round(pcmData.length * this.targetSampleRate / this.inputSampleRate));
        const ratio = pcmData.length / resampled.length;
        for (let i = 0; i < resampled.length; i++) {
          resampled[i] = pcmData[Math.floor(i * ratio)];
        }

        // Convert Float32 (-1, 1) samples to Int16 (-32768, 32767)
        const resampledInt16 = new Int16Array(resampled.length);
        for (let i = 0; i < resampled.length; i++) {
          const sample = Math.max(-1, Math.min(1, resampled[i]));
          if (sample < 0) {
            resampledInt16[i] = sample * 32768;
          } else {
            resampledInt16[i] = sample * 32767;
          }
        }
        
        this.port.postMessage(resampledInt16);
      }
      // Return true to keep the processor alive and processing the next audio block.
      return true;
    }
  }

  // Register the processor with a name that can be used to instantiate it from the main thread.
  registerProcessor('${AUDIO_PROCESSOR_NAME}', AudioProcessor);
`;
/**
 * Encapsulates the core logic of an audio conversation.
 *
 * @internal
 */
class AudioConversationRunner {
    constructor(liveSession, options, deps) {
        this.liveSession = liveSession;
        this.options = options;
        this.deps = deps;
        /** A flag to indicate if the conversation has been stopped. */
        this.isStopped = false;
        /** A deferred that contains a promise that is resolved when stop() is called, to unblock the receive loop. */
        this.stopDeferred = new util.Deferred();
        /** A FIFO queue of 24kHz, 16-bit PCM audio chunks received from the server. */
        this.playbackQueue = [];
        /** Tracks scheduled audio sources. Used to cancel scheduled audio when the model is interrupted. */
        this.scheduledSources = [];
        /** A high-precision timeline pointer for scheduling gapless audio playback. */
        this.nextStartTime = 0;
        /** A mutex to prevent the playback processing loop from running multiple times concurrently. */
        this.isPlaybackLoopRunning = false;
        this.liveSession.inConversation = true;
        // Start listening for messages from the server.
        this.receiveLoopPromise = this.runReceiveLoop().finally(() => this.cleanup());
        // Set up the handler for receiving processed audio data from the worklet.
        // Message data has been resampled to 16kHz 16-bit PCM.
        this.deps.workletNode.port.onmessage = event => {
            if (this.isStopped) {
                return;
            }
            const pcm16 = event.data;
            const base64 = btoa(String.fromCharCode.apply(null, Array.from(new Uint8Array(pcm16.buffer))));
            const chunk = {
                mimeType: 'audio/pcm',
                data: base64
            };
            void this.liveSession.sendAudioRealtime(chunk);
        };
    }
    /**
     * Stops the conversation and unblocks the main receive loop.
     */
    async stop() {
        if (this.isStopped) {
            return;
        }
        this.isStopped = true;
        this.stopDeferred.resolve(); // Unblock the receive loop
        await this.receiveLoopPromise; // Wait for the loop and cleanup to finish
    }
    /**
     * Cleans up all audio resources (nodes, stream tracks, context) and marks the
     * session as no longer in a conversation.
     */
    cleanup() {
        this.interruptPlayback(); // Ensure all audio is stopped on final cleanup.
        this.deps.workletNode.port.onmessage = null;
        this.deps.workletNode.disconnect();
        this.deps.sourceNode.disconnect();
        this.deps.mediaStream.getTracks().forEach(track => track.stop());
        if (this.deps.audioContext.state !== 'closed') {
            void this.deps.audioContext.close();
        }
        this.liveSession.inConversation = false;
    }
    /**
     * Adds audio data to the queue and ensures the playback loop is running.
     */
    enqueueAndPlay(audioData) {
        this.playbackQueue.push(audioData);
        // Will no-op if it's already running.
        void this.processPlaybackQueue();
    }
    /**
     * Stops all current and pending audio playback and clears the queue. This is
     * called when the server indicates the model's speech was interrupted with
     * `LiveServerContent.modelTurn.interrupted`.
     */
    interruptPlayback() {
        // Stop all sources that have been scheduled. The onended event will fire for each,
        // which will clean up the scheduledSources array.
        [...this.scheduledSources].forEach(source => source.stop(0));
        // Clear the internal buffer of unprocessed audio chunks.
        this.playbackQueue.length = 0;
        // Reset the playback clock to start fresh.
        this.nextStartTime = this.deps.audioContext.currentTime;
    }
    /**
     * Processes the playback queue in a loop, scheduling each chunk in a gapless sequence.
     */
    async processPlaybackQueue() {
        if (this.isPlaybackLoopRunning) {
            return;
        }
        this.isPlaybackLoopRunning = true;
        while (this.playbackQueue.length > 0 && !this.isStopped) {
            const pcmRawBuffer = this.playbackQueue.shift();
            try {
                const pcm16 = new Int16Array(pcmRawBuffer);
                const frameCount = pcm16.length;
                const audioBuffer = this.deps.audioContext.createBuffer(1, frameCount, SERVER_OUTPUT_SAMPLE_RATE);
                // Convert 16-bit PCM to 32-bit PCM, required by the Web Audio API.
                const channelData = audioBuffer.getChannelData(0);
                for (let i = 0; i < frameCount; i++) {
                    channelData[i] = pcm16[i] / 32768; // Normalize to Float32 range [-1.0, 1.0]
                }
                const source = this.deps.audioContext.createBufferSource();
                source.buffer = audioBuffer;
                source.connect(this.deps.audioContext.destination);
                // Track the source and set up a handler to remove it from tracking when it finishes.
                this.scheduledSources.push(source);
                source.onended = () => {
                    this.scheduledSources = this.scheduledSources.filter(s => s !== source);
                };
                // To prevent gaps, schedule the next chunk to start either now (if we're catching up)
                // or exactly when the previous chunk is scheduled to end.
                this.nextStartTime = Math.max(this.deps.audioContext.currentTime, this.nextStartTime);
                source.start(this.nextStartTime);
                // Update the schedule for the *next* chunk.
                this.nextStartTime += audioBuffer.duration;
            }
            catch (e) {
                logger.error('Error playing audio:', e);
            }
        }
        this.isPlaybackLoopRunning = false;
    }
    /**
     * The main loop that listens for and processes messages from the server.
     */
    async runReceiveLoop() {
        const messageGenerator = this.liveSession.receive();
        while (!this.isStopped) {
            const result = await Promise.race([
                messageGenerator.next(),
                this.stopDeferred.promise
            ]);
            if (this.isStopped || !result || result.done) {
                break;
            }
            const message = result.value;
            if (message.type === 'serverContent') {
                const serverContent = message;
                if (serverContent.interrupted) {
                    this.interruptPlayback();
                }
                const audioPart = serverContent.modelTurn?.parts.find(part => part.inlineData?.mimeType.startsWith('audio/'));
                if (audioPart?.inlineData) {
                    const audioData = Uint8Array.from(atob(audioPart.inlineData.data), c => c.charCodeAt(0)).buffer;
                    this.enqueueAndPlay(audioData);
                }
            }
            else if (message.type === 'toolCall') {
                if (!this.options.functionCallingHandler) {
                    logger.warn('Received tool call message, but StartAudioConversationOptions.functionCallingHandler is undefined. Ignoring tool call.');
                }
                else {
                    try {
                        const functionResponse = await this.options.functionCallingHandler(message.functionCalls);
                        if (!this.isStopped) {
                            void this.liveSession.sendFunctionResponses([functionResponse]);
                        }
                    }
                    catch (e) {
                        throw new AIError(AIErrorCode.ERROR, `Function calling handler failed: ${e.message}`);
                    }
                }
            }
        }
    }
}
/**
 * Starts a real-time, bidirectional audio conversation with the model. This helper function manages
 * the complexities of microphone access, audio recording, playback, and interruptions.
 *
 * @remarks Important: This function must be called in response to a user gesture
 * (for example, a button click) to comply with {@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API/Best_practices#autoplay_policy | browser autoplay policies}.
 *
 * @example
 * ```javascript
 * const liveSession = await model.connect();
 * let conversationController;
 *
 * // This function must be called from within a click handler.
 * async function startConversation() {
 *   try {
 *     conversationController = await startAudioConversation(liveSession);
 *   } catch (e) {
 *     // Handle AI-specific errors
 *     if (e instanceof AIError) {
 *       console.error("AI Error:", e.message);
 *     }
 *     // Handle microphone permission and hardware errors
 *     else if (e instanceof DOMException) {
 *       console.error("Microphone Error:", e.message);
 *     }
 *     // Handle other unexpected errors
 *     else {
 *       console.error("An unexpected error occurred:", e);
 *     }
 *   }
 * }
 *
 * // Later, to stop the conversation:
 * // if (conversationController) {
 * //   await conversationController.stop();
 * // }
 * ```
 *
 * @param liveSession - An active {@link LiveSession} instance.
 * @param options - Configuration options for the audio conversation.
 * @returns A `Promise` that resolves with an {@link AudioConversationController}.
 * @throws `AIError` if the environment does not support required Web APIs (`UNSUPPORTED`), if a conversation is already active (`REQUEST_ERROR`), the session is closed (`SESSION_CLOSED`), or if an unexpected initialization error occurs (`ERROR`).
 * @throws `DOMException` Thrown by `navigator.mediaDevices.getUserMedia()` if issues occur with microphone access, such as permissions being denied (`NotAllowedError`) or no compatible hardware being found (`NotFoundError`). See the {@link https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia#exceptions | MDN documentation} for a full list of exceptions.
 *
 * @beta
 */
async function startAudioConversation(liveSession, options = {}) {
    if (liveSession.isClosed) {
        throw new AIError(AIErrorCode.SESSION_CLOSED, 'Cannot start audio conversation on a closed LiveSession.');
    }
    if (liveSession.inConversation) {
        throw new AIError(AIErrorCode.REQUEST_ERROR, 'An audio conversation is already in progress for this session.');
    }
    // Check for necessary Web API support.
    if (typeof AudioWorkletNode === 'undefined' ||
        typeof AudioContext === 'undefined' ||
        typeof navigator === 'undefined' ||
        !navigator.mediaDevices) {
        throw new AIError(AIErrorCode.UNSUPPORTED, 'Audio conversation is not supported in this environment. It requires the Web Audio API and AudioWorklet support.');
    }
    let audioContext;
    try {
        // 1. Set up the audio context. This must be in response to a user gesture.
        // See: https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API/Best_practices#autoplay_policy
        audioContext = new AudioContext();
        if (audioContext.state === 'suspended') {
            await audioContext.resume();
        }
        // 2. Prompt for microphone access and get the media stream.
        // This can throw a variety of permission or hardware-related errors.
        const mediaStream = await navigator.mediaDevices.getUserMedia({
            audio: true
        });
        // 3. Load the AudioWorklet processor.
        // See: https://developer.mozilla.org/en-US/docs/Web/API/AudioWorklet
        const workletBlob = new Blob([audioProcessorWorkletString], {
            type: 'application/javascript'
        });
        const workletURL = URL.createObjectURL(workletBlob);
        await audioContext.audioWorklet.addModule(workletURL);
        // 4. Create the audio graph: Microphone -> Source Node -> Worklet Node
        const sourceNode = audioContext.createMediaStreamSource(mediaStream);
        const workletNode = new AudioWorkletNode(audioContext, AUDIO_PROCESSOR_NAME, {
            processorOptions: { targetSampleRate: SERVER_INPUT_SAMPLE_RATE }
        });
        sourceNode.connect(workletNode);
        // 5. Instantiate and return the runner which manages the conversation.
        const runner = new AudioConversationRunner(liveSession, options, {
            audioContext,
            mediaStream,
            sourceNode,
            workletNode
        });
        return { stop: () => runner.stop() };
    }
    catch (e) {
        // Ensure the audio context is closed on any setup error.
        if (audioContext && audioContext.state !== 'closed') {
            void audioContext.close();
        }
        // Re-throw specific, known error types directly. The user may want to handle `DOMException`
        // errors differently (for example, if permission to access audio device was denied).
        if (e instanceof AIError || e instanceof DOMException) {
            throw e;
        }
        // Wrap any other unexpected errors in a standard AIError.
        throw new AIError(AIErrorCode.ERROR, `Failed to initialize audio recording: ${e.message}`);
    }
}

/**
 * @license
 * Copyright 2024 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Returns the default {@link AI} instance that is associated with the provided
 * {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new instance with the
 * default settings.
 *
 * @example
 * ```javascript
 * const ai = getAI(app);
 * ```
 *
 * @example
 * ```javascript
 * // Get an AI instance configured to use the Gemini Developer API (via Google AI).
 * const ai = getAI(app, { backend: new GoogleAIBackend() });
 * ```
 *
 * @example
 * ```javascript
 * // Get an AI instance configured to use the Vertex AI Gemini API.
 * const ai = getAI(app, { backend: new VertexAIBackend() });
 * ```
 *
 * @param app - The {@link @firebase/app#FirebaseApp} to use.
 * @param options - {@link AIOptions} that configure the AI instance.
 * @returns The default {@link AI} instance for the given {@link @firebase/app#FirebaseApp}.
 *
 * @public
 */
function getAI(app$1 = app.getApp(), options) {
    app$1 = util.getModularInstance(app$1);
    // Dependencies
    const AIProvider = app._getProvider(app$1, AI_TYPE);
    const backend = options?.backend ?? new GoogleAIBackend();
    const finalOptions = {
        useLimitedUseAppCheckTokens: options?.useLimitedUseAppCheckTokens ?? false
    };
    const identifier = encodeInstanceIdentifier(backend);
    const aiInstance = AIProvider.getImmediate({
        identifier
    });
    aiInstance.options = finalOptions;
    return aiInstance;
}
/**
 * Returns a {@link GenerativeModel} class with methods for inference
 * and other functionality.
 *
 * @public
 */
function getGenerativeModel(ai, modelParams, requestOptions) {
    // Uses the existence of HybridParams.mode to clarify the type of the modelParams input.
    const hybridParams = modelParams;
    let inCloudParams;
    if (hybridParams.mode) {
        inCloudParams = hybridParams.inCloudParams || {
            model: DEFAULT_HYBRID_IN_CLOUD_MODEL
        };
    }
    else {
        inCloudParams = modelParams;
    }
    if (!inCloudParams.model) {
        throw new AIError(AIErrorCode.NO_MODEL, `Must provide a model name. Example: getGenerativeModel({ model: 'my-model-name' })`);
    }
    /**
     * An AIService registered by index.node.ts will not have a
     * chromeAdapterFactory() method.
     */
    const chromeAdapter = ai.chromeAdapterFactory?.(hybridParams.mode, typeof window === 'undefined' ? undefined : window, hybridParams.onDeviceParams);
    return new GenerativeModel(ai, inCloudParams, requestOptions, chromeAdapter);
}
/**
 * Returns an {@link ImagenModel} class with methods for using Imagen.
 *
 * Only Imagen 3 models (named `imagen-3.0-*`) are supported.
 *
 * @param ai - An {@link AI} instance.
 * @param modelParams - Parameters to use when making Imagen requests.
 * @param requestOptions - Additional options to use when making requests.
 *
 * @throws If the `apiKey` or `projectId` fields are missing in your
 * Firebase config.
 *
 * @public
 */
function getImagenModel(ai, modelParams, requestOptions) {
    if (!modelParams.model) {
        throw new AIError(AIErrorCode.NO_MODEL, `Must provide a model name. Example: getImagenModel({ model: 'my-model-name' })`);
    }
    return new ImagenModel(ai, modelParams, requestOptions);
}
/**
 * Returns a {@link LiveGenerativeModel} class for real-time, bidirectional communication.
 *
 * The Live API is only supported in modern browser windows and Node >= 22.
 *
 * @param ai - An {@link AI} instance.
 * @param modelParams - Parameters to use when setting up a {@link LiveSession}.
 * @throws If the `apiKey` or `projectId` fields are missing in your
 * Firebase config.
 *
 * @beta
 */
function getLiveGenerativeModel(ai, modelParams) {
    if (!modelParams.model) {
        throw new AIError(AIErrorCode.NO_MODEL, `Must provide a model name for getLiveGenerativeModel. Example: getLiveGenerativeModel(ai, { model: 'my-model-name' })`);
    }
    const webSocketHandler = new WebSocketHandlerImpl();
    return new LiveGenerativeModel(ai, modelParams, webSocketHandler);
}

/**
 * The Firebase AI Web SDK.
 *
 * @packageDocumentation
 */
function registerAI() {
    app._registerComponent(new component.Component(AI_TYPE, factory, "PUBLIC" /* ComponentType.PUBLIC */).setMultipleInstances(true));
    app.registerVersion(name, version);
    // BUILD_TARGET will be replaced by values like esm, cjs, etc during the compilation
    app.registerVersion(name, version, 'cjs2020');
}
registerAI();

exports.AIError = AIError;
exports.AIErrorCode = AIErrorCode;
exports.AIModel = AIModel;
exports.AnyOfSchema = AnyOfSchema;
exports.ArraySchema = ArraySchema;
exports.Backend = Backend;
exports.BackendType = BackendType;
exports.BlockReason = BlockReason;
exports.BooleanSchema = BooleanSchema;
exports.ChatSession = ChatSession;
exports.FinishReason = FinishReason;
exports.FunctionCallingMode = FunctionCallingMode;
exports.GenerativeModel = GenerativeModel;
exports.GoogleAIBackend = GoogleAIBackend;
exports.HarmBlockMethod = HarmBlockMethod;
exports.HarmBlockThreshold = HarmBlockThreshold;
exports.HarmCategory = HarmCategory;
exports.HarmProbability = HarmProbability;
exports.HarmSeverity = HarmSeverity;
exports.ImagenAspectRatio = ImagenAspectRatio;
exports.ImagenImageFormat = ImagenImageFormat;
exports.ImagenModel = ImagenModel;
exports.ImagenPersonFilterLevel = ImagenPersonFilterLevel;
exports.ImagenSafetyFilterLevel = ImagenSafetyFilterLevel;
exports.InferenceMode = InferenceMode;
exports.InferenceSource = InferenceSource;
exports.IntegerSchema = IntegerSchema;
exports.Language = Language;
exports.LiveGenerativeModel = LiveGenerativeModel;
exports.LiveResponseType = LiveResponseType;
exports.LiveSession = LiveSession;
exports.Modality = Modality;
exports.NumberSchema = NumberSchema;
exports.ObjectSchema = ObjectSchema;
exports.Outcome = Outcome;
exports.POSSIBLE_ROLES = POSSIBLE_ROLES;
exports.ResponseModality = ResponseModality;
exports.Schema = Schema;
exports.SchemaType = SchemaType;
exports.StringSchema = StringSchema;
exports.URLRetrievalStatus = URLRetrievalStatus;
exports.VertexAIBackend = VertexAIBackend;
exports.getAI = getAI;
exports.getGenerativeModel = getGenerativeModel;
exports.getImagenModel = getImagenModel;
exports.getLiveGenerativeModel = getLiveGenerativeModel;
exports.startAudioConversation = startAudioConversation;
//# sourceMappingURL=index.cjs.js.map