diff --git a/.gitignore b/.gitignore index a5319209b51f9..b537017d63e5c 100644 --- a/.gitignore +++ b/.gitignore @@ -17,6 +17,7 @@ tags *.gcov *.tsbuildinfo compile_commands.json +*.env # emacs backup files in any directory. # lint-ignore-next-line: syntax-difference @@ -393,6 +394,10 @@ toolkit/crashreporter/minidump-analyzer/target/ # Ignore mozperftest artifacts folder /artifacts/ +# Distribution packages (generated files) +Oasis-Browser-*.dmg +Oasis-Browser-*.zip + # Ignore personal preferences files CLAUDE.local.md diff --git a/.lto.o/0.arm64.lto.o b/.lto.o/0.arm64.lto.o new file mode 100644 index 0000000000000..45008c435d4d2 Binary files /dev/null and b/.lto.o/0.arm64.lto.o differ diff --git a/.lto.o/1.arm64.lto.o b/.lto.o/1.arm64.lto.o new file mode 100644 index 0000000000000..6ee1490778979 Binary files /dev/null and b/.lto.o/1.arm64.lto.o differ diff --git a/.lto.o/10.arm64.lto.o b/.lto.o/10.arm64.lto.o new file mode 100644 index 0000000000000..9820cca19383a Binary files /dev/null and b/.lto.o/10.arm64.lto.o differ diff --git a/.lto.o/100.arm64.lto.o b/.lto.o/100.arm64.lto.o new file mode 100644 index 0000000000000..26590a0b6ba13 Binary files /dev/null and b/.lto.o/100.arm64.lto.o differ diff --git a/.lto.o/101.arm64.lto.o b/.lto.o/101.arm64.lto.o new file mode 100644 index 0000000000000..7f6b01b0024ee Binary files /dev/null and b/.lto.o/101.arm64.lto.o differ diff --git a/.lto.o/102.arm64.lto.o b/.lto.o/102.arm64.lto.o new file mode 100644 index 0000000000000..bff1c07f3dce7 Binary files /dev/null and b/.lto.o/102.arm64.lto.o differ diff --git a/.lto.o/103.arm64.lto.o b/.lto.o/103.arm64.lto.o new file mode 100644 index 0000000000000..99c4c46b14104 Binary files /dev/null and b/.lto.o/103.arm64.lto.o differ diff --git a/.lto.o/104.arm64.lto.o b/.lto.o/104.arm64.lto.o new file mode 100644 index 0000000000000..2c13d9dd898f4 Binary files /dev/null and b/.lto.o/104.arm64.lto.o differ diff --git a/.lto.o/105.arm64.lto.o b/.lto.o/105.arm64.lto.o new file mode 100644 index 0000000000000..72e69821ce2dc Binary files /dev/null and b/.lto.o/105.arm64.lto.o differ diff --git a/.lto.o/106.arm64.lto.o b/.lto.o/106.arm64.lto.o new file mode 100644 index 0000000000000..d900d8db31c91 Binary files /dev/null and b/.lto.o/106.arm64.lto.o differ diff --git a/.lto.o/107.arm64.lto.o b/.lto.o/107.arm64.lto.o new file mode 100644 index 0000000000000..693e18d1eb200 Binary files /dev/null and b/.lto.o/107.arm64.lto.o differ diff --git a/.lto.o/108.arm64.lto.o b/.lto.o/108.arm64.lto.o new file mode 100644 index 0000000000000..8dfec7fb8fac4 Binary files /dev/null and b/.lto.o/108.arm64.lto.o differ diff --git a/.lto.o/109.arm64.lto.o b/.lto.o/109.arm64.lto.o new file mode 100644 index 0000000000000..31c44cea8abc7 Binary files /dev/null and b/.lto.o/109.arm64.lto.o differ diff --git a/.lto.o/11.arm64.lto.o b/.lto.o/11.arm64.lto.o new file mode 100644 index 0000000000000..ca02ca4d84f99 Binary files /dev/null and b/.lto.o/11.arm64.lto.o differ diff --git a/.lto.o/12.arm64.lto.o b/.lto.o/12.arm64.lto.o new file mode 100644 index 0000000000000..34a05092bd36d Binary files /dev/null and b/.lto.o/12.arm64.lto.o differ diff --git a/.lto.o/13.arm64.lto.o b/.lto.o/13.arm64.lto.o new file mode 100644 index 0000000000000..267e364426ffa Binary files /dev/null and b/.lto.o/13.arm64.lto.o differ diff --git a/.lto.o/14.arm64.lto.o b/.lto.o/14.arm64.lto.o new file mode 100644 index 0000000000000..15f1286bb9b9a Binary files /dev/null and b/.lto.o/14.arm64.lto.o differ diff --git a/.lto.o/15.arm64.lto.o b/.lto.o/15.arm64.lto.o new file mode 100644 index 0000000000000..ae327fc68ded3 Binary files /dev/null and b/.lto.o/15.arm64.lto.o differ diff --git a/.lto.o/16.arm64.lto.o b/.lto.o/16.arm64.lto.o new file mode 100644 index 0000000000000..b302fcad5274a Binary files /dev/null and b/.lto.o/16.arm64.lto.o differ diff --git a/.lto.o/17.arm64.lto.o b/.lto.o/17.arm64.lto.o new file mode 100644 index 0000000000000..b76a4ab352cce Binary files /dev/null and b/.lto.o/17.arm64.lto.o differ diff --git a/.lto.o/18.arm64.lto.o b/.lto.o/18.arm64.lto.o new file mode 100644 index 0000000000000..058fd1f00a747 Binary files /dev/null and b/.lto.o/18.arm64.lto.o differ diff --git a/.lto.o/19.arm64.lto.o b/.lto.o/19.arm64.lto.o new file mode 100644 index 0000000000000..f1ee67439516f Binary files /dev/null and b/.lto.o/19.arm64.lto.o differ diff --git a/.lto.o/2.arm64.lto.o b/.lto.o/2.arm64.lto.o new file mode 100644 index 0000000000000..28608678a369c Binary files /dev/null and b/.lto.o/2.arm64.lto.o differ diff --git a/.lto.o/20.arm64.lto.o b/.lto.o/20.arm64.lto.o new file mode 100644 index 0000000000000..fa089ed3ca984 Binary files /dev/null and b/.lto.o/20.arm64.lto.o differ diff --git a/.lto.o/21.arm64.lto.o b/.lto.o/21.arm64.lto.o new file mode 100644 index 0000000000000..6108292484ff6 Binary files /dev/null and b/.lto.o/21.arm64.lto.o differ diff --git a/.lto.o/22.arm64.lto.o b/.lto.o/22.arm64.lto.o new file mode 100644 index 0000000000000..aaf7ea53d3383 Binary files /dev/null and b/.lto.o/22.arm64.lto.o differ diff --git a/.lto.o/23.arm64.lto.o b/.lto.o/23.arm64.lto.o new file mode 100644 index 0000000000000..d7cc924def1c5 Binary files /dev/null and b/.lto.o/23.arm64.lto.o differ diff --git a/.lto.o/24.arm64.lto.o b/.lto.o/24.arm64.lto.o new file mode 100644 index 0000000000000..1c0cc111ff884 Binary files /dev/null and b/.lto.o/24.arm64.lto.o differ diff --git a/.lto.o/25.arm64.lto.o b/.lto.o/25.arm64.lto.o new file mode 100644 index 0000000000000..496fb74f6ad5e Binary files /dev/null and b/.lto.o/25.arm64.lto.o differ diff --git a/.lto.o/26.arm64.lto.o b/.lto.o/26.arm64.lto.o new file mode 100644 index 0000000000000..7b664a0351a7d Binary files /dev/null and b/.lto.o/26.arm64.lto.o differ diff --git a/.lto.o/27.arm64.lto.o b/.lto.o/27.arm64.lto.o new file mode 100644 index 0000000000000..93aeea5ca6fc6 Binary files /dev/null and b/.lto.o/27.arm64.lto.o differ diff --git a/.lto.o/28.arm64.lto.o b/.lto.o/28.arm64.lto.o new file mode 100644 index 0000000000000..7e47643b20dc3 Binary files /dev/null and b/.lto.o/28.arm64.lto.o differ diff --git a/.lto.o/29.arm64.lto.o b/.lto.o/29.arm64.lto.o new file mode 100644 index 0000000000000..5ea715202421c Binary files /dev/null and b/.lto.o/29.arm64.lto.o differ diff --git a/.lto.o/3.arm64.lto.o b/.lto.o/3.arm64.lto.o new file mode 100644 index 0000000000000..bbfd9a064947e Binary files /dev/null and b/.lto.o/3.arm64.lto.o differ diff --git a/.lto.o/30.arm64.lto.o b/.lto.o/30.arm64.lto.o new file mode 100644 index 0000000000000..af7cf0d1709e0 Binary files /dev/null and b/.lto.o/30.arm64.lto.o differ diff --git a/.lto.o/31.arm64.lto.o b/.lto.o/31.arm64.lto.o new file mode 100644 index 0000000000000..94819faf5fce1 Binary files /dev/null and b/.lto.o/31.arm64.lto.o differ diff --git a/.lto.o/32.arm64.lto.o b/.lto.o/32.arm64.lto.o new file mode 100644 index 0000000000000..9f68790611000 Binary files /dev/null and b/.lto.o/32.arm64.lto.o differ diff --git a/.lto.o/33.arm64.lto.o b/.lto.o/33.arm64.lto.o new file mode 100644 index 0000000000000..9ff3c58c55908 Binary files /dev/null and b/.lto.o/33.arm64.lto.o differ diff --git a/.lto.o/34.arm64.lto.o b/.lto.o/34.arm64.lto.o new file mode 100644 index 0000000000000..34af619ea692a Binary files /dev/null and b/.lto.o/34.arm64.lto.o differ diff --git a/.lto.o/35.arm64.lto.o b/.lto.o/35.arm64.lto.o new file mode 100644 index 0000000000000..cf0d807cf5b25 Binary files /dev/null and b/.lto.o/35.arm64.lto.o differ diff --git a/.lto.o/36.arm64.lto.o b/.lto.o/36.arm64.lto.o new file mode 100644 index 0000000000000..a70663f12d2ff Binary files /dev/null and b/.lto.o/36.arm64.lto.o differ diff --git a/.lto.o/37.arm64.lto.o b/.lto.o/37.arm64.lto.o new file mode 100644 index 0000000000000..c1198db084a2c Binary files /dev/null and b/.lto.o/37.arm64.lto.o differ diff --git a/.lto.o/38.arm64.lto.o b/.lto.o/38.arm64.lto.o new file mode 100644 index 0000000000000..84b655ff90ec3 Binary files /dev/null and b/.lto.o/38.arm64.lto.o differ diff --git a/.lto.o/39.arm64.lto.o b/.lto.o/39.arm64.lto.o new file mode 100644 index 0000000000000..aec8d07aa1b91 Binary files /dev/null and b/.lto.o/39.arm64.lto.o differ diff --git a/.lto.o/4.arm64.lto.o b/.lto.o/4.arm64.lto.o new file mode 100644 index 0000000000000..2b0475aabca3a Binary files /dev/null and b/.lto.o/4.arm64.lto.o differ diff --git a/.lto.o/40.arm64.lto.o b/.lto.o/40.arm64.lto.o new file mode 100644 index 0000000000000..57cc717929523 Binary files /dev/null and b/.lto.o/40.arm64.lto.o differ diff --git a/.lto.o/41.arm64.lto.o b/.lto.o/41.arm64.lto.o new file mode 100644 index 0000000000000..55a28ead5d1e9 Binary files /dev/null and b/.lto.o/41.arm64.lto.o differ diff --git a/.lto.o/42.arm64.lto.o b/.lto.o/42.arm64.lto.o new file mode 100644 index 0000000000000..040e1a70d68c0 Binary files /dev/null and b/.lto.o/42.arm64.lto.o differ diff --git a/.lto.o/43.arm64.lto.o b/.lto.o/43.arm64.lto.o new file mode 100644 index 0000000000000..00397a91e8733 Binary files /dev/null and b/.lto.o/43.arm64.lto.o differ diff --git a/.lto.o/44.arm64.lto.o b/.lto.o/44.arm64.lto.o new file mode 100644 index 0000000000000..a4dc30eca8175 Binary files /dev/null and b/.lto.o/44.arm64.lto.o differ diff --git a/.lto.o/45.arm64.lto.o b/.lto.o/45.arm64.lto.o new file mode 100644 index 0000000000000..8a52878a64212 Binary files /dev/null and b/.lto.o/45.arm64.lto.o differ diff --git a/.lto.o/46.arm64.lto.o b/.lto.o/46.arm64.lto.o new file mode 100644 index 0000000000000..10822586e74c8 Binary files /dev/null and b/.lto.o/46.arm64.lto.o differ diff --git a/.lto.o/47.arm64.lto.o b/.lto.o/47.arm64.lto.o new file mode 100644 index 0000000000000..6afdf35b77a9c Binary files /dev/null and b/.lto.o/47.arm64.lto.o differ diff --git a/.lto.o/48.arm64.lto.o b/.lto.o/48.arm64.lto.o new file mode 100644 index 0000000000000..8cdba3db6513b Binary files /dev/null and b/.lto.o/48.arm64.lto.o differ diff --git a/.lto.o/49.arm64.lto.o b/.lto.o/49.arm64.lto.o new file mode 100644 index 0000000000000..3bcffa72bae15 Binary files /dev/null and b/.lto.o/49.arm64.lto.o differ diff --git a/.lto.o/5.arm64.lto.o b/.lto.o/5.arm64.lto.o new file mode 100644 index 0000000000000..118975295fe19 Binary files /dev/null and b/.lto.o/5.arm64.lto.o differ diff --git a/.lto.o/50.arm64.lto.o b/.lto.o/50.arm64.lto.o new file mode 100644 index 0000000000000..bc4b19c97b7d3 Binary files /dev/null and b/.lto.o/50.arm64.lto.o differ diff --git a/.lto.o/51.arm64.lto.o b/.lto.o/51.arm64.lto.o new file mode 100644 index 0000000000000..b40b749c0db66 Binary files /dev/null and b/.lto.o/51.arm64.lto.o differ diff --git a/.lto.o/52.arm64.lto.o b/.lto.o/52.arm64.lto.o new file mode 100644 index 0000000000000..ae5c7abc5f16a Binary files /dev/null and b/.lto.o/52.arm64.lto.o differ diff --git a/.lto.o/53.arm64.lto.o b/.lto.o/53.arm64.lto.o new file mode 100644 index 0000000000000..2a37f1582a47c Binary files /dev/null and b/.lto.o/53.arm64.lto.o differ diff --git a/.lto.o/54.arm64.lto.o b/.lto.o/54.arm64.lto.o new file mode 100644 index 0000000000000..e60eb5edc517a Binary files /dev/null and b/.lto.o/54.arm64.lto.o differ diff --git a/.lto.o/55.arm64.lto.o b/.lto.o/55.arm64.lto.o new file mode 100644 index 0000000000000..7c1afd559c350 Binary files /dev/null and b/.lto.o/55.arm64.lto.o differ diff --git a/.lto.o/56.arm64.lto.o b/.lto.o/56.arm64.lto.o new file mode 100644 index 0000000000000..ef51be6832ffb Binary files /dev/null and b/.lto.o/56.arm64.lto.o differ diff --git a/.lto.o/57.arm64.lto.o b/.lto.o/57.arm64.lto.o new file mode 100644 index 0000000000000..f1446bab1e8bc Binary files /dev/null and b/.lto.o/57.arm64.lto.o differ diff --git a/.lto.o/58.arm64.lto.o b/.lto.o/58.arm64.lto.o new file mode 100644 index 0000000000000..f8d94f4e4444e Binary files /dev/null and b/.lto.o/58.arm64.lto.o differ diff --git a/.lto.o/59.arm64.lto.o b/.lto.o/59.arm64.lto.o new file mode 100644 index 0000000000000..d6199520a2878 Binary files /dev/null and b/.lto.o/59.arm64.lto.o differ diff --git a/.lto.o/6.arm64.lto.o b/.lto.o/6.arm64.lto.o new file mode 100644 index 0000000000000..2ae5d7c1d1f9c Binary files /dev/null and b/.lto.o/6.arm64.lto.o differ diff --git a/.lto.o/60.arm64.lto.o b/.lto.o/60.arm64.lto.o new file mode 100644 index 0000000000000..265d4e3c0913a Binary files /dev/null and b/.lto.o/60.arm64.lto.o differ diff --git a/.lto.o/61.arm64.lto.o b/.lto.o/61.arm64.lto.o new file mode 100644 index 0000000000000..928a21e71f61d Binary files /dev/null and b/.lto.o/61.arm64.lto.o differ diff --git a/.lto.o/62.arm64.lto.o b/.lto.o/62.arm64.lto.o new file mode 100644 index 0000000000000..a72c523083383 Binary files /dev/null and b/.lto.o/62.arm64.lto.o differ diff --git a/.lto.o/63.arm64.lto.o b/.lto.o/63.arm64.lto.o new file mode 100644 index 0000000000000..46e92e38b4cc5 Binary files /dev/null and b/.lto.o/63.arm64.lto.o differ diff --git a/.lto.o/64.arm64.lto.o b/.lto.o/64.arm64.lto.o new file mode 100644 index 0000000000000..947522a9757f9 Binary files /dev/null and b/.lto.o/64.arm64.lto.o differ diff --git a/.lto.o/65.arm64.lto.o b/.lto.o/65.arm64.lto.o new file mode 100644 index 0000000000000..0df4887afce07 Binary files /dev/null and b/.lto.o/65.arm64.lto.o differ diff --git a/.lto.o/66.arm64.lto.o b/.lto.o/66.arm64.lto.o new file mode 100644 index 0000000000000..ed459617b6cd4 Binary files /dev/null and b/.lto.o/66.arm64.lto.o differ diff --git a/.lto.o/67.arm64.lto.o b/.lto.o/67.arm64.lto.o new file mode 100644 index 0000000000000..07fac395713ae Binary files /dev/null and b/.lto.o/67.arm64.lto.o differ diff --git a/.lto.o/68.arm64.lto.o b/.lto.o/68.arm64.lto.o new file mode 100644 index 0000000000000..122a7c02efe32 Binary files /dev/null and b/.lto.o/68.arm64.lto.o differ diff --git a/.lto.o/69.arm64.lto.o b/.lto.o/69.arm64.lto.o new file mode 100644 index 0000000000000..56fe8f07412db Binary files /dev/null and b/.lto.o/69.arm64.lto.o differ diff --git a/.lto.o/7.arm64.lto.o b/.lto.o/7.arm64.lto.o new file mode 100644 index 0000000000000..5fea53faf59f5 Binary files /dev/null and b/.lto.o/7.arm64.lto.o differ diff --git a/.lto.o/70.arm64.lto.o b/.lto.o/70.arm64.lto.o new file mode 100644 index 0000000000000..e696c735fe911 Binary files /dev/null and b/.lto.o/70.arm64.lto.o differ diff --git a/.lto.o/71.arm64.lto.o b/.lto.o/71.arm64.lto.o new file mode 100644 index 0000000000000..246e9c908fb99 Binary files /dev/null and b/.lto.o/71.arm64.lto.o differ diff --git a/.lto.o/72.arm64.lto.o b/.lto.o/72.arm64.lto.o new file mode 100644 index 0000000000000..34f9728e41d9a Binary files /dev/null and b/.lto.o/72.arm64.lto.o differ diff --git a/.lto.o/73.arm64.lto.o b/.lto.o/73.arm64.lto.o new file mode 100644 index 0000000000000..f7b1a0d91c6ba Binary files /dev/null and b/.lto.o/73.arm64.lto.o differ diff --git a/.lto.o/74.arm64.lto.o b/.lto.o/74.arm64.lto.o new file mode 100644 index 0000000000000..ec6680fa593d6 Binary files /dev/null and b/.lto.o/74.arm64.lto.o differ diff --git a/.lto.o/75.arm64.lto.o b/.lto.o/75.arm64.lto.o new file mode 100644 index 0000000000000..e056d403af836 Binary files /dev/null and b/.lto.o/75.arm64.lto.o differ diff --git a/.lto.o/76.arm64.lto.o b/.lto.o/76.arm64.lto.o new file mode 100644 index 0000000000000..3d9342de6526a Binary files /dev/null and b/.lto.o/76.arm64.lto.o differ diff --git a/.lto.o/77.arm64.lto.o b/.lto.o/77.arm64.lto.o new file mode 100644 index 0000000000000..6bfe99914d04f Binary files /dev/null and b/.lto.o/77.arm64.lto.o differ diff --git a/.lto.o/78.arm64.lto.o b/.lto.o/78.arm64.lto.o new file mode 100644 index 0000000000000..99e581949fa09 Binary files /dev/null and b/.lto.o/78.arm64.lto.o differ diff --git a/.lto.o/79.arm64.lto.o b/.lto.o/79.arm64.lto.o new file mode 100644 index 0000000000000..ddca9a6fa4377 Binary files /dev/null and b/.lto.o/79.arm64.lto.o differ diff --git a/.lto.o/8.arm64.lto.o b/.lto.o/8.arm64.lto.o new file mode 100644 index 0000000000000..8fdc58b0dee92 Binary files /dev/null and b/.lto.o/8.arm64.lto.o differ diff --git a/.lto.o/80.arm64.lto.o b/.lto.o/80.arm64.lto.o new file mode 100644 index 0000000000000..5da5b05d5e205 Binary files /dev/null and b/.lto.o/80.arm64.lto.o differ diff --git a/.lto.o/81.arm64.lto.o b/.lto.o/81.arm64.lto.o new file mode 100644 index 0000000000000..2a9da9f91fe88 Binary files /dev/null and b/.lto.o/81.arm64.lto.o differ diff --git a/.lto.o/82.arm64.lto.o b/.lto.o/82.arm64.lto.o new file mode 100644 index 0000000000000..03bbf9b18c595 Binary files /dev/null and b/.lto.o/82.arm64.lto.o differ diff --git a/.lto.o/83.arm64.lto.o b/.lto.o/83.arm64.lto.o new file mode 100644 index 0000000000000..c2d72d58ad5e7 Binary files /dev/null and b/.lto.o/83.arm64.lto.o differ diff --git a/.lto.o/84.arm64.lto.o b/.lto.o/84.arm64.lto.o new file mode 100644 index 0000000000000..524816e9dae9b Binary files /dev/null and b/.lto.o/84.arm64.lto.o differ diff --git a/.lto.o/85.arm64.lto.o b/.lto.o/85.arm64.lto.o new file mode 100644 index 0000000000000..c3bc62c400d63 Binary files /dev/null and b/.lto.o/85.arm64.lto.o differ diff --git a/.lto.o/86.arm64.lto.o b/.lto.o/86.arm64.lto.o new file mode 100644 index 0000000000000..b1812171adb8e Binary files /dev/null and b/.lto.o/86.arm64.lto.o differ diff --git a/.lto.o/87.arm64.lto.o b/.lto.o/87.arm64.lto.o new file mode 100644 index 0000000000000..936f61b1b24bd Binary files /dev/null and b/.lto.o/87.arm64.lto.o differ diff --git a/.lto.o/88.arm64.lto.o b/.lto.o/88.arm64.lto.o new file mode 100644 index 0000000000000..172d4ad592779 Binary files /dev/null and b/.lto.o/88.arm64.lto.o differ diff --git a/.lto.o/89.arm64.lto.o b/.lto.o/89.arm64.lto.o new file mode 100644 index 0000000000000..80968ca5710c2 Binary files /dev/null and b/.lto.o/89.arm64.lto.o differ diff --git a/.lto.o/9.arm64.lto.o b/.lto.o/9.arm64.lto.o new file mode 100644 index 0000000000000..d27fb11e7345a Binary files /dev/null and b/.lto.o/9.arm64.lto.o differ diff --git a/.lto.o/90.arm64.lto.o b/.lto.o/90.arm64.lto.o new file mode 100644 index 0000000000000..ca7abd330bb41 Binary files /dev/null and b/.lto.o/90.arm64.lto.o differ diff --git a/.lto.o/91.arm64.lto.o b/.lto.o/91.arm64.lto.o new file mode 100644 index 0000000000000..494235ef2e32a Binary files /dev/null and b/.lto.o/91.arm64.lto.o differ diff --git a/.lto.o/92.arm64.lto.o b/.lto.o/92.arm64.lto.o new file mode 100644 index 0000000000000..072fdc306738b Binary files /dev/null and b/.lto.o/92.arm64.lto.o differ diff --git a/.lto.o/93.arm64.lto.o b/.lto.o/93.arm64.lto.o new file mode 100644 index 0000000000000..1626724f7780a Binary files /dev/null and b/.lto.o/93.arm64.lto.o differ diff --git a/.lto.o/94.arm64.lto.o b/.lto.o/94.arm64.lto.o new file mode 100644 index 0000000000000..fbcc0ee4a291a Binary files /dev/null and b/.lto.o/94.arm64.lto.o differ diff --git a/.lto.o/95.arm64.lto.o b/.lto.o/95.arm64.lto.o new file mode 100644 index 0000000000000..91cf2b9084888 Binary files /dev/null and b/.lto.o/95.arm64.lto.o differ diff --git a/.lto.o/96.arm64.lto.o b/.lto.o/96.arm64.lto.o new file mode 100644 index 0000000000000..d236eec7d2b70 Binary files /dev/null and b/.lto.o/96.arm64.lto.o differ diff --git a/.lto.o/97.arm64.lto.o b/.lto.o/97.arm64.lto.o new file mode 100644 index 0000000000000..1812d07eca638 Binary files /dev/null and b/.lto.o/97.arm64.lto.o differ diff --git a/.lto.o/98.arm64.lto.o b/.lto.o/98.arm64.lto.o new file mode 100644 index 0000000000000..027005a7de481 Binary files /dev/null and b/.lto.o/98.arm64.lto.o differ diff --git a/.lto.o/99.arm64.lto.o b/.lto.o/99.arm64.lto.o new file mode 100644 index 0000000000000..8823ff033fa4e Binary files /dev/null and b/.lto.o/99.arm64.lto.o differ diff --git a/BUILD_GUIDE.md b/BUILD_GUIDE.md new file mode 100644 index 0000000000000..b7cc23442050e --- /dev/null +++ b/BUILD_GUIDE.md @@ -0,0 +1,293 @@ +# Firefox Oasis Browser Build Guide + +This guide explains how to build the Firefox Oasis browser with the AI assistant feature enabled. + +## Prerequisites + +- macOS (tested on macOS 24.6.0) +- Node.js and npm installed +- Python 3 +- Git +- Sufficient disk space (Firefox builds require several GB) + +## Overview + +Building the Firefox Oasis browser involves two main steps: + +1. **Building the AI Assistant Bundle** - Compiles TypeScript code into a JavaScript bundle +2. **Building the Firefox Browser** - Compiles the entire browser with your customizations + +## Step 1: Build the AI Assistant Bundle + +The AI assistant is a separate TypeScript/JavaScript project that needs to be built before building the browser. + +### Navigate to the Assistant Build Directory + +```bash +cd browser/base/content/assistant/build +``` + +### Install Dependencies + +```bash +npm install +``` + +This installs the required dependencies including: +- esbuild (for bundling) +- TypeScript +- AWS SDK dependencies +- LangChain dependencies +- Supabase client + +**Important**: If you see platform-specific errors (e.g., Windows binaries on macOS), delete `node_modules` and run `npm install` again. The build system will install the correct binaries for your platform. + +### Build the Assistant Bundle + +```bash +npm run build +``` + +This runs `node esbuild.config.mjs` which: +- Compiles TypeScript files in `src/` +- Bundles all dependencies +- Outputs `assistant.bundle.js` in the parent directory (`browser/base/content/assistant/`) + +You should see output like: +``` +../assistant.bundle.js 1.9mb ⚠️ +⚡ Done in 66ms +``` + +### Troubleshooting Assistant Build + +- **Platform mismatch error**: If you get errors about wrong platform binaries, delete `node_modules` and run `npm install` again +- **Missing script error**: Make sure you're in the `build` subdirectory, not the `assistant` directory + +## Step 2: Build the Firefox Browser + +### Navigate to Firefox Root Directory + +```bash +cd /path/to/firefox-oasis +``` + +### Important: Branding Asset Fix + +Before building, ensure the branding asset file exists: + +```bash +# If it doesn't exist, copy it from another branding directory +cp browser/branding/unofficial/Assets.car browser/branding/custom/Assets.car +``` + +This file is required for the macOS build. Without it, the build will fail with: +``` +cp: /path/to/browser/branding/custom/Assets.car: No such file or directory +``` + +### Run the Build + +```bash +./mach build +``` + +**Note**: Always run `mach` commands from the Firefox root directory. Do not run them from subdirectories. + +The build process will: +- Configure the build system +- Compile C++, Rust, and JavaScript code +- Link libraries +- Package the browser + +### Build Time and Resources + +- **Time**: Expect 10-20 minutes depending on your hardware +- **CPU**: Uses parallel jobs based on available cores and memory +- **Warnings**: You may see compiler warnings (e.g., deprecated API warnings on macOS). These are typically safe to ignore. + +### Successful Build Output + +You should see: +``` +Your build was successful! +To view a profile of the build, run |mach resource-usage| +To take your build for a test drive, run: |mach run| +``` + +### Troubleshooting Browser Build + +- **Permission errors with mach**: Remove stale lock files: + ```bash + rm -f ~/.mozbuild/srcdirs/firefox-oasis-*/_virtualenvs/mach.lock + ``` +- **Missing Assets.car**: See "Branding Asset Fix" above +- **Build failures**: Check the error output. Common issues include: + - Missing dependencies + - Platform-specific build issues + - Disk space issues + +## Step 3: Access the AI Assistant + +After successfully building the browser, launch it: + +```bash +./mach run +``` + +### Opening the Assistant Sidebar + +The AI assistant is integrated as a sidebar panel. You can open it in three ways: + +#### Method 1: Toolbar Button +1. Look for the "Oasis Assistant" button in the browser toolbar +2. If not visible, right-click the toolbar → Customize Toolbar → drag the Assistant button to your toolbar +3. Click the button to toggle the sidebar + +#### Method 2: View Menu +1. Go to **View** → **Sidebar** → **Oasis Assistant** +2. The sidebar will open on the left side of the browser + +#### Method 3: Keyboard Shortcut +- If configured, use the keyboard shortcut for `viewOasisAssistantSidebar` + +### Assistant Interface + +The assistant sidebar displays: +- **Authentication section** at the top with Sign In/Sign Up buttons +- **Chat log area** in the middle +- **Input field** at the bottom with: + - Text input for questions + - Send button + - Stop button (during responses) + - Clear Context button + - Microphone button (for voice input) + +### Using the Assistant + +1. **Sign In**: Click "Sign In" and authenticate using: + - Email/password + - Google OAuth +2. **Ask Questions**: Type your question in the input field and press Enter or click Send +3. **Voice Input**: Click the microphone button to record voice input (requires authentication) +4. **Clear Context**: Click "Clear Context" to start a fresh conversation + +## Architecture Overview + +### File Structure + +``` +firefox-oasis/ +├── browser/ +│ ├── base/ +│ │ ├── content/ +│ │ │ └── assistant/ +│ │ │ ├── assistant.xhtml # Assistant UI +│ │ │ ├── assistant.bundle.js # Compiled bundle (from build step) +│ │ │ ├── assistant.ui.js # UI logic +│ │ │ ├── bootstrap.js # Button integration +│ │ │ └── build/ +│ │ │ ├── src/ # TypeScript source +│ │ │ ├── package.json +│ │ │ └── esbuild.config.mjs +│ │ └── jar.mn # Resource registration +│ └── components/ +│ └── sidebar/ +│ └── browser-sidebar.js # Sidebar registration +``` + +### Integration Points + +1. **Sidebar Registration**: `browser/components/sidebar/browser-sidebar.js` registers the assistant as a sidebar panel +2. **Preference**: `browser.sidebar.oasis_assistant.enabled` (default: `true`) in `browser/app/profile/firefox.js` +3. **Toolbar Button**: `browser/base/content/navigator-toolbox.inc.xhtml` defines the assistant button +4. **Bootstrap**: `browser/base/content/assistant/bootstrap.js` wires the button to the sidebar controller + +### Build Process Flow + +``` +1. Developer edits TypeScript in assistant/build/src/ +2. Run npm run build → compiles to assistant.bundle.js +3. Run mach build → includes bundle in browser.jar +4. Run mach run → browser loads with assistant sidebar +``` + +## Common Issues and Solutions + +### Issue: Assistant bundle not updating +**Solution**: Make sure you rebuild the bundle after code changes: +```bash +cd browser/base/content/assistant/build && npm run build +``` + +### Issue: Sidebar doesn't appear +**Solution**: +1. Check that preference is enabled: `browser.sidebar.oasis_assistant.enabled` should be `true` +2. Check browser console for errors (Cmd+Shift+J on macOS) +3. Verify the sidebar is registered in `browser-sidebar.js` + +### Issue: Assistant button doesn't work +**Solution**: +1. Check that `bootstrap.js` is loaded in `browser.xhtml` +2. Check browser console for JavaScript errors +3. Try accessing via View menu instead + +### Issue: Authentication doesn't work +**Solution**: +1. Check browser console for authentication errors +2. Verify Supabase configuration in `assistant/build/src/config/env.ts` +3. Check network connectivity to Supabase + +## Development Workflow + +For active development: + +1. **Edit Assistant Code**: + ```bash + cd browser/base/content/assistant/build + # Edit files in src/ + npm run build + ``` + +2. **Test Changes**: + ```bash + cd /path/to/firefox-oasis + ./mach run + ``` + +3. **For Browser Code Changes**: + ```bash + # After editing browser code + ./mach build + ./mach run + ``` + +## Quick Reference + +```bash +# Full build workflow +cd browser/base/content/assistant/build +npm install +npm run build +cd /path/to/firefox-oasis +./mach build +./mach run + +# Quick rebuild of assistant only +cd browser/base/content/assistant/build && npm run build + +# Quick rebuild of browser (after code changes) +cd /path/to/firefox-oasis && ./mach build +``` + +## Additional Resources + +- Firefox Build Documentation: https://firefox-source-docs.mozilla.org/setup/ +- Assistant Source Code: `browser/base/content/assistant/build/src/` +- Sidebar System: `browser/components/sidebar/browser-sidebar.js` + +--- + +**Last Updated**: Based on build process tested October 2024 +**Tested On**: macOS 24.6.0, Firefox Oasis build system + diff --git a/README_NOTARIZATION.md b/README_NOTARIZATION.md new file mode 100644 index 0000000000000..2794325081b05 --- /dev/null +++ b/README_NOTARIZATION.md @@ -0,0 +1,46 @@ +# 🍎 Oasis Browser - Release & Notarization + +## 🎯 Quick Start for Team Members + +### For Release & Notarization: +```bash +# Navigate to the notarization directory +cd notarization + +# Follow the complete guide +open docs/NOTARIZATION_SUCCESS_GUIDE.md +``` + +### Prerequisites: +1. **Apple Developer Account** with Developer ID Application certificate +2. **Certificate File** (`developer_id.p12`) - Place in `notarization/` directory +3. **App Store Connect API Key** for notarization +4. **Built Firefox Application** in `obj-*/dist/` directory + +## 📚 Complete Documentation + +### 🏆 Main Guide +- **[notarization/docs/NOTARIZATION_SUCCESS_GUIDE.md](notarization/docs/NOTARIZATION_SUCCESS_GUIDE.md)** - Complete 50+ page guide + +### 🛠️ Quick Commands +```bash +# Run notarization +cd notarization && ./scripts/resolve_symlinks_and_sign.sh + +# Test before notarization +cd notarization && ./scripts/pre_notarization_test.sh +``` + +## 🔐 Security Notes + +- **Certificate files are NOT in the repository** (security) +- **Place your `developer_id.p12` in `notarization/` directory** +- **Set permissions**: `chmod 600 notarization/developer_id.p12` + +## ✅ Success Rate: 100% + +The notarization process has been fully tested and documented with a 100% success rate. + +--- + +**For complete instructions, see**: [notarization/README.md](notarization/README.md) diff --git a/RELEASE_GUIDE.md b/RELEASE_GUIDE.md new file mode 100644 index 0000000000000..81401efdcf834 --- /dev/null +++ b/RELEASE_GUIDE.md @@ -0,0 +1,261 @@ +# Oasis Browser Release Guide + +## 🎯 Overview + +This guide documents the complete process for building, signing, and packaging the Oasis Browser for distribution. The Oasis Browser is a custom Firefox variant with enhanced branding and privacy features. + +## 📋 Prerequisites + +### System Requirements +- **macOS**: 10.15+ (Catalina or later) +- **RAM**: 8GB minimum, 16GB recommended +- **Storage**: 20GB free space minimum +- **CPU**: Multi-core processor recommended + +### Required Software +```bash +# Install Xcode Command Line Tools +xcode-select --install + +# Install Homebrew (if not already installed) +/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" + +# Install Python 3 +brew install python@3.11 + +# Install Mercurial (for source control) +brew install mercurial +``` + +### Apple Developer Account +- **Apple ID**: Required for code signing +- **Developer ID Application Certificate**: For code signing +- **App-Specific Password**: For notarization (optional) + +## 🚀 Build Process + +### 1. Repository Setup +```bash +# Clone the repository +git clone https://github.com/Kahana-LLC/firefox-oasis.git +cd firefox-oasis + +# Check current branch +git branch --show-current +# Should be on: release-v1.2.0 +``` + +### 2. Build Environment +```bash +# Bootstrap the build environment +./mach bootstrap --no-interactive + +# Verify setup +./mach doctor +# Should show: "Your system is ready to build Firefox!" +``` + +### 3. Build the Browser +```bash +# Clean any previous builds (optional) +./mach clobber + +# Configure for development +./mach configure + +# Build Oasis Browser +./mach build +# This will take 30-60 minutes depending on your system +``` + +### 4. Test the Build +```bash +# Run the browser to test +./mach run + +# Or run directly +open obj-aarch64-apple-darwin24.6.0/dist/Oasis.app +``` + +## 📦 Packaging Process + +### 1. Create Unsigned DMG +```bash +# Make the script executable +chmod +x create_simple_dmg.sh + +# Create unsigned DMG +./create_simple_dmg.sh +``` + +**Output**: `Oasis-Browser-1.2.0-YYYYMMDD.dmg` + +### 2. Create Code-Signed DMG (Recommended) +```bash +# Make the script executable +chmod +x create_signed_dmg_only.sh + +# Create code-signed DMG +./create_signed_dmg_only.sh +``` + +**Output**: `Oasis-Browser-1.2.0-Signed-YYYYMMDD.dmg` + +## 🔐 Code Signing Setup + +### 1. Verify Developer Certificate +```bash +# Check available certificates +security find-identity -v -p codesigning + +# Should show: "Developer ID Application: Adam Richard Kershner (NV6BDYHYA5)" +``` + +### 2. Update Signing Configuration +Edit `create_signed_dmg_only.sh` and update: +- `DEVELOPER_ID`: Your Developer ID certificate name +- `APPLE_ID`: Your Apple ID email +- `TEAM_ID`: Your Apple Developer Team ID + +### 3. Signing Process +The signing script will: +1. Create a copy of the app for signing +2. Remove problematic files that can't be signed +3. Sign all dylibs, executables, and app bundles +4. Sign the main app bundle +5. Create a DMG with the signed app + +## 📁 File Structure + +### Key Files Created +``` +firefox-oasis/ +├── create_simple_dmg.sh # Creates unsigned DMG +├── create_signed_dmg_only.sh # Creates code-signed DMG +├── entitlements.plist # Code signing entitlements +├── RELEASE_GUIDE.md # This guide +└── obj-aarch64-apple-darwin24.6.0/ + └── dist/ + ├── Oasis.app # Built application + └── Oasis-Signed.app # Code-signed application +``` + +### DMG Contents +- **Oasis Browser.app**: The main application +- **Applications**: Symbolic link to Applications folder +- **README.txt**: Installation instructions + +## 🎨 Branding Features + +The Oasis Browser includes the following custom branding: +- **App Name**: "Oasis Browser" instead of Firefox +- **Custom Icons**: Oasis-specific app icons +- **Enhanced Privacy**: Privacy-focused features +- **Custom Branding**: Throughout the user interface + +## 📋 Release Checklist + +### Before Building +- [ ] Verify you're on the correct branch (`release-v1.2.0`) +- [ ] Ensure all branding changes are committed +- [ ] Clean any previous builds if needed + +### Build Process +- [ ] Run `./mach bootstrap --no-interactive` +- [ ] Run `./mach configure` +- [ ] Run `./mach build` +- [ ] Test the build with `./mach run` + +### Packaging +- [ ] Create unsigned DMG with `./create_simple_dmg.sh` +- [ ] Create signed DMG with `./create_signed_dmg_only.sh` +- [ ] Test both DMGs on a clean macOS system + +### Distribution +- [ ] Verify DMG opens correctly +- [ ] Test installation process +- [ ] Verify app launches without errors +- [ ] Share DMG with team members + +## 🔧 Troubleshooting + +### Build Issues +```bash +# Clean and rebuild +./mach clobber +./mach configure +./mach build +``` + +### Signing Issues +```bash +# Check certificate +security find-identity -v -p codesigning + +# Verify app structure +codesign --verify --verbose obj-aarch64-apple-darwin24.6.0/dist/Oasis-Signed.app +``` + +### DMG Issues +```bash +# Check DMG integrity +hdiutil verify Oasis-Browser-*.dmg + +# Mount and test +hdiutil attach Oasis-Browser-*.dmg +``` + +## 📊 Release Information + +### Current Release +- **Version**: 1.2.0 +- **Build Date**: September 12, 2024 +- **Branch**: release-v1.2.0 +- **Status**: Code Signed ✅ + +### File Sizes +- **Unsigned DMG**: ~211MB +- **Signed DMG**: ~212MB +- **App Bundle**: ~200MB + +## 🚀 Future Releases + +### Version Updates +1. Update version numbers in scripts +2. Update branch name if needed +3. Follow the same build process +4. Test thoroughly before distribution + +### Script Maintenance +- Update `DEVELOPER_ID` if certificate changes +- Update `APPLE_ID` if Apple ID changes +- Update `TEAM_ID` if team changes +- Test scripts on clean macOS system + +## 📞 Support + +### Getting Help +- **Documentation**: Check this guide first +- **Issues**: File bugs on GitHub Issues +- **Community**: Contact the development team + +### Common Questions + +**Q: Why is the app not notarized?** +A: The current build is code-signed but not notarized. This provides good security while avoiding the complexity of notarization. Users may see a one-time security warning. + +**Q: Can I notarize the app?** +A: Yes, but it requires additional setup and may have issues with the complex Firefox build structure. The current code-signed version works well for most use cases. + +**Q: How do I update the branding?** +A: Modify the branding files in the `browser/branding/` directory and rebuild. + +## 🎉 Success! + +You now have a complete, working Oasis Browser that can be distributed to team members. The code-signed DMG provides a professional installation experience with minimal security warnings. + +--- + +**Last Updated**: September 12, 2024 +**Version**: 1.2.0 +**Status**: Production Ready ✅ diff --git a/SUPABASE_AUTH_IMPLEMENTATION_GUIDE.md b/SUPABASE_AUTH_IMPLEMENTATION_GUIDE.md new file mode 100644 index 0000000000000..f40bbb548513d --- /dev/null +++ b/SUPABASE_AUTH_IMPLEMENTATION_GUIDE.md @@ -0,0 +1,1051 @@ +# Supabase Authentication Implementation Guide + +## Overview + +This guide provides complete information for re-implementing the Supabase authentication system from the Oasis Electron browser in any other project. It includes all necessary configuration, database schema, authentication methods, and implementation details. + +## Table of Contents + +1. [Environment Configuration](#environment-configuration) +2. [Database Schema](#database-schema) +3. [Supabase Project Setup](#supabase-project-setup) +4. [Authentication Service Implementation](#authentication-service-implementation) +5. [OAuth Flow Implementation](#oauth-flow-implementation) +6. [Session Management](#session-management) +7. [Error Handling](#error-handling) +8. [Usage Examples](#usage-examples) +9. [Security Considerations](#security-considerations) + +## Environment Configuration + +### Required Environment Variables + +Create a `.env` file with the following variables: + +```env +# Supabase Configuration +SUPABASE_URL=https://wvclepquxxczgrukfqyr.supabase.co +SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Ind2Y2xlcHF1eHhjemdydWtmcXlyIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTUwODU5OTksImV4cCI6MjA3MDY2MTk5OX0.T-hZ_8QxtVnOt0mtCY_Zch87SYEcsyQZwnvvFAtZiNY + +# Google OAuth Configuration (Optional - for OAuth flow) +GOOGLE_CLIENT_ID=your_google_client_id +GOOGLE_CLIENT_SECRET=your_google_client_secret + +# Application Configuration +APP_VERSION=1.0.0 +LOG_LEVEL=info +``` + +**ℹ️ Note about Supabase Anon Key:** +- The anon key is designed to be public and safe to include in client-side code +- Data access is controlled by Row Level Security (RLS) policies +- Supabase has built-in rate limiting to prevent abuse +- This key can be safely committed to version control + +### Environment Configuration Class + +```typescript +// config/env.ts +import * as dotenv from 'dotenv'; + +// Load environment variables +dotenv.config(); + +export const ENV = { + // Supabase configuration + SUPABASE_URL: process.env.SUPABASE_URL || '', + SUPABASE_ANON_KEY: process.env.SUPABASE_ANON_KEY || '', + + // Google OAuth configuration + GOOGLE_CLIENT_ID: process.env.GOOGLE_CLIENT_ID || '', + GOOGLE_CLIENT_SECRET: process.env.GOOGLE_CLIENT_SECRET || '', + + // Application configuration + APP_VERSION: process.env.APP_VERSION || '1.0.0', + LOG_LEVEL: process.env.LOG_LEVEL || 'info', + + // Validate environment variables + validate(): void { + if (!this.SUPABASE_URL) { + throw new Error('SUPABASE_URL is required'); + } + if (!this.SUPABASE_ANON_KEY) { + throw new Error('SUPABASE_ANON_KEY is required'); + } + } +}; +``` + +## Database Schema + +### Required Supabase Tables + +#### 1. Users Table + +```sql +-- Create users table +CREATE TABLE users ( + user_id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + name TEXT, + email TEXT UNIQUE NOT NULL, + password_hash TEXT, -- Handled by Supabase Auth + created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + last_login TIMESTAMP WITH TIME ZONE, + status TEXT DEFAULT 'active' CHECK (status IN ('active', 'suspended')) +); + +-- Create index for email lookups +CREATE INDEX idx_users_email ON users(email); + +-- Enable Row Level Security +ALTER TABLE users ENABLE ROW LEVEL SECURITY; + +-- Create policy for users to access their own data +CREATE POLICY "Users can view own profile" ON users + FOR SELECT USING (auth.uid() = user_id); + +CREATE POLICY "Users can update own profile" ON users + FOR UPDATE USING (auth.uid() = user_id); +``` + +#### 2. Sessions Table + +```sql +-- Create sessions table +CREATE TABLE sessions ( + session_id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + user_id UUID REFERENCES users(user_id) ON DELETE CASCADE, + started_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + ended_at TIMESTAMP WITH TIME ZONE, + device_info JSONB +); + +-- Create index for user sessions +CREATE INDEX idx_sessions_user_id ON sessions(user_id); + +-- Enable Row Level Security +ALTER TABLE sessions ENABLE ROW LEVEL SECURITY; + +-- Create policy for users to access their own sessions +CREATE POLICY "Users can view own sessions" ON sessions + FOR SELECT USING (auth.uid() = user_id); + +CREATE POLICY "Users can insert own sessions" ON sessions + FOR INSERT WITH CHECK (auth.uid() = user_id); +``` + +#### 3. LLM Usage Table (Optional - for AI features) + +```sql +-- Create llm_usage table for tracking AI assistant usage +CREATE TABLE llm_usage ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + user_id UUID REFERENCES users(user_id) ON DELETE CASCADE, + tokens_used INTEGER NOT NULL, + usage_count INTEGER DEFAULT 1, + prompt_summary TEXT, + model_used TEXT, + success BOOLEAN DEFAULT true, + latency_ms INTEGER, + created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() +); + +-- Create index for user usage tracking +CREATE INDEX idx_llm_usage_user_id ON llm_usage(user_id); + +-- Enable Row Level Security +ALTER TABLE llm_usage ENABLE ROW LEVEL SECURITY; + +-- Create policy for users to access their own usage data +CREATE POLICY "Users can view own usage" ON llm_usage + FOR SELECT USING (auth.uid() = user_id); + +CREATE POLICY "Users can insert own usage" ON llm_usage + FOR INSERT WITH CHECK (auth.uid() = user_id); +``` + +#### 4. Bookmarks History Table (Optional - for browser features) + +```sql +-- Create bookmarks_history table +CREATE TABLE bookmarks_history ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + user_id UUID REFERENCES users(user_id) ON DELETE CASCADE, + url TEXT NOT NULL, + title TEXT, + is_bookmarked BOOLEAN DEFAULT false, + created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() +); + +-- Create index for user bookmarks +CREATE INDEX idx_bookmarks_user_id ON bookmarks_history(user_id); + +-- Enable Row Level Security +ALTER TABLE bookmarks_history ENABLE ROW LEVEL SECURITY; + +-- Create policy for users to access their own bookmarks +CREATE POLICY "Users can view own bookmarks" ON bookmarks_history + FOR SELECT USING (auth.uid() = user_id); + +CREATE POLICY "Users can insert own bookmarks" ON bookmarks_history + FOR INSERT WITH CHECK (auth.uid() = user_id); +``` + +## Supabase Project Setup + +### 1. Supabase Project Configuration + +- **Project URL**: `https://wvclepquxxczgrukfqyr.supabase.co` +- **Anon Key**: `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Ind2Y2xlcHF1eHhjemdydWtmcXlyIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTUwODU5OTksImV4cCI6MjA3MDY2MTk5OX0.T-hZ_8QxtVnOt0mtCY_Zch87SYEcsyQZwnvvFAtZiNY` + +### 2. Authentication Providers Setup + +In your Supabase dashboard: + +1. Go to Authentication > Providers +2. Enable Email provider +3. Enable Google OAuth provider +4. Configure Google OAuth with your client credentials +5. Set redirect URLs for your application + +### 3. Custom Protocol Setup (for OAuth) + +For the OAuth flow, configure a custom protocol handler: +- **Protocol**: `kahana://auth-callback` +- **Redirect URL**: `kahana://auth-callback` + +## Authentication Service Implementation + +### TypeScript Interfaces + +```typescript +// types/auth.ts +import { User, Session, AuthError } from '@supabase/supabase-js'; + +export interface UserProfile { + user_id: string; + name?: string; + email: string; + created_at: string; + last_login?: string; + status: 'active' | 'suspended'; +} + +export interface UserSession { + session_id: string; + user_id: string; + started_at: string; + ended_at?: string; + device_info?: { + platform: string; + version: string; + userAgent?: string; + }; +} + +export interface AuthState { + user: User | null; + session: Session | null; + isAuthenticated: boolean; +} +``` + +### Main Authentication Service + +```typescript +// services/SupabaseAuth.ts +import { createClient, SupabaseClient, User, Session, AuthError } from '@supabase/supabase-js'; +import { ENV } from '../config/env'; +import { UserProfile, UserSession, AuthState } from '../types/auth'; + +export class SupabaseAuth { + private static instance: SupabaseAuth; + private supabase: SupabaseClient; + private currentSession: UserSession | null = null; + private authStateCallbacks: Array<(state: AuthState) => void> = []; + + private constructor() { + // Initialize Supabase client + this.supabase = createClient(ENV.SUPABASE_URL, ENV.SUPABASE_ANON_KEY); + + // Set up auth state change listener + this.supabase.auth.onAuthStateChange((event, session) => { + console.log('Auth state changed:', event); + this.handleAuthStateChange(event, session); + }); + } + + public static getInstance(): SupabaseAuth { + if (!SupabaseAuth.instance) { + SupabaseAuth.instance = new SupabaseAuth(); + } + return SupabaseAuth.instance; + } + + // Email/Password Authentication + public async signInWithEmail(email: string, password: string): Promise<{ user: User | null; error: AuthError | null }> { + try { + console.log('Attempting email sign in for:', email); + + const { data, error } = await this.supabase.auth.signInWithPassword({ + email, + password + }); + + if (error) { + console.error('Email sign in error:', error.message); + return { user: null, error }; + } + + if (data.user) { + await this.updateLastLogin(data.user.id); + await this.createSession(data.user.id); + console.log('Email sign in successful for user:', data.user.id); + } + + return { user: data.user, error: null }; + } catch (error) { + console.error('Sign in error:', error); + return { user: null, error: error as AuthError }; + } + } + + public async signUp(email: string, password: string, name?: string): Promise<{ user: User | null; error: AuthError | null }> { + try { + console.log('Attempting sign up for:', email); + + const { data, error } = await this.supabase.auth.signUp({ + email, + password, + options: { + data: { + name: name || email.split('@')[0] + } + } + }); + + if (error) { + console.error('Sign up error:', error.message); + return { user: null, error }; + } + + if (data.user) { + // Create user profile in our custom users table + await this.createUserProfile(data.user, name); + console.log('Sign up successful for user:', data.user.id); + } + + return { user: data.user, error: null }; + } catch (error) { + console.error('Sign up error:', error); + return { user: null, error: error as AuthError }; + } + } + + public async signOut(): Promise<{ error: AuthError | null }> { + try { + console.log('Attempting sign out'); + + // End current session if exists + if (this.currentSession) { + await this.endSession(this.currentSession.session_id); + } + + const { error } = await this.supabase.auth.signOut(); + + if (error) { + console.error('Sign out error:', error.message); + return { error }; + } + + this.currentSession = null; + console.log('Sign out successful'); + return { error: null }; + } catch (error) { + console.error('Sign out error:', error); + return { error: error as AuthError }; + } + } + + // Session Management + public async getCurrentUser(): Promise { + const { data: { user } } = await this.supabase.auth.getUser(); + return user; + } + + public async getSession(): Promise { + const { data: { session } } = await this.supabase.auth.getSession(); + return session; + } + + public async isAuthenticated(): Promise { + const user = await this.getCurrentUser(); + return user !== null; + } + + // User Profile Management + public async getUserProfile(): Promise { + try { + const user = await this.getCurrentUser(); + if (!user) return null; + + const { data, error } = await this.supabase + .from('users') + .select('*') + .eq('user_id', user.id) + .single(); + + if (error) { + console.error('Error fetching user profile:', error.message); + return null; + } + + return data as UserProfile; + } catch (error) { + console.error('Error fetching user profile:', error); + return null; + } + } + + public async updateUserProfile(updates: Partial): Promise<{ error: string | null }> { + try { + const user = await this.getCurrentUser(); + if (!user) { + return { error: 'No authenticated user' }; + } + + const { error } = await this.supabase + .from('users') + .update(updates) + .eq('user_id', user.id); + + if (error) { + console.error('Error updating user profile:', error.message); + return { error: error.message }; + } + + return { error: null }; + } catch (error) { + console.error('Error updating user profile:', error); + return { error: error instanceof Error ? error.message : 'Unknown error' }; + } + } + + // Password Management + public async updatePassword(newPassword: string): Promise<{ error: AuthError | null }> { + try { + const { error } = await this.supabase.auth.updateUser({ + password: newPassword + }); + + if (error) { + console.error('Error updating password:', error.message); + return { error }; + } + + return { error: null }; + } catch (error) { + console.error('Error updating password:', error); + return { error: error as AuthError }; + } + } + + public async resetPassword(email: string): Promise<{ error: AuthError | null }> { + try { + const { error } = await this.supabase.auth.resetPasswordForEmail(email); + + if (error) { + console.error('Error sending password reset:', error.message); + return { error }; + } + + return { error: null }; + } catch (error) { + console.error('Error sending password reset:', error); + return { error: error as AuthError }; + } + } + + // Auth State Management + public onAuthStateChange(callback: (state: AuthState) => void): void { + this.authStateCallbacks.push(callback); + } + + private async handleAuthStateChange(event: string, session: Session | null): Promise { + const user = session?.user || null; + const authState: AuthState = { + user, + session, + isAuthenticated: user !== null + }; + + // Notify all callbacks + this.authStateCallbacks.forEach(callback => { + try { + callback(authState); + } catch (error) { + console.error('Error in auth state callback:', error); + } + }); + + // Handle session creation/destruction + if (event === 'SIGNED_IN' && user) { + await this.createSession(user.id); + } else if (event === 'SIGNED_OUT' && this.currentSession) { + await this.endSession(this.currentSession.session_id); + this.currentSession = null; + } + } + + // Database Operations + private async createUserProfile(user: User, name?: string): Promise { + try { + const { error } = await this.supabase + .from('users') + .insert({ + user_id: user.id, + email: user.email!, + name: name || user.user_metadata?.name || user.email!.split('@')[0], + password_hash: '', // Supabase handles this + status: 'active' + }); + + if (error) { + console.error('Error creating user profile:', error.message); + } else { + console.log('User profile created successfully'); + } + } catch (error) { + console.error('Error creating user profile:', error); + } + } + + private async updateLastLogin(userId: string): Promise { + try { + const { error } = await this.supabase + .from('users') + .update({ last_login: new Date().toISOString() }) + .eq('user_id', userId); + + if (error) { + console.error('Error updating last login:', error.message); + } + } catch (error) { + console.error('Error updating last login:', error); + } + } + + private async createSession(userId: string): Promise { + try { + const deviceInfo = { + platform: typeof window !== 'undefined' ? 'browser' : 'server', + version: ENV.APP_VERSION, + userAgent: typeof window !== 'undefined' ? window.navigator.userAgent : 'Server' + }; + + const { data, error } = await this.supabase + .from('sessions') + .insert({ + user_id: userId, + device_info: deviceInfo + }) + .select() + .single(); + + if (error) { + console.error('Error creating session:', error.message); + } else if (data) { + this.currentSession = data as UserSession; + console.log('Session created:', data.session_id); + } + } catch (error) { + console.error('Error creating session:', error); + } + } + + private async endSession(sessionId: string): Promise { + try { + const { error } = await this.supabase + .from('sessions') + .update({ ended_at: new Date().toISOString() }) + .eq('session_id', sessionId); + + if (error) { + console.error('Error ending session:', error.message); + } else { + console.log('Session ended:', sessionId); + } + } catch (error) { + console.error('Error ending session:', error); + } + } + + // Utility Methods + public handleAuthError(error: AuthError): string { + switch (error.message) { + case 'Invalid login credentials': + return 'Invalid email or password. Please try again.'; + case 'Email not confirmed': + return 'Please check your email and click the confirmation link.'; + case 'User already registered': + return 'An account with this email already exists.'; + case 'Password should be at least 6 characters': + return 'Password must be at least 6 characters long.'; + case 'Unable to validate email address: invalid format': + return 'Please enter a valid email address.'; + default: + return error.message || 'An unexpected error occurred. Please try again.'; + } + } + + // Check if email exists in database + public async checkEmailExists(email: string): Promise<{ exists: boolean; user?: UserProfile; error?: string }> { + try { + const { data, error } = await this.supabase + .from('users') + .select('user_id, name, email, created_at, status') + .eq('email', email.toLowerCase().trim()) + .single(); + + if (error) { + // PGRST116 means no rows found, which is expected for new users + if (error.code === 'PGRST116') { + return { exists: false }; + } + console.error('Email check error:', error.message); + return { exists: false, error: 'Database error' }; + } + + return { exists: true, user: data as UserProfile }; + } catch (error) { + console.error('Email verification error:', error); + return { exists: false, error: 'Verification failed' }; + } + } +} + +// Export singleton instance +export const supabaseAuth = SupabaseAuth.getInstance(); +``` + +## OAuth Flow Implementation + +### Google OAuth with Custom Protocol + +```typescript +// Add to SupabaseAuth class +public async signInWithGoogle(): Promise<{ user: User | null; error: AuthError | null }> { + try { + console.log('Attempting Google sign in with OAuth flow'); + + // Check if user is already authenticated + const currentUser = await this.getCurrentUser(); + if (currentUser) { + console.log('User already authenticated:', currentUser.id); + return { user: currentUser, error: null }; + } + + // Generate OAuth URL with Supabase + const { data, error } = await this.supabase.auth.signInWithOAuth({ + provider: 'google', + options: { + skipBrowserRedirect: true, + // Use a custom protocol the app can handle + redirectTo: 'kahana://auth-callback', + // Request consent prompt and offline access for refresh token + queryParams: { + prompt: 'select_account', + access_type: 'offline', + include_granted_scopes: 'true', + response_type: 'code' + } + } + }); + + if (error || !data.url) { + console.error('Failed to generate OAuth URL:', error); + return { user: null, error: error || { message: 'Failed to generate OAuth URL', status: 500 } as AuthError }; + } + + console.log('Generated OAuth URL, opening in browser...'); + + // Open the OAuth URL in browser + if (typeof window !== 'undefined') { + window.open(data.url, '_blank'); + } + + // Return a success message indicating OAuth was initiated + return { user: null, error: null }; + + } catch (error) { + console.error('Google sign in error:', error); + return { user: null, error: error as AuthError }; + } +} + +/** + * Handle OAuth redirect deep link (e.g., kahana://auth-callback?code=...) + * Exchanges the code for a session or sets the session from hash tokens. + */ +public async handleOAuthRedirectCallback(callbackUrl: string): Promise<{ success: boolean; error?: string }> { + try { + console.log('Handling OAuth redirect callback:', callbackUrl); + const urlObj = new URL(callbackUrl); + if (urlObj.protocol !== 'kahana:') { + console.warn('Invalid protocol in callback URL:', urlObj.protocol); + return { success: false, error: 'Invalid protocol' }; + } + + // Prefer PKCE code exchange + const authCode = urlObj.searchParams.get('code'); + const errorParam = urlObj.searchParams.get('error'); + const errorDescription = urlObj.searchParams.get('error_description'); + + if (errorParam) { + console.error('OAuth redirect contained error:', errorParam, errorDescription); + return { success: false, error: errorDescription || errorParam }; + } + + if (authCode) { + console.log('Exchanging auth code for session...'); + const { data, error } = await this.supabase.auth.exchangeCodeForSession(authCode); + if (error) { + console.error('Failed to exchange code for session:', error.message); + return { success: false, error: error.message }; + } else { + console.log('Exchanged code for session for user:', data.user?.id); + + // Ensure user profile exists + if (data.user) { + const existingProfile = await this.getUserProfile(); + if (!existingProfile) { + await this.createUserProfile(data.user, data.user.user_metadata?.name); + console.log('Created user profile from OAuth callback'); + } + + // Update last login and create session + await this.updateLastLogin(data.user.id); + await this.createSession(data.user.id); + } + + return { success: true }; + } + } + + // Fallback: handle implicit flow fragments (access_token in hash) + if (urlObj.hash && urlObj.hash.startsWith('#')) { + console.log('Handling implicit flow with hash tokens...'); + const hashParams = new URLSearchParams(urlObj.hash.substring(1)); + const accessToken = hashParams.get('access_token'); + const refreshToken = hashParams.get('refresh_token'); + if (accessToken && refreshToken) { + const { data, error } = await this.supabase.auth.setSession({ + access_token: accessToken, + refresh_token: refreshToken + }); + if (error) { + console.error('Failed to set session from hash tokens:', error.message); + return { success: false, error: error.message }; + } else { + console.log('Set session from hash tokens for user:', data.user?.id); + + // Ensure user profile exists + if (data.user) { + const existingProfile = await this.getUserProfile(); + if (!existingProfile) { + await this.createUserProfile(data.user, data.user.user_metadata?.name); + console.log('Created user profile from hash tokens'); + } + + // Update last login and create session + await this.updateLastLogin(data.user.id); + await this.createSession(data.user.id); + } + + return { success: true }; + } + } else { + console.warn('OAuth redirect missing tokens in hash'); + return { success: false, error: 'Missing tokens in hash' }; + } + } + + console.warn('No valid OAuth response found in callback'); + return { success: false, error: 'No valid OAuth response' }; + + } catch (error) { + console.error('Error handling OAuth redirect callback:', error); + return { success: false, error: error instanceof Error ? error.message : 'Unknown error' }; + } +} +``` + +### Custom Protocol Handler (Electron) + +For Electron applications, register the custom protocol: + +```typescript +// main.ts (Electron main process) +import { app, protocol } from 'electron'; +import { supabaseAuth } from './services/SupabaseAuth'; + +// Register custom protocol +app.setAsDefaultProtocolClient('kahana'); + +// Handle protocol URLs +app.on('open-url', async (event, url) => { + event.preventDefault(); + console.log('Received protocol URL:', url); + + if (url.startsWith('kahana://auth-callback')) { + const result = await supabaseAuth.handleOAuthRedirectCallback(url); + if (result.success) { + console.log('OAuth authentication successful'); + } else { + console.error('OAuth authentication failed:', result.error); + } + } +}); + +// Handle protocol URLs on Windows +app.on('second-instance', async (event, commandLine, workingDirectory) => { + const url = commandLine.find(arg => arg.startsWith('kahana://')); + if (url) { + console.log('Received protocol URL from second instance:', url); + + if (url.startsWith('kahana://auth-callback')) { + const result = await supabaseAuth.handleOAuthRedirectCallback(url); + if (result.success) { + console.log('OAuth authentication successful'); + } else { + console.error('OAuth authentication failed:', result.error); + } + } + } +}); +``` + +## Session Management + +### Session Tracking + +The authentication service automatically tracks user sessions in the database. Each session includes: + +- **Session ID**: Unique identifier +- **User ID**: Reference to the user +- **Start Time**: When the session began +- **End Time**: When the session ended (null for active sessions) +- **Device Info**: Platform, version, and user agent information + +### Session Lifecycle + +1. **Session Creation**: Automatically created when user signs in +2. **Session Updates**: Last login time updated on each authentication +3. **Session Termination**: Automatically ended when user signs out + +## Error Handling + +### Common Authentication Errors + +```typescript +// Error handling utility +export const handleAuthError = (error: AuthError): string => { + switch (error.message) { + case 'Invalid login credentials': + return 'Invalid email or password. Please try again.'; + case 'Email not confirmed': + return 'Please check your email and click the confirmation link.'; + case 'User already registered': + return 'An account with this email already exists.'; + case 'Password should be at least 6 characters': + return 'Password must be at least 6 characters long.'; + case 'Unable to validate email address: invalid format': + return 'Please enter a valid email address.'; + case 'Too many requests': + return 'Too many attempts. Please try again later.'; + default: + return error.message || 'An unexpected error occurred. Please try again.'; + } +}; +``` + +## Usage Examples + +### Basic Authentication Flow + +```typescript +import { supabaseAuth } from './services/SupabaseAuth'; + +// Sign up a new user +const signUpUser = async (email: string, password: string, name: string) => { + const { user, error } = await supabaseAuth.signUp(email, password, name); + + if (error) { + console.error('Sign up failed:', supabaseAuth.handleAuthError(error)); + return false; + } + + console.log('User signed up successfully:', user?.id); + return true; +}; + +// Sign in existing user +const signInUser = async (email: string, password: string) => { + const { user, error } = await supabaseAuth.signInWithEmail(email, password); + + if (error) { + console.error('Sign in failed:', supabaseAuth.handleAuthError(error)); + return false; + } + + console.log('User signed in successfully:', user?.id); + return true; +}; + +// Sign in with Google OAuth +const signInWithGoogle = async () => { + const { user, error } = await supabaseAuth.signInWithGoogle(); + + if (error) { + console.error('Google sign in failed:', supabaseAuth.handleAuthError(error)); + return false; + } + + console.log('Google sign in initiated'); + return true; +}; + +// Check authentication status +const checkAuthStatus = async () => { + const isAuthenticated = await supabaseAuth.isAuthenticated(); + const user = await supabaseAuth.getCurrentUser(); + const profile = await supabaseAuth.getUserProfile(); + + console.log('Auth status:', { isAuthenticated, user: user?.id, profile }); + return { isAuthenticated, user, profile }; +}; + +// Sign out +const signOutUser = async () => { + const { error } = await supabaseAuth.signOut(); + + if (error) { + console.error('Sign out failed:', supabaseAuth.handleAuthError(error)); + return false; + } + + console.log('User signed out successfully'); + return true; +}; +``` + +### Auth State Monitoring + +```typescript +// Listen for authentication state changes +supabaseAuth.onAuthStateChange((authState) => { + console.log('Auth state changed:', authState); + + if (authState.isAuthenticated) { + console.log('User is authenticated:', authState.user?.email); + // Update UI to show authenticated state + } else { + console.log('User is not authenticated'); + // Update UI to show unauthenticated state + } +}); +``` + +### User Profile Management + +```typescript +// Get user profile +const getUserProfile = async () => { + const profile = await supabaseAuth.getUserProfile(); + + if (profile) { + console.log('User profile:', profile); + return profile; + } else { + console.log('No user profile found'); + return null; + } +}; + +// Update user profile +const updateProfile = async (updates: Partial) => { + const { error } = await supabaseAuth.updateUserProfile(updates); + + if (error) { + console.error('Profile update failed:', error); + return false; + } + + console.log('Profile updated successfully'); + return true; +}; +``` + +## Security Considerations + +### 1. Environment Variables +- Never commit `.env` files to version control +- Use different credentials for development and production +- Rotate API keys regularly + +### 2. Row Level Security (RLS) +- All database tables have RLS enabled +- Users can only access their own data +- Policies are enforced at the database level + +### 3. Session Management +- Sessions are tracked in the database +- Automatic session cleanup on sign out +- Device information is logged for security + +### 4. OAuth Security +- Use PKCE flow for OAuth +- Validate redirect URLs +- Handle OAuth errors gracefully + +### 5. Password Security +- Passwords are handled by Supabase Auth +- Minimum 6 character requirement +- Password reset functionality included + +## Dependencies + +### Required NPM Packages + +```json +{ + "dependencies": { + "@supabase/supabase-js": "^2.38.0", + "dotenv": "^16.3.1" + }, + "devDependencies": { + "@types/node": "^20.0.0", + "typescript": "^5.0.0" + } +} +``` + +### Installation + +```bash +npm install @supabase/supabase-js dotenv +npm install -D @types/node typescript +``` + +## Conclusion + +This guide provides everything needed to re-implement the Supabase authentication system in any project. The implementation includes: + +- Complete database schema with RLS policies +- Full authentication service with all methods +- OAuth flow with custom protocol handling +- Session management and tracking +- Error handling and user feedback +- Security best practices + +The authentication system is production-ready and includes all the features from the original Oasis browser implementation. diff --git a/browser/app/profile/firefox.js b/browser/app/profile/firefox.js index 21e20e7a583d0..398dc5ebbcae8 100644 --- a/browser/app/profile/firefox.js +++ b/browser/app/profile/firefox.js @@ -1546,10 +1546,10 @@ pref("toolkit.datacollection.infoURL", "https://www.mozilla.org/legal/privacy/firefox.html"); // base URL for web-based support pages -pref("app.support.baseURL", "https://support.mozilla.org/1/firefox/%VERSION%/%OS%/%LOCALE%/"); +pref("app.support.baseURL", "https://kahana.co/docs"); // base url for web-based feedback pages -pref("app.feedback.baseURL", "https://ideas.mozilla.org/"); +pref("app.feedback.baseURL", "https://kahana.co/oasis-feedback-survey"); pref("security.certerrors.permanentOverride", true); pref("security.certerrors.mitm.priming.enabled", true); @@ -2195,6 +2195,7 @@ pref("sidebar.animation.expand-on-hover.delay-duration-ms", 200); pref("sidebar.main.tools", ""); pref("sidebar.installed.extensions", ""); pref("sidebar.verticalTabs", false); +pref("browser.sidebar.oasis_assistant.enabled", true); pref("sidebar.verticalTabs.dragToPinPromo.dismissed", false); pref("sidebar.visibility", "always-show"); // Sidebar UI state is stored per-window via session restore. Use this pref @@ -3549,7 +3550,12 @@ pref("browser.ipProtection.log", false); pref("browser.ipProtection.guardian.endpoint", "https://vpn.mozilla.org/"); pref("browser.ipProtection.added", false); -// Pref to enable aboug:glean redesign. + +// Oasis Assistant defaults +pref("oasis.assistant.anthropic_api_key", "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"); +pref("oasis.assistant.model", "claude-3-5-sonnet-20240620"); +pref("oasis.assistant.temperature", "0.3"); +pref("oasis.assistant.maxTokens", "200"); pref("about.glean.redesign.enabled", false); // Forward Rust component logs to the JS console (comma separate list of crate names) diff --git a/browser/base/content/appmenu-viewcache.inc.xhtml b/browser/base/content/appmenu-viewcache.inc.xhtml index 09b491b2a3bb7..35bbb3d920f69 100644 --- a/browser/base/content/appmenu-viewcache.inc.xhtml +++ b/browser/base/content/appmenu-viewcache.inc.xhtml @@ -686,7 +686,7 @@ diff --git a/browser/base/content/assistant/VOICE_INPUT_SETUP.md b/browser/base/content/assistant/VOICE_INPUT_SETUP.md new file mode 100644 index 0000000000000..3af4789eaa357 --- /dev/null +++ b/browser/base/content/assistant/VOICE_INPUT_SETUP.md @@ -0,0 +1,145 @@ +# Voice Input Setup Guide + +## Overview +The voice input feature uses a microphone button in the assistant UI to record audio, send it to your AWS Lambda function for transcription via Deepgram (with Gemini fallback), and populate the input field with the transcribed text. + +## Architecture + +``` +User clicks mic → Records audio → Sends to Lambda → Deepgram/Gemini → Returns transcript → Fills input +``` + +## Frontend Components + +### 1. Voice Input Service (`src/services/voiceInput.ts`) +- Handles microphone access via `navigator.mediaDevices.getUserMedia()` +- Records audio using `MediaRecorder` API +- Converts recorded audio to base64 +- Sends to lambda via `transcribeAudio()` in `proxyClient.ts` + +### 2. Proxy Client (`src/proxyClient.ts`) +- `transcribeAudio(audioBlob)` - Sends audio to lambda with `op: "transcribe"` +- Uses same authenticated `postSigned()` method as chat/route operations +- Includes Supabase JWT token in Authorization header + +### 3. UI Integration (`assistant.ui.js`) +- Microphone button (🎤) added next to Stop and Clear Context buttons +- Click to start recording → shows (⏹️) and red background +- Click again to stop → shows loading (⏳) → transcribes → fills input field +- Displays status messages in the log + +## Backend Lambda Configuration + +### Environment Variables Required +```bash +DEEPGRAM_API_KEY= +GEMINI_API_KEY= +OASIS_API_BASE= +``` + +### Request Format +```json +{ + "op": "transcribe", + "audio": "", + "mimeType": "audio/webm;codecs=opus" +} +``` + +### Response Format +```json +{ + "transcript": "This is the transcribed text" +} +``` + +### Supported Audio Formats +The frontend attempts these MIME types in order: +1. `audio/webm;codecs=opus` (preferred) +2. `audio/webm` +3. `audio/ogg;codecs=opus` +4. `audio/mp4` + +## Lambda Function Structure + +Your current lambda already handles the `transcribe` operation correctly: + +1. ✅ Accepts `op: "transcribe"` +2. ✅ Expects `audio` (base64), `mimeType`, and optional `language` +3. ✅ Uses Deepgram first, falls back to Gemini +4. ✅ Returns `{ transcript: "..." }` + +## How to Test + +1. **Build the frontend:** + ```bash + cd browser/base/content/assistant/build + npm run build + ``` + +2. **Rebuild Firefox:** + ```bash + cd /Users/ashwinjohn/Projects/firefox-oasis + ./mach build + ``` + +3. **Run Firefox and open the assistant sidebar** + +4. **Test the microphone:** + - Ensure you're signed in (authentication required) + - Click the 🎤 button + - Grant microphone permissions when prompted + - Speak clearly + - Click ⏹️ to stop recording + - Watch the input field populate with transcribed text + +## Troubleshooting + +### "Failed to access microphone" +- Grant microphone permissions in Firefox +- Check `about:permissions` in Firefox +- On macOS, check System Preferences → Security & Privacy → Microphone + +### "Transcription failed" +- Check browser console for errors +- Verify `DEEPGRAM_API_KEY` is set in lambda +- Check lambda CloudWatch logs +- Ensure lambda has correct IAM permissions + +### "Please sign in to use voice input" +- User must be authenticated with Supabase +- Check that JWT token is being sent in Authorization header + +### Audio quality issues +- Deepgram works best with clear, noise-free audio +- Consider adding `language` parameter if not English +- Gemini fallback is slower but may work better for accented speech + +## Advanced Configuration + +### Add language selection (optional) +Modify `proxyClient.ts` to pass language: +```typescript +return postSigned("transcribe", { + audio: base64Audio, + mimeType: audioBlob.type, + language: "en-US" // or user-selected language +}); +``` + +### Force Gemini provider (optional) +Set lambda environment variable: +```bash +TRANSCRIBE_PROVIDER=gemini +``` + +## Integration with TTS (Future) + +Your lambda can also handle text-to-speech. To add TTS playback: + +1. Add a speaker button in the UI +2. Create `textToSpeech()` function in `proxyClient.ts` +3. Add TTS handler in lambda for `op: "tts"` +4. Play returned audio using Web Audio API + +Example TTS implementation already included in `proxyClient.ts` (ready to use when backend is implemented). diff --git a/browser/base/content/assistant/assistant.bundle.js b/browser/base/content/assistant/assistant.bundle.js new file mode 100644 index 0000000000000..b35c5a209c5b7 --- /dev/null +++ b/browser/base/content/assistant/assistant.bundle.js @@ -0,0 +1,62088 @@ +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __esm = (fn, res) => function __init() { + return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; +}; +var __commonJS = (cb, mod) => function __require() { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; +}; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// node_modules/uuid/dist/esm-browser/regex.js +var regex_default; +var init_regex = __esm({ + "node_modules/uuid/dist/esm-browser/regex.js"() { + regex_default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i; + } +}); + +// node_modules/uuid/dist/esm-browser/validate.js +function validate(uuid) { + return typeof uuid === "string" && regex_default.test(uuid); +} +var validate_default; +var init_validate = __esm({ + "node_modules/uuid/dist/esm-browser/validate.js"() { + init_regex(); + validate_default = validate; + } +}); + +// node_modules/uuid/dist/esm-browser/parse.js +function parse(uuid) { + if (!validate_default(uuid)) { + throw TypeError("Invalid UUID"); + } + var v; + var arr3 = new Uint8Array(16); + arr3[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; + arr3[1] = v >>> 16 & 255; + arr3[2] = v >>> 8 & 255; + arr3[3] = v & 255; + arr3[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; + arr3[5] = v & 255; + arr3[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; + arr3[7] = v & 255; + arr3[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; + arr3[9] = v & 255; + arr3[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 1099511627776 & 255; + arr3[11] = v / 4294967296 & 255; + arr3[12] = v >>> 24 & 255; + arr3[13] = v >>> 16 & 255; + arr3[14] = v >>> 8 & 255; + arr3[15] = v & 255; + return arr3; +} +var parse_default; +var init_parse = __esm({ + "node_modules/uuid/dist/esm-browser/parse.js"() { + init_validate(); + parse_default = parse; + } +}); + +// node_modules/uuid/dist/esm-browser/stringify.js +function unsafeStringify(arr3, offset = 0) { + return (byteToHex[arr3[offset + 0]] + byteToHex[arr3[offset + 1]] + byteToHex[arr3[offset + 2]] + byteToHex[arr3[offset + 3]] + "-" + byteToHex[arr3[offset + 4]] + byteToHex[arr3[offset + 5]] + "-" + byteToHex[arr3[offset + 6]] + byteToHex[arr3[offset + 7]] + "-" + byteToHex[arr3[offset + 8]] + byteToHex[arr3[offset + 9]] + "-" + byteToHex[arr3[offset + 10]] + byteToHex[arr3[offset + 11]] + byteToHex[arr3[offset + 12]] + byteToHex[arr3[offset + 13]] + byteToHex[arr3[offset + 14]] + byteToHex[arr3[offset + 15]]).toLowerCase(); +} +var byteToHex, i; +var init_stringify = __esm({ + "node_modules/uuid/dist/esm-browser/stringify.js"() { + byteToHex = []; + for (i = 0; i < 256; ++i) { + byteToHex.push((i + 256).toString(16).slice(1)); + } + } +}); + +// node_modules/uuid/dist/esm-browser/rng.js +function rng() { + if (!getRandomValues) { + getRandomValues = typeof crypto !== "undefined" && crypto.getRandomValues && crypto.getRandomValues.bind(crypto); + if (!getRandomValues) { + throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported"); + } + } + return getRandomValues(rnds8); +} +var getRandomValues, rnds8; +var init_rng = __esm({ + "node_modules/uuid/dist/esm-browser/rng.js"() { + rnds8 = new Uint8Array(16); + } +}); + +// node_modules/uuid/dist/esm-browser/v1.js +function v1(options, buf, offset) { + var i = buf && offset || 0; + var b = buf || new Array(16); + options = options || {}; + var node = options.node; + var clockseq = options.clockseq; + if (!options._v6) { + if (!node) { + node = _nodeId; + } + if (clockseq == null) { + clockseq = _clockseq; + } + } + if (node == null || clockseq == null) { + var seedBytes = options.random || (options.rng || rng)(); + if (node == null) { + node = [seedBytes[0], seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; + if (!_nodeId && !options._v6) { + node[0] |= 1; + _nodeId = node; + } + } + if (clockseq == null) { + clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 16383; + if (_clockseq === void 0 && !options._v6) { + _clockseq = clockseq; + } + } + } + var msecs = options.msecs !== void 0 ? options.msecs : Date.now(); + var nsecs = options.nsecs !== void 0 ? options.nsecs : _lastNSecs + 1; + var dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 1e4; + if (dt < 0 && options.clockseq === void 0) { + clockseq = clockseq + 1 & 16383; + } + if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === void 0) { + nsecs = 0; + } + if (nsecs >= 1e4) { + throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); + } + _lastMSecs = msecs; + _lastNSecs = nsecs; + _clockseq = clockseq; + msecs += 122192928e5; + var tl = ((msecs & 268435455) * 1e4 + nsecs) % 4294967296; + b[i++] = tl >>> 24 & 255; + b[i++] = tl >>> 16 & 255; + b[i++] = tl >>> 8 & 255; + b[i++] = tl & 255; + var tmh = msecs / 4294967296 * 1e4 & 268435455; + b[i++] = tmh >>> 8 & 255; + b[i++] = tmh & 255; + b[i++] = tmh >>> 24 & 15 | 16; + b[i++] = tmh >>> 16 & 255; + b[i++] = clockseq >>> 8 | 128; + b[i++] = clockseq & 255; + for (var n2 = 0; n2 < 6; ++n2) { + b[i + n2] = node[n2]; + } + return buf || unsafeStringify(b); +} +var _nodeId, _clockseq, _lastMSecs, _lastNSecs, v1_default; +var init_v1 = __esm({ + "node_modules/uuid/dist/esm-browser/v1.js"() { + init_rng(); + init_stringify(); + _lastMSecs = 0; + _lastNSecs = 0; + v1_default = v1; + } +}); + +// node_modules/uuid/dist/esm-browser/v1ToV6.js +function v1ToV6(uuid) { + var v1Bytes = typeof uuid === "string" ? parse_default(uuid) : uuid; + var v6Bytes = _v1ToV6(v1Bytes); + return typeof uuid === "string" ? unsafeStringify(v6Bytes) : v6Bytes; +} +function _v1ToV6(v1Bytes, randomize = false) { + return Uint8Array.of((v1Bytes[6] & 15) << 4 | v1Bytes[7] >> 4 & 15, (v1Bytes[7] & 15) << 4 | (v1Bytes[4] & 240) >> 4, (v1Bytes[4] & 15) << 4 | (v1Bytes[5] & 240) >> 4, (v1Bytes[5] & 15) << 4 | (v1Bytes[0] & 240) >> 4, (v1Bytes[0] & 15) << 4 | (v1Bytes[1] & 240) >> 4, (v1Bytes[1] & 15) << 4 | (v1Bytes[2] & 240) >> 4, 96 | v1Bytes[2] & 15, v1Bytes[3], v1Bytes[8], v1Bytes[9], v1Bytes[10], v1Bytes[11], v1Bytes[12], v1Bytes[13], v1Bytes[14], v1Bytes[15]); +} +var init_v1ToV6 = __esm({ + "node_modules/uuid/dist/esm-browser/v1ToV6.js"() { + init_parse(); + init_stringify(); + } +}); + +// node_modules/uuid/dist/esm-browser/v35.js +function stringToBytes(str) { + str = unescape(encodeURIComponent(str)); + var bytes = []; + for (var i = 0; i < str.length; ++i) { + bytes.push(str.charCodeAt(i)); + } + return bytes; +} +function v35(name, version2, hashfunc) { + function generateUUID(value, namespace, buf, offset) { + var _namespace; + if (typeof value === "string") { + value = stringToBytes(value); + } + if (typeof namespace === "string") { + namespace = parse_default(namespace); + } + if (((_namespace = namespace) === null || _namespace === void 0 ? void 0 : _namespace.length) !== 16) { + throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)"); + } + var bytes = new Uint8Array(16 + value.length); + bytes.set(namespace); + bytes.set(value, namespace.length); + bytes = hashfunc(bytes); + bytes[6] = bytes[6] & 15 | version2; + bytes[8] = bytes[8] & 63 | 128; + if (buf) { + offset = offset || 0; + for (var i = 0; i < 16; ++i) { + buf[offset + i] = bytes[i]; + } + return buf; + } + return unsafeStringify(bytes); + } + try { + generateUUID.name = name; + } catch (err) { + } + generateUUID.DNS = DNS; + generateUUID.URL = URL2; + return generateUUID; +} +var DNS, URL2; +var init_v35 = __esm({ + "node_modules/uuid/dist/esm-browser/v35.js"() { + init_stringify(); + init_parse(); + DNS = "6ba7b810-9dad-11d1-80b4-00c04fd430c8"; + URL2 = "6ba7b811-9dad-11d1-80b4-00c04fd430c8"; + } +}); + +// node_modules/uuid/dist/esm-browser/native.js +var randomUUID, native_default; +var init_native = __esm({ + "node_modules/uuid/dist/esm-browser/native.js"() { + randomUUID = typeof crypto !== "undefined" && crypto.randomUUID && crypto.randomUUID.bind(crypto); + native_default = { + randomUUID + }; + } +}); + +// node_modules/uuid/dist/esm-browser/v4.js +function v4(options, buf, offset) { + if (native_default.randomUUID && !buf && !options) { + return native_default.randomUUID(); + } + options = options || {}; + var rnds = options.random || (options.rng || rng)(); + rnds[6] = rnds[6] & 15 | 64; + rnds[8] = rnds[8] & 63 | 128; + if (buf) { + offset = offset || 0; + for (var i = 0; i < 16; ++i) { + buf[offset + i] = rnds[i]; + } + return buf; + } + return unsafeStringify(rnds); +} +var v4_default; +var init_v4 = __esm({ + "node_modules/uuid/dist/esm-browser/v4.js"() { + init_native(); + init_rng(); + init_stringify(); + v4_default = v4; + } +}); + +// node_modules/uuid/dist/esm-browser/sha1.js +function f(s, x, y, z) { + switch (s) { + case 0: + return x & y ^ ~x & z; + case 1: + return x ^ y ^ z; + case 2: + return x & y ^ x & z ^ y & z; + case 3: + return x ^ y ^ z; + } +} +function ROTL(x, n2) { + return x << n2 | x >>> 32 - n2; +} +function sha1(bytes) { + var K2 = [1518500249, 1859775393, 2400959708, 3395469782]; + var H = [1732584193, 4023233417, 2562383102, 271733878, 3285377520]; + if (typeof bytes === "string") { + var msg = unescape(encodeURIComponent(bytes)); + bytes = []; + for (var i = 0; i < msg.length; ++i) { + bytes.push(msg.charCodeAt(i)); + } + } else if (!Array.isArray(bytes)) { + bytes = Array.prototype.slice.call(bytes); + } + bytes.push(128); + var l = bytes.length / 4 + 2; + var N = Math.ceil(l / 16); + var M = new Array(N); + for (var _i = 0; _i < N; ++_i) { + var arr3 = new Uint32Array(16); + for (var j = 0; j < 16; ++j) { + arr3[j] = bytes[_i * 64 + j * 4] << 24 | bytes[_i * 64 + j * 4 + 1] << 16 | bytes[_i * 64 + j * 4 + 2] << 8 | bytes[_i * 64 + j * 4 + 3]; + } + M[_i] = arr3; + } + M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32); + M[N - 1][14] = Math.floor(M[N - 1][14]); + M[N - 1][15] = (bytes.length - 1) * 8 & 4294967295; + for (var _i2 = 0; _i2 < N; ++_i2) { + var W = new Uint32Array(80); + for (var t = 0; t < 16; ++t) { + W[t] = M[_i2][t]; + } + for (var _t = 16; _t < 80; ++_t) { + W[_t] = ROTL(W[_t - 3] ^ W[_t - 8] ^ W[_t - 14] ^ W[_t - 16], 1); + } + var a = H[0]; + var b = H[1]; + var c = H[2]; + var d = H[3]; + var e = H[4]; + for (var _t2 = 0; _t2 < 80; ++_t2) { + var s = Math.floor(_t2 / 20); + var T = ROTL(a, 5) + f(s, b, c, d) + e + K2[s] + W[_t2] >>> 0; + e = d; + d = c; + c = ROTL(b, 30) >>> 0; + b = a; + a = T; + } + H[0] = H[0] + a >>> 0; + H[1] = H[1] + b >>> 0; + H[2] = H[2] + c >>> 0; + H[3] = H[3] + d >>> 0; + H[4] = H[4] + e >>> 0; + } + return [H[0] >> 24 & 255, H[0] >> 16 & 255, H[0] >> 8 & 255, H[0] & 255, H[1] >> 24 & 255, H[1] >> 16 & 255, H[1] >> 8 & 255, H[1] & 255, H[2] >> 24 & 255, H[2] >> 16 & 255, H[2] >> 8 & 255, H[2] & 255, H[3] >> 24 & 255, H[3] >> 16 & 255, H[3] >> 8 & 255, H[3] & 255, H[4] >> 24 & 255, H[4] >> 16 & 255, H[4] >> 8 & 255, H[4] & 255]; +} +var sha1_default; +var init_sha1 = __esm({ + "node_modules/uuid/dist/esm-browser/sha1.js"() { + sha1_default = sha1; + } +}); + +// node_modules/uuid/dist/esm-browser/v5.js +var v5, v5_default; +var init_v5 = __esm({ + "node_modules/uuid/dist/esm-browser/v5.js"() { + init_v35(); + init_sha1(); + v5 = v35("v5", 80, sha1_default); + v5_default = v5; + } +}); + +// node_modules/uuid/dist/esm-browser/v6.js +function ownKeys(e, r) { + var t = Object.keys(e); + if (Object.getOwnPropertySymbols) { + var o = Object.getOwnPropertySymbols(e); + r && (o = o.filter(function(r2) { + return Object.getOwnPropertyDescriptor(e, r2).enumerable; + })), t.push.apply(t, o); + } + return t; +} +function _objectSpread(e) { + for (var r = 1; r < arguments.length; r++) { + var t = null != arguments[r] ? arguments[r] : {}; + r % 2 ? ownKeys(Object(t), true).forEach(function(r2) { + _defineProperty(e, r2, t[r2]); + }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function(r2) { + Object.defineProperty(e, r2, Object.getOwnPropertyDescriptor(t, r2)); + }); + } + return e; +} +function _defineProperty(e, r, t) { + return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: true, configurable: true, writable: true }) : e[r] = t, e; +} +function _toPropertyKey(t) { + var i = _toPrimitive(t, "string"); + return "symbol" == typeof i ? i : i + ""; +} +function _toPrimitive(t, r) { + if ("object" != typeof t || !t) return t; + var e = t[Symbol.toPrimitive]; + if (void 0 !== e) { + var i = e.call(t, r || "default"); + if ("object" != typeof i) return i; + throw new TypeError("@@toPrimitive must return a primitive value."); + } + return ("string" === r ? String : Number)(t); +} +function v6(options = {}, buf, offset = 0) { + var bytes = v1_default(_objectSpread(_objectSpread({}, options), {}, { + _v6: true + }), new Uint8Array(16)); + bytes = v1ToV6(bytes); + if (buf) { + for (var i = 0; i < 16; i++) { + buf[offset + i] = bytes[i]; + } + return buf; + } + return unsafeStringify(bytes); +} +var init_v6 = __esm({ + "node_modules/uuid/dist/esm-browser/v6.js"() { + init_stringify(); + init_v1(); + init_v1ToV6(); + } +}); + +// node_modules/uuid/dist/esm-browser/index.js +var init_esm_browser = __esm({ + "node_modules/uuid/dist/esm-browser/index.js"() { + init_v4(); + init_v5(); + init_v6(); + init_validate(); + } +}); + +// node_modules/decamelize/index.js +var require_decamelize = __commonJS({ + "node_modules/decamelize/index.js"(exports, module) { + "use strict"; + module.exports = function(str, sep) { + if (typeof str !== "string") { + throw new TypeError("Expected a string"); + } + sep = typeof sep === "undefined" ? "_" : sep; + return str.replace(/([a-z\d])([A-Z])/g, "$1" + sep + "$2").replace(/([A-Z]+)([A-Z][a-z\d]+)/g, "$1" + sep + "$2").toLowerCase(); + }; + } +}); + +// node_modules/camelcase/index.js +var require_camelcase = __commonJS({ + "node_modules/camelcase/index.js"(exports, module) { + "use strict"; + var UPPERCASE = /[\p{Lu}]/u; + var LOWERCASE = /[\p{Ll}]/u; + var LEADING_CAPITAL = /^[\p{Lu}](?![\p{Lu}])/gu; + var IDENTIFIER = /([\p{Alpha}\p{N}_]|$)/u; + var SEPARATORS = /[_.\- ]+/; + var LEADING_SEPARATORS = new RegExp("^" + SEPARATORS.source); + var SEPARATORS_AND_IDENTIFIER = new RegExp(SEPARATORS.source + IDENTIFIER.source, "gu"); + var NUMBERS_AND_IDENTIFIER = new RegExp("\\d+" + IDENTIFIER.source, "gu"); + var preserveCamelCase = (string, toLowerCase, toUpperCase) => { + let isLastCharLower = false; + let isLastCharUpper = false; + let isLastLastCharUpper = false; + for (let i = 0; i < string.length; i++) { + const character = string[i]; + if (isLastCharLower && UPPERCASE.test(character)) { + string = string.slice(0, i) + "-" + string.slice(i); + isLastCharLower = false; + isLastLastCharUpper = isLastCharUpper; + isLastCharUpper = true; + i++; + } else if (isLastCharUpper && isLastLastCharUpper && LOWERCASE.test(character)) { + string = string.slice(0, i - 1) + "-" + string.slice(i - 1); + isLastLastCharUpper = isLastCharUpper; + isLastCharUpper = false; + isLastCharLower = true; + } else { + isLastCharLower = toLowerCase(character) === character && toUpperCase(character) !== character; + isLastLastCharUpper = isLastCharUpper; + isLastCharUpper = toUpperCase(character) === character && toLowerCase(character) !== character; + } + } + return string; + }; + var preserveConsecutiveUppercase = (input, toLowerCase) => { + LEADING_CAPITAL.lastIndex = 0; + return input.replace(LEADING_CAPITAL, (m1) => toLowerCase(m1)); + }; + var postProcess = (input, toUpperCase) => { + SEPARATORS_AND_IDENTIFIER.lastIndex = 0; + NUMBERS_AND_IDENTIFIER.lastIndex = 0; + return input.replace(SEPARATORS_AND_IDENTIFIER, (_, identifier) => toUpperCase(identifier)).replace(NUMBERS_AND_IDENTIFIER, (m) => toUpperCase(m)); + }; + var camelCase2 = (input, options) => { + if (!(typeof input === "string" || Array.isArray(input))) { + throw new TypeError("Expected the input to be `string | string[]`"); + } + options = { + pascalCase: false, + preserveConsecutiveUppercase: false, + ...options + }; + if (Array.isArray(input)) { + input = input.map((x) => x.trim()).filter((x) => x.length).join("-"); + } else { + input = input.trim(); + } + if (input.length === 0) { + return ""; + } + const toLowerCase = options.locale === false ? (string) => string.toLowerCase() : (string) => string.toLocaleLowerCase(options.locale); + const toUpperCase = options.locale === false ? (string) => string.toUpperCase() : (string) => string.toLocaleUpperCase(options.locale); + if (input.length === 1) { + return options.pascalCase ? toUpperCase(input) : toLowerCase(input); + } + const hasUpperCase = input !== toLowerCase(input); + if (hasUpperCase) { + input = preserveCamelCase(input, toLowerCase, toUpperCase); + } + input = input.replace(LEADING_SEPARATORS, ""); + if (options.preserveConsecutiveUppercase) { + input = preserveConsecutiveUppercase(input, toLowerCase); + } else { + input = toLowerCase(input); + } + if (options.pascalCase) { + input = toUpperCase(input.charAt(0)) + input.slice(1); + } + return postProcess(input, toUpperCase); + }; + module.exports = camelCase2; + module.exports.default = camelCase2; + } +}); + +// node_modules/@langchain/core/dist/load/map_keys.js +function keyToJson(key, map) { + return map?.[key] || (0, import_decamelize.default)(key); +} +function keyFromJson(key, map) { + return map?.[key] || (0, import_camelcase.default)(key); +} +function mapKeys(fields, mapper, map) { + const mapped = {}; + for (const key in fields) { + if (Object.hasOwn(fields, key)) { + mapped[mapper(key, map)] = fields[key]; + } + } + return mapped; +} +var import_decamelize, import_camelcase; +var init_map_keys = __esm({ + "node_modules/@langchain/core/dist/load/map_keys.js"() { + import_decamelize = __toESM(require_decamelize(), 1); + import_camelcase = __toESM(require_camelcase(), 1); + } +}); + +// node_modules/@langchain/core/dist/load/serializable.js +var serializable_exports = {}; +__export(serializable_exports, { + Serializable: () => Serializable, + get_lc_unique_name: () => get_lc_unique_name +}); +function shallowCopy(obj) { + return Array.isArray(obj) ? [...obj] : { ...obj }; +} +function replaceSecrets(root2, secretsMap) { + const result = shallowCopy(root2); + for (const [path, secretId] of Object.entries(secretsMap)) { + const [last2, ...partsReverse] = path.split(".").reverse(); + let current = result; + for (const part of partsReverse.reverse()) { + if (current[part] === void 0) { + break; + } + current[part] = shallowCopy(current[part]); + current = current[part]; + } + if (current[last2] !== void 0) { + current[last2] = { + lc: 1, + type: "secret", + id: [secretId] + }; + } + } + return result; +} +function get_lc_unique_name(serializableClass) { + const parentClass = Object.getPrototypeOf(serializableClass); + const lcNameIsSubclassed = typeof serializableClass.lc_name === "function" && (typeof parentClass.lc_name !== "function" || serializableClass.lc_name() !== parentClass.lc_name()); + if (lcNameIsSubclassed) { + return serializableClass.lc_name(); + } else { + return serializableClass.name; + } +} +var Serializable; +var init_serializable = __esm({ + "node_modules/@langchain/core/dist/load/serializable.js"() { + init_map_keys(); + Serializable = class _Serializable { + /** + * The name of the serializable. Override to provide an alias or + * to preserve the serialized module name in minified environments. + * + * Implemented as a static method to support loading logic. + */ + static lc_name() { + return this.name; + } + /** + * The final serialized identifier for the module. + */ + get lc_id() { + return [ + ...this.lc_namespace, + get_lc_unique_name(this.constructor) + ]; + } + /** + * A map of secrets, which will be omitted from serialization. + * Keys are paths to the secret in constructor args, e.g. "foo.bar.baz". + * Values are the secret ids, which will be used when deserializing. + */ + get lc_secrets() { + return void 0; + } + /** + * A map of additional attributes to merge with constructor args. + * Keys are the attribute names, e.g. "foo". + * Values are the attribute values, which will be serialized. + * These attributes need to be accepted by the constructor as arguments. + */ + get lc_attributes() { + return void 0; + } + /** + * A map of aliases for constructor args. + * Keys are the attribute names, e.g. "foo". + * Values are the alias that will replace the key in serialization. + * This is used to eg. make argument names match Python. + */ + get lc_aliases() { + return void 0; + } + /** + * A manual list of keys that should be serialized. + * If not overridden, all fields passed into the constructor will be serialized. + */ + get lc_serializable_keys() { + return void 0; + } + constructor(kwargs, ..._args) { + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "lc_kwargs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + if (this.lc_serializable_keys !== void 0) { + this.lc_kwargs = Object.fromEntries(Object.entries(kwargs || {}).filter(([key]) => this.lc_serializable_keys?.includes(key))); + } else { + this.lc_kwargs = kwargs ?? {}; + } + } + toJSON() { + if (!this.lc_serializable) { + return this.toJSONNotImplemented(); + } + if ( + // eslint-disable-next-line no-instanceof/no-instanceof + this.lc_kwargs instanceof _Serializable || typeof this.lc_kwargs !== "object" || Array.isArray(this.lc_kwargs) + ) { + return this.toJSONNotImplemented(); + } + const aliases = {}; + const secrets = {}; + const kwargs = Object.keys(this.lc_kwargs).reduce((acc, key) => { + acc[key] = key in this ? this[key] : this.lc_kwargs[key]; + return acc; + }, {}); + for (let current = Object.getPrototypeOf(this); current; current = Object.getPrototypeOf(current)) { + Object.assign(aliases, Reflect.get(current, "lc_aliases", this)); + Object.assign(secrets, Reflect.get(current, "lc_secrets", this)); + Object.assign(kwargs, Reflect.get(current, "lc_attributes", this)); + } + Object.keys(secrets).forEach((keyPath) => { + let read = this; + let write = kwargs; + const [last2, ...partsReverse] = keyPath.split(".").reverse(); + for (const key of partsReverse.reverse()) { + if (!(key in read) || read[key] === void 0) + return; + if (!(key in write) || write[key] === void 0) { + if (typeof read[key] === "object" && read[key] != null) { + write[key] = {}; + } else if (Array.isArray(read[key])) { + write[key] = []; + } + } + read = read[key]; + write = write[key]; + } + if (last2 in read && read[last2] !== void 0) { + write[last2] = write[last2] || read[last2]; + } + }); + return { + lc: 1, + type: "constructor", + id: this.lc_id, + kwargs: mapKeys(Object.keys(secrets).length ? replaceSecrets(kwargs, secrets) : kwargs, keyToJson, aliases) + }; + } + toJSONNotImplemented() { + return { + lc: 1, + type: "not_implemented", + id: this.lc_id + }; + } + }; + } +}); + +// node_modules/@langchain/core/dist/errors/index.js +function addLangChainErrorFields(error, lc_error_code) { + error.lc_error_code = lc_error_code; + error.message = `${error.message} + +Troubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${lc_error_code}/ +`; + return error; +} +var init_errors = __esm({ + "node_modules/@langchain/core/dist/errors/index.js"() { + } +}); + +// node_modules/@langchain/core/dist/tools/utils.js +function _isToolCall(toolCall) { + return !!(toolCall && typeof toolCall === "object" && "type" in toolCall && toolCall.type === "tool_call"); +} +function _configHasToolCallId(config2) { + return !!(config2 && typeof config2 === "object" && "toolCall" in config2 && config2.toolCall != null && typeof config2.toolCall === "object" && "id" in config2.toolCall && typeof config2.toolCall.id === "string"); +} +var ToolInputParsingException; +var init_utils = __esm({ + "node_modules/@langchain/core/dist/tools/utils.js"() { + ToolInputParsingException = class extends Error { + constructor(message, output) { + super(message); + Object.defineProperty(this, "output", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.output = output; + } + }; + } +}); + +// node_modules/@langchain/core/dist/utils/json.js +function parseJsonMarkdown(s, parser = parsePartialJson) { + s = s.trim(); + const firstFenceIndex = s.indexOf("```"); + if (firstFenceIndex === -1) { + return parser(s); + } + let contentAfterFence = s.substring(firstFenceIndex + 3); + if (contentAfterFence.startsWith("json\n")) { + contentAfterFence = contentAfterFence.substring(5); + } else if (contentAfterFence.startsWith("json")) { + contentAfterFence = contentAfterFence.substring(4); + } else if (contentAfterFence.startsWith("\n")) { + contentAfterFence = contentAfterFence.substring(1); + } + const closingFenceIndex = contentAfterFence.indexOf("```"); + let finalContent = contentAfterFence; + if (closingFenceIndex !== -1) { + finalContent = contentAfterFence.substring(0, closingFenceIndex); + } + return parser(finalContent.trim()); +} +function parsePartialJson(s) { + if (typeof s === "undefined") { + return null; + } + try { + return JSON.parse(s); + } catch (error) { + } + let new_s = ""; + const stack = []; + let isInsideString = false; + let escaped = false; + for (let char of s) { + if (isInsideString) { + if (char === '"' && !escaped) { + isInsideString = false; + } else if (char === "\n" && !escaped) { + char = "\\n"; + } else if (char === "\\") { + escaped = !escaped; + } else { + escaped = false; + } + } else { + if (char === '"') { + isInsideString = true; + escaped = false; + } else if (char === "{") { + stack.push("}"); + } else if (char === "[") { + stack.push("]"); + } else if (char === "}" || char === "]") { + if (stack && stack[stack.length - 1] === char) { + stack.pop(); + } else { + return null; + } + } + } + new_s += char; + } + if (isInsideString) { + new_s += '"'; + } + for (let i = stack.length - 1; i >= 0; i -= 1) { + new_s += stack[i]; + } + try { + return JSON.parse(new_s); + } catch (error) { + return null; + } +} +var init_json = __esm({ + "node_modules/@langchain/core/dist/utils/json.js"() { + } +}); + +// node_modules/@langchain/core/dist/messages/content_blocks.js +function isDataContentBlock(content_block) { + return typeof content_block === "object" && content_block !== null && "type" in content_block && typeof content_block.type === "string" && "source_type" in content_block && (content_block.source_type === "url" || content_block.source_type === "base64" || content_block.source_type === "text" || content_block.source_type === "id"); +} +function isURLContentBlock(content_block) { + return isDataContentBlock(content_block) && content_block.source_type === "url" && "url" in content_block && typeof content_block.url === "string"; +} +function isBase64ContentBlock(content_block) { + return isDataContentBlock(content_block) && content_block.source_type === "base64" && "data" in content_block && typeof content_block.data === "string"; +} +function isPlainTextContentBlock(content_block) { + return isDataContentBlock(content_block) && content_block.source_type === "text" && "text" in content_block && typeof content_block.text === "string"; +} +function isIDContentBlock(content_block) { + return isDataContentBlock(content_block) && content_block.source_type === "id" && "id" in content_block && typeof content_block.id === "string"; +} +function convertToOpenAIImageBlock(content_block) { + if (isDataContentBlock(content_block)) { + if (content_block.source_type === "url") { + return { + type: "image_url", + image_url: { + url: content_block.url + } + }; + } + if (content_block.source_type === "base64") { + if (!content_block.mime_type) { + throw new Error("mime_type key is required for base64 data."); + } + const mime_type = content_block.mime_type; + return { + type: "image_url", + image_url: { + url: `data:${mime_type};base64,${content_block.data}` + } + }; + } + } + throw new Error("Unsupported source type. Only 'url' and 'base64' are supported."); +} +function parseMimeType(mime_type) { + const parts = mime_type.split(";")[0].split("/"); + if (parts.length !== 2) { + throw new Error(`Invalid mime type: "${mime_type}" - does not match type/subtype format.`); + } + const type = parts[0].trim(); + const subtype = parts[1].trim(); + if (type === "" || subtype === "") { + throw new Error(`Invalid mime type: "${mime_type}" - type or subtype is empty.`); + } + const parameters = {}; + for (const parameterKvp of mime_type.split(";").slice(1)) { + const parameterParts = parameterKvp.split("="); + if (parameterParts.length !== 2) { + throw new Error(`Invalid parameter syntax in mime type: "${mime_type}".`); + } + const key = parameterParts[0].trim(); + const value = parameterParts[1].trim(); + if (key === "") { + throw new Error(`Invalid parameter syntax in mime type: "${mime_type}".`); + } + parameters[key] = value; + } + return { + type, + subtype, + parameters + }; +} +function parseBase64DataUrl({ dataUrl: data_url, asTypedArray = false }) { + const formatMatch = data_url.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/); + let mime_type; + if (formatMatch) { + mime_type = formatMatch[1].toLowerCase(); + const data = asTypedArray ? Uint8Array.from(atob(formatMatch[2]), (c) => c.charCodeAt(0)) : formatMatch[2]; + return { + mime_type, + data + }; + } + return void 0; +} +function convertToProviderContentBlock(block, converter) { + if (block.type === "text") { + if (!converter.fromStandardTextBlock) { + throw new Error(`Converter for ${converter.providerName} does not implement \`fromStandardTextBlock\` method.`); + } + return converter.fromStandardTextBlock(block); + } + if (block.type === "image") { + if (!converter.fromStandardImageBlock) { + throw new Error(`Converter for ${converter.providerName} does not implement \`fromStandardImageBlock\` method.`); + } + return converter.fromStandardImageBlock(block); + } + if (block.type === "audio") { + if (!converter.fromStandardAudioBlock) { + throw new Error(`Converter for ${converter.providerName} does not implement \`fromStandardAudioBlock\` method.`); + } + return converter.fromStandardAudioBlock(block); + } + if (block.type === "file") { + if (!converter.fromStandardFileBlock) { + throw new Error(`Converter for ${converter.providerName} does not implement \`fromStandardFileBlock\` method.`); + } + return converter.fromStandardFileBlock(block); + } + throw new Error(`Unable to convert content block type '${block.type}' to provider-specific format: not recognized.`); +} +var init_content_blocks = __esm({ + "node_modules/@langchain/core/dist/messages/content_blocks.js"() { + } +}); + +// node_modules/@langchain/core/dist/messages/base.js +function mergeContent(firstContent, secondContent) { + if (typeof firstContent === "string") { + if (firstContent === "") { + return secondContent; + } + if (typeof secondContent === "string") { + return firstContent + secondContent; + } else if (Array.isArray(secondContent) && secondContent.some((c) => isDataContentBlock(c))) { + return [ + { + type: "text", + source_type: "text", + text: firstContent + }, + ...secondContent + ]; + } else { + return [{ type: "text", text: firstContent }, ...secondContent]; + } + } else if (Array.isArray(secondContent)) { + return _mergeLists(firstContent, secondContent) ?? [ + ...firstContent, + ...secondContent + ]; + } else { + if (secondContent === "") { + return firstContent; + } else if (Array.isArray(firstContent) && firstContent.some((c) => isDataContentBlock(c))) { + return [ + ...firstContent, + { + type: "file", + source_type: "text", + text: secondContent + } + ]; + } else { + return [...firstContent, { type: "text", text: secondContent }]; + } + } +} +function _mergeStatus(left, right) { + if (left === "error" || right === "error") { + return "error"; + } + return "success"; +} +function stringifyWithDepthLimit(obj, depthLimit) { + function helper(obj2, currentDepth) { + if (typeof obj2 !== "object" || obj2 === null || obj2 === void 0) { + return obj2; + } + if (currentDepth >= depthLimit) { + if (Array.isArray(obj2)) { + return "[Array]"; + } + return "[Object]"; + } + if (Array.isArray(obj2)) { + return obj2.map((item) => helper(item, currentDepth + 1)); + } + const result = {}; + for (const key of Object.keys(obj2)) { + result[key] = helper(obj2[key], currentDepth + 1); + } + return result; + } + return JSON.stringify(helper(obj, 0), null, 2); +} +function isOpenAIToolCallArray(value) { + return Array.isArray(value) && value.every((v) => typeof v.index === "number"); +} +function _mergeDicts(left, right) { + const merged = { ...left }; + for (const [key, value] of Object.entries(right)) { + if (merged[key] == null) { + merged[key] = value; + } else if (value == null) { + continue; + } else if (typeof merged[key] !== typeof value || Array.isArray(merged[key]) !== Array.isArray(value)) { + throw new Error(`field[${key}] already exists in the message chunk, but with a different type.`); + } else if (typeof merged[key] === "string") { + if (key === "type") { + continue; + } + merged[key] += value; + } else if (typeof merged[key] === "object" && !Array.isArray(merged[key])) { + merged[key] = _mergeDicts(merged[key], value); + } else if (Array.isArray(merged[key])) { + merged[key] = _mergeLists(merged[key], value); + } else if (merged[key] === value) { + continue; + } else { + console.warn(`field[${key}] already exists in this message chunk and value has unsupported type.`); + } + } + return merged; +} +function _mergeLists(left, right) { + if (left === void 0 && right === void 0) { + return void 0; + } else if (left === void 0 || right === void 0) { + return left || right; + } else { + const merged = [...left]; + for (const item of right) { + if (typeof item === "object" && "index" in item && typeof item.index === "number") { + const toMerge = merged.findIndex((leftItem) => leftItem.index === item.index); + if (toMerge !== -1) { + merged[toMerge] = _mergeDicts(merged[toMerge], item); + } else { + merged.push(item); + } + } else if (typeof item === "object" && "text" in item && item.text === "") { + continue; + } else { + merged.push(item); + } + } + return merged; + } +} +function _mergeObj(left, right) { + if (!left && !right) { + throw new Error("Cannot merge two undefined objects."); + } + if (!left || !right) { + return left || right; + } else if (typeof left !== typeof right) { + throw new Error(`Cannot merge objects of different types. +Left ${typeof left} +Right ${typeof right}`); + } else if (typeof left === "string" && typeof right === "string") { + return left + right; + } else if (Array.isArray(left) && Array.isArray(right)) { + return _mergeLists(left, right); + } else if (typeof left === "object" && typeof right === "object") { + return _mergeDicts(left, right); + } else if (left === right) { + return left; + } else { + throw new Error(`Can not merge objects of different types. +Left ${left} +Right ${right}`); + } +} +function _isMessageFieldWithRole(x) { + return typeof x.role === "string"; +} +function isBaseMessage(messageLike) { + return typeof messageLike?._getType === "function"; +} +function isBaseMessageChunk(messageLike) { + return isBaseMessage(messageLike) && typeof messageLike.concat === "function"; +} +var BaseMessage, BaseMessageChunk; +var init_base = __esm({ + "node_modules/@langchain/core/dist/messages/base.js"() { + init_serializable(); + init_content_blocks(); + BaseMessage = class extends Serializable { + get lc_aliases() { + return { + additional_kwargs: "additional_kwargs", + response_metadata: "response_metadata" + }; + } + /** + * Get text content of the message. + */ + get text() { + if (typeof this.content === "string") { + return this.content; + } + if (!Array.isArray(this.content)) + return ""; + return this.content.map((c) => { + if (typeof c === "string") + return c; + if (c.type === "text") + return c.text; + return ""; + }).join(""); + } + /** The type of the message. */ + getType() { + return this._getType(); + } + constructor(fields, kwargs) { + if (typeof fields === "string") { + fields = { + content: fields, + additional_kwargs: kwargs, + response_metadata: {} + }; + } + if (!fields.additional_kwargs) { + fields.additional_kwargs = {}; + } + if (!fields.response_metadata) { + fields.response_metadata = {}; + } + super(fields); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain_core", "messages"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "content", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "additional_kwargs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "response_metadata", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "id", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.name = fields.name; + this.content = fields.content; + this.additional_kwargs = fields.additional_kwargs; + this.response_metadata = fields.response_metadata; + this.id = fields.id; + } + toDict() { + return { + type: this._getType(), + data: this.toJSON().kwargs + }; + } + static lc_name() { + return "BaseMessage"; + } + // Can't be protected for silly reasons + get _printableFields() { + return { + id: this.id, + content: this.content, + name: this.name, + additional_kwargs: this.additional_kwargs, + response_metadata: this.response_metadata + }; + } + // this private method is used to update the ID for the runtime + // value as well as in lc_kwargs for serialisation + _updateId(value) { + this.id = value; + this.lc_kwargs.id = value; + } + get [Symbol.toStringTag]() { + return this.constructor.lc_name(); + } + // Override the default behavior of console.log + [Symbol.for("nodejs.util.inspect.custom")](depth) { + if (depth === null) { + return this; + } + const printable = stringifyWithDepthLimit(this._printableFields, Math.max(4, depth)); + return `${this.constructor.lc_name()} ${printable}`; + } + }; + BaseMessageChunk = class extends BaseMessage { + }; + } +}); + +// node_modules/@langchain/core/dist/messages/tool.js +function isDirectToolOutput(x) { + return x != null && typeof x === "object" && "lc_direct_tool_output" in x && x.lc_direct_tool_output === true; +} +function defaultToolCallParser(rawToolCalls) { + const toolCalls = []; + const invalidToolCalls = []; + for (const toolCall of rawToolCalls) { + if (!toolCall.function) { + continue; + } else { + const functionName = toolCall.function.name; + try { + const functionArgs = JSON.parse(toolCall.function.arguments); + const parsed = { + name: functionName || "", + args: functionArgs || {}, + id: toolCall.id + }; + toolCalls.push(parsed); + } catch (error) { + invalidToolCalls.push({ + name: functionName, + args: toolCall.function.arguments, + id: toolCall.id, + error: "Malformed args." + }); + } + } + } + return [toolCalls, invalidToolCalls]; +} +function isToolMessage(x) { + return x._getType() === "tool"; +} +function isToolMessageChunk(x) { + return x._getType() === "tool"; +} +var ToolMessage, ToolMessageChunk; +var init_tool = __esm({ + "node_modules/@langchain/core/dist/messages/tool.js"() { + init_base(); + ToolMessage = class extends BaseMessage { + static lc_name() { + return "ToolMessage"; + } + get lc_aliases() { + return { tool_call_id: "tool_call_id" }; + } + constructor(fields, tool_call_id, name) { + if (typeof fields === "string") { + fields = { content: fields, name, tool_call_id }; + } + super(fields); + Object.defineProperty(this, "lc_direct_tool_output", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "status", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "tool_call_id", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "metadata", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "artifact", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.tool_call_id = fields.tool_call_id; + this.artifact = fields.artifact; + this.status = fields.status; + this.metadata = fields.metadata; + } + _getType() { + return "tool"; + } + static isInstance(message) { + return message._getType() === "tool"; + } + get _printableFields() { + return { + ...super._printableFields, + tool_call_id: this.tool_call_id, + artifact: this.artifact + }; + } + }; + ToolMessageChunk = class _ToolMessageChunk extends BaseMessageChunk { + constructor(fields) { + super(fields); + Object.defineProperty(this, "tool_call_id", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "status", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "artifact", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.tool_call_id = fields.tool_call_id; + this.artifact = fields.artifact; + this.status = fields.status; + } + static lc_name() { + return "ToolMessageChunk"; + } + _getType() { + return "tool"; + } + concat(chunk) { + return new _ToolMessageChunk({ + content: mergeContent(this.content, chunk.content), + additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs), + response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata), + artifact: _mergeObj(this.artifact, chunk.artifact), + tool_call_id: this.tool_call_id, + id: this.id ?? chunk.id, + status: _mergeStatus(this.status, chunk.status) + }); + } + get _printableFields() { + return { + ...super._printableFields, + tool_call_id: this.tool_call_id, + artifact: this.artifact + }; + } + }; + } +}); + +// node_modules/@langchain/core/dist/messages/ai.js +function isAIMessage(x) { + return x._getType() === "ai"; +} +function isAIMessageChunk(x) { + return x._getType() === "ai"; +} +var AIMessage, AIMessageChunk; +var init_ai = __esm({ + "node_modules/@langchain/core/dist/messages/ai.js"() { + init_json(); + init_base(); + init_tool(); + AIMessage = class extends BaseMessage { + get lc_aliases() { + return { + ...super.lc_aliases, + tool_calls: "tool_calls", + invalid_tool_calls: "invalid_tool_calls" + }; + } + constructor(fields, kwargs) { + let initParams; + if (typeof fields === "string") { + initParams = { + content: fields, + tool_calls: [], + invalid_tool_calls: [], + additional_kwargs: kwargs ?? {} + }; + } else { + initParams = fields; + const rawToolCalls = initParams.additional_kwargs?.tool_calls; + const toolCalls = initParams.tool_calls; + if (!(rawToolCalls == null) && rawToolCalls.length > 0 && (toolCalls === void 0 || toolCalls.length === 0)) { + console.warn([ + "New LangChain packages are available that more efficiently handle", + "tool calling.\n\nPlease upgrade your packages to versions that set", + "message tool calls. e.g., `yarn add @langchain/anthropic`,", + "yarn add @langchain/openai`, etc." + ].join(" ")); + } + try { + if (!(rawToolCalls == null) && toolCalls === void 0) { + const [toolCalls2, invalidToolCalls] = defaultToolCallParser(rawToolCalls); + initParams.tool_calls = toolCalls2 ?? []; + initParams.invalid_tool_calls = invalidToolCalls ?? []; + } else { + initParams.tool_calls = initParams.tool_calls ?? []; + initParams.invalid_tool_calls = initParams.invalid_tool_calls ?? []; + } + } catch (e) { + initParams.tool_calls = []; + initParams.invalid_tool_calls = []; + } + } + super(initParams); + Object.defineProperty(this, "tool_calls", { + enumerable: true, + configurable: true, + writable: true, + value: [] + }); + Object.defineProperty(this, "invalid_tool_calls", { + enumerable: true, + configurable: true, + writable: true, + value: [] + }); + Object.defineProperty(this, "usage_metadata", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + if (typeof initParams !== "string") { + this.tool_calls = initParams.tool_calls ?? this.tool_calls; + this.invalid_tool_calls = initParams.invalid_tool_calls ?? this.invalid_tool_calls; + } + this.usage_metadata = initParams.usage_metadata; + } + static lc_name() { + return "AIMessage"; + } + _getType() { + return "ai"; + } + get _printableFields() { + return { + ...super._printableFields, + tool_calls: this.tool_calls, + invalid_tool_calls: this.invalid_tool_calls, + usage_metadata: this.usage_metadata + }; + } + }; + AIMessageChunk = class _AIMessageChunk extends BaseMessageChunk { + constructor(fields) { + let initParams; + if (typeof fields === "string") { + initParams = { + content: fields, + tool_calls: [], + invalid_tool_calls: [], + tool_call_chunks: [] + }; + } else if (fields.tool_call_chunks === void 0) { + initParams = { + ...fields, + tool_calls: fields.tool_calls ?? [], + invalid_tool_calls: [], + tool_call_chunks: [], + usage_metadata: fields.usage_metadata !== void 0 ? fields.usage_metadata : void 0 + }; + } else { + const groupedToolCallChunk = fields.tool_call_chunks.reduce((acc, chunk) => { + const chunkId = chunk.id || `fallback-${chunk.index || 0}`; + acc[chunkId] = acc[chunkId] ?? []; + acc[chunkId].push(chunk); + return acc; + }, {}); + const toolCalls = []; + const invalidToolCalls = []; + for (const [id, chunks] of Object.entries(groupedToolCallChunk)) { + let parsedArgs = {}; + const name = chunks[0]?.name ?? ""; + const joinedArgs = chunks.map((c) => c.args || "").join(""); + const argsStr = joinedArgs.length ? joinedArgs : "{}"; + const originalId = chunks[0]?.id || id; + try { + parsedArgs = parsePartialJson(argsStr); + if (parsedArgs === null || typeof parsedArgs !== "object" || Array.isArray(parsedArgs)) { + throw new Error("Malformed tool call chunk args."); + } + toolCalls.push({ + name, + args: parsedArgs, + id: originalId, + type: "tool_call" + }); + } catch (e) { + invalidToolCalls.push({ + name, + args: argsStr, + id: originalId, + error: "Malformed args.", + type: "invalid_tool_call" + }); + } + } + initParams = { + ...fields, + tool_calls: toolCalls, + invalid_tool_calls: invalidToolCalls, + usage_metadata: fields.usage_metadata !== void 0 ? fields.usage_metadata : void 0 + }; + } + super(initParams); + Object.defineProperty(this, "tool_calls", { + enumerable: true, + configurable: true, + writable: true, + value: [] + }); + Object.defineProperty(this, "invalid_tool_calls", { + enumerable: true, + configurable: true, + writable: true, + value: [] + }); + Object.defineProperty(this, "tool_call_chunks", { + enumerable: true, + configurable: true, + writable: true, + value: [] + }); + Object.defineProperty(this, "usage_metadata", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.tool_call_chunks = initParams.tool_call_chunks ?? this.tool_call_chunks; + this.tool_calls = initParams.tool_calls ?? this.tool_calls; + this.invalid_tool_calls = initParams.invalid_tool_calls ?? this.invalid_tool_calls; + this.usage_metadata = initParams.usage_metadata; + } + get lc_aliases() { + return { + ...super.lc_aliases, + tool_calls: "tool_calls", + invalid_tool_calls: "invalid_tool_calls", + tool_call_chunks: "tool_call_chunks" + }; + } + static lc_name() { + return "AIMessageChunk"; + } + _getType() { + return "ai"; + } + get _printableFields() { + return { + ...super._printableFields, + tool_calls: this.tool_calls, + tool_call_chunks: this.tool_call_chunks, + invalid_tool_calls: this.invalid_tool_calls, + usage_metadata: this.usage_metadata + }; + } + concat(chunk) { + const combinedFields = { + content: mergeContent(this.content, chunk.content), + additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs), + response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata), + tool_call_chunks: [], + id: this.id ?? chunk.id + }; + if (this.tool_call_chunks !== void 0 || chunk.tool_call_chunks !== void 0) { + const rawToolCalls = _mergeLists(this.tool_call_chunks, chunk.tool_call_chunks); + if (rawToolCalls !== void 0 && rawToolCalls.length > 0) { + combinedFields.tool_call_chunks = rawToolCalls; + } + } + if (this.usage_metadata !== void 0 || chunk.usage_metadata !== void 0) { + const inputTokenDetails = { + ...(this.usage_metadata?.input_token_details?.audio !== void 0 || chunk.usage_metadata?.input_token_details?.audio !== void 0) && { + audio: (this.usage_metadata?.input_token_details?.audio ?? 0) + (chunk.usage_metadata?.input_token_details?.audio ?? 0) + }, + ...(this.usage_metadata?.input_token_details?.cache_read !== void 0 || chunk.usage_metadata?.input_token_details?.cache_read !== void 0) && { + cache_read: (this.usage_metadata?.input_token_details?.cache_read ?? 0) + (chunk.usage_metadata?.input_token_details?.cache_read ?? 0) + }, + ...(this.usage_metadata?.input_token_details?.cache_creation !== void 0 || chunk.usage_metadata?.input_token_details?.cache_creation !== void 0) && { + cache_creation: (this.usage_metadata?.input_token_details?.cache_creation ?? 0) + (chunk.usage_metadata?.input_token_details?.cache_creation ?? 0) + } + }; + const outputTokenDetails = { + ...(this.usage_metadata?.output_token_details?.audio !== void 0 || chunk.usage_metadata?.output_token_details?.audio !== void 0) && { + audio: (this.usage_metadata?.output_token_details?.audio ?? 0) + (chunk.usage_metadata?.output_token_details?.audio ?? 0) + }, + ...(this.usage_metadata?.output_token_details?.reasoning !== void 0 || chunk.usage_metadata?.output_token_details?.reasoning !== void 0) && { + reasoning: (this.usage_metadata?.output_token_details?.reasoning ?? 0) + (chunk.usage_metadata?.output_token_details?.reasoning ?? 0) + } + }; + const left = this.usage_metadata ?? { + input_tokens: 0, + output_tokens: 0, + total_tokens: 0 + }; + const right = chunk.usage_metadata ?? { + input_tokens: 0, + output_tokens: 0, + total_tokens: 0 + }; + const usage_metadata = { + input_tokens: left.input_tokens + right.input_tokens, + output_tokens: left.output_tokens + right.output_tokens, + total_tokens: left.total_tokens + right.total_tokens, + // Do not include `input_token_details` / `output_token_details` keys in combined fields + // unless their values are defined. + ...Object.keys(inputTokenDetails).length > 0 && { + input_token_details: inputTokenDetails + }, + ...Object.keys(outputTokenDetails).length > 0 && { + output_token_details: outputTokenDetails + } + }; + combinedFields.usage_metadata = usage_metadata; + } + return new _AIMessageChunk(combinedFields); + } + }; + } +}); + +// node_modules/@langchain/core/dist/messages/chat.js +function isChatMessage(x) { + return x._getType() === "generic"; +} +function isChatMessageChunk(x) { + return x._getType() === "generic"; +} +var ChatMessage, ChatMessageChunk; +var init_chat = __esm({ + "node_modules/@langchain/core/dist/messages/chat.js"() { + init_base(); + ChatMessage = class _ChatMessage extends BaseMessage { + static lc_name() { + return "ChatMessage"; + } + static _chatMessageClass() { + return _ChatMessage; + } + constructor(fields, role) { + if (typeof fields === "string") { + fields = { content: fields, role }; + } + super(fields); + Object.defineProperty(this, "role", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.role = fields.role; + } + _getType() { + return "generic"; + } + static isInstance(message) { + return message._getType() === "generic"; + } + get _printableFields() { + return { + ...super._printableFields, + role: this.role + }; + } + }; + ChatMessageChunk = class _ChatMessageChunk extends BaseMessageChunk { + static lc_name() { + return "ChatMessageChunk"; + } + constructor(fields, role) { + if (typeof fields === "string") { + fields = { content: fields, role }; + } + super(fields); + Object.defineProperty(this, "role", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.role = fields.role; + } + _getType() { + return "generic"; + } + concat(chunk) { + return new _ChatMessageChunk({ + content: mergeContent(this.content, chunk.content), + additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs), + response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata), + role: this.role, + id: this.id ?? chunk.id + }); + } + get _printableFields() { + return { + ...super._printableFields, + role: this.role + }; + } + }; + } +}); + +// node_modules/@langchain/core/dist/messages/function.js +function isFunctionMessage(x) { + return x._getType() === "function"; +} +function isFunctionMessageChunk(x) { + return x._getType() === "function"; +} +var FunctionMessage, FunctionMessageChunk; +var init_function = __esm({ + "node_modules/@langchain/core/dist/messages/function.js"() { + init_base(); + FunctionMessage = class extends BaseMessage { + static lc_name() { + return "FunctionMessage"; + } + constructor(fields, name) { + if (typeof fields === "string") { + fields = { content: fields, name }; + } + super(fields); + } + _getType() { + return "function"; + } + }; + FunctionMessageChunk = class _FunctionMessageChunk extends BaseMessageChunk { + static lc_name() { + return "FunctionMessageChunk"; + } + _getType() { + return "function"; + } + concat(chunk) { + return new _FunctionMessageChunk({ + content: mergeContent(this.content, chunk.content), + additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs), + response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata), + name: this.name ?? "", + id: this.id ?? chunk.id + }); + } + }; + } +}); + +// node_modules/@langchain/core/dist/messages/human.js +function isHumanMessage(x) { + return x.getType() === "human"; +} +function isHumanMessageChunk(x) { + return x.getType() === "human"; +} +var HumanMessage, HumanMessageChunk; +var init_human = __esm({ + "node_modules/@langchain/core/dist/messages/human.js"() { + init_base(); + HumanMessage = class extends BaseMessage { + static lc_name() { + return "HumanMessage"; + } + _getType() { + return "human"; + } + constructor(fields, kwargs) { + super(fields, kwargs); + } + }; + HumanMessageChunk = class _HumanMessageChunk extends BaseMessageChunk { + static lc_name() { + return "HumanMessageChunk"; + } + _getType() { + return "human"; + } + constructor(fields, kwargs) { + super(fields, kwargs); + } + concat(chunk) { + return new _HumanMessageChunk({ + content: mergeContent(this.content, chunk.content), + additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs), + response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata), + id: this.id ?? chunk.id + }); + } + }; + } +}); + +// node_modules/@langchain/core/dist/messages/system.js +function isSystemMessage(x) { + return x._getType() === "system"; +} +function isSystemMessageChunk(x) { + return x._getType() === "system"; +} +var SystemMessage, SystemMessageChunk; +var init_system = __esm({ + "node_modules/@langchain/core/dist/messages/system.js"() { + init_base(); + SystemMessage = class extends BaseMessage { + static lc_name() { + return "SystemMessage"; + } + _getType() { + return "system"; + } + constructor(fields, kwargs) { + super(fields, kwargs); + } + }; + SystemMessageChunk = class _SystemMessageChunk extends BaseMessageChunk { + static lc_name() { + return "SystemMessageChunk"; + } + _getType() { + return "system"; + } + constructor(fields, kwargs) { + super(fields, kwargs); + } + concat(chunk) { + return new _SystemMessageChunk({ + content: mergeContent(this.content, chunk.content), + additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs), + response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata), + id: this.id ?? chunk.id + }); + } + }; + } +}); + +// node_modules/@langchain/core/dist/messages/utils.js +function _coerceToolCall(toolCall) { + if (_isToolCall(toolCall)) { + return toolCall; + } else if (typeof toolCall.id === "string" && toolCall.type === "function" && typeof toolCall.function === "object" && toolCall.function !== null && "arguments" in toolCall.function && typeof toolCall.function.arguments === "string" && "name" in toolCall.function && typeof toolCall.function.name === "string") { + return { + id: toolCall.id, + args: JSON.parse(toolCall.function.arguments), + name: toolCall.function.name, + type: "tool_call" + }; + } else { + return toolCall; + } +} +function isSerializedConstructor(x) { + return typeof x === "object" && x != null && x.lc === 1 && Array.isArray(x.id) && x.kwargs != null && typeof x.kwargs === "object"; +} +function _constructMessageFromParams(params) { + let type; + let rest; + if (isSerializedConstructor(params)) { + const className = params.id.at(-1); + if (className === "HumanMessage" || className === "HumanMessageChunk") { + type = "user"; + } else if (className === "AIMessage" || className === "AIMessageChunk") { + type = "assistant"; + } else if (className === "SystemMessage" || className === "SystemMessageChunk") { + type = "system"; + } else if (className === "FunctionMessage" || className === "FunctionMessageChunk") { + type = "function"; + } else if (className === "ToolMessage" || className === "ToolMessageChunk") { + type = "tool"; + } else { + type = "unknown"; + } + rest = params.kwargs; + } else { + const { type: extractedType, ...otherParams } = params; + type = extractedType; + rest = otherParams; + } + if (type === "human" || type === "user") { + return new HumanMessage(rest); + } else if (type === "ai" || type === "assistant") { + const { tool_calls: rawToolCalls, ...other } = rest; + if (!Array.isArray(rawToolCalls)) { + return new AIMessage(rest); + } + const tool_calls = rawToolCalls.map(_coerceToolCall); + return new AIMessage({ ...other, tool_calls }); + } else if (type === "system") { + return new SystemMessage(rest); + } else if (type === "developer") { + return new SystemMessage({ + ...rest, + additional_kwargs: { + ...rest.additional_kwargs, + __openai_role__: "developer" + } + }); + } else if (type === "tool" && "tool_call_id" in rest) { + return new ToolMessage({ + ...rest, + content: rest.content, + tool_call_id: rest.tool_call_id, + name: rest.name + }); + } else { + const error = addLangChainErrorFields(new Error(`Unable to coerce message from array: only human, AI, system, developer, or tool message coercion is currently supported. + +Received: ${JSON.stringify(params, null, 2)}`), "MESSAGE_COERCION_FAILURE"); + throw error; + } +} +function coerceMessageLikeToMessage(messageLike) { + if (typeof messageLike === "string") { + return new HumanMessage(messageLike); + } else if (isBaseMessage(messageLike)) { + return messageLike; + } + if (Array.isArray(messageLike)) { + const [type, content] = messageLike; + return _constructMessageFromParams({ type, content }); + } else if (_isMessageFieldWithRole(messageLike)) { + const { role: type, ...rest } = messageLike; + return _constructMessageFromParams({ ...rest, type }); + } else { + return _constructMessageFromParams(messageLike); + } +} +function getBufferString(messages, humanPrefix = "Human", aiPrefix = "AI") { + const string_messages = []; + for (const m of messages) { + let role; + if (m._getType() === "human") { + role = humanPrefix; + } else if (m._getType() === "ai") { + role = aiPrefix; + } else if (m._getType() === "system") { + role = "System"; + } else if (m._getType() === "function") { + role = "Function"; + } else if (m._getType() === "tool") { + role = "Tool"; + } else if (m._getType() === "generic") { + role = m.role; + } else { + throw new Error(`Got unsupported message type: ${m._getType()}`); + } + const nameStr = m.name ? `${m.name}, ` : ""; + const readableContent = typeof m.content === "string" ? m.content : JSON.stringify(m.content, null, 2); + string_messages.push(`${role}: ${nameStr}${readableContent}`); + } + return string_messages.join("\n"); +} +function mapV1MessageToStoredMessage(message) { + if (message.data !== void 0) { + return message; + } else { + const v1Message = message; + return { + type: v1Message.type, + data: { + content: v1Message.text, + role: v1Message.role, + name: void 0, + tool_call_id: void 0 + } + }; + } +} +function mapStoredMessageToChatMessage(message) { + const storedMessage = mapV1MessageToStoredMessage(message); + switch (storedMessage.type) { + case "human": + return new HumanMessage(storedMessage.data); + case "ai": + return new AIMessage(storedMessage.data); + case "system": + return new SystemMessage(storedMessage.data); + case "function": + if (storedMessage.data.name === void 0) { + throw new Error("Name must be defined for function messages"); + } + return new FunctionMessage(storedMessage.data); + case "tool": + if (storedMessage.data.tool_call_id === void 0) { + throw new Error("Tool call ID must be defined for tool messages"); + } + return new ToolMessage(storedMessage.data); + case "generic": { + if (storedMessage.data.role === void 0) { + throw new Error("Role must be defined for chat messages"); + } + return new ChatMessage(storedMessage.data); + } + default: + throw new Error(`Got unexpected type: ${storedMessage.type}`); + } +} +function mapStoredMessagesToChatMessages(messages) { + return messages.map(mapStoredMessageToChatMessage); +} +function mapChatMessagesToStoredMessages(messages) { + return messages.map((message) => message.toDict()); +} +function convertToChunk(message) { + const type = message._getType(); + if (type === "human") { + return new HumanMessageChunk({ ...message }); + } else if (type === "ai") { + let aiChunkFields = { + ...message + }; + if ("tool_calls" in aiChunkFields) { + aiChunkFields = { + ...aiChunkFields, + tool_call_chunks: aiChunkFields.tool_calls?.map((tc) => ({ + ...tc, + type: "tool_call_chunk", + index: void 0, + args: JSON.stringify(tc.args) + })) + }; + } + return new AIMessageChunk({ ...aiChunkFields }); + } else if (type === "system") { + return new SystemMessageChunk({ ...message }); + } else if (type === "function") { + return new FunctionMessageChunk({ ...message }); + } else if (ChatMessage.isInstance(message)) { + return new ChatMessageChunk({ ...message }); + } else { + throw new Error("Unknown message type."); + } +} +var init_utils2 = __esm({ + "node_modules/@langchain/core/dist/messages/utils.js"() { + init_errors(); + init_utils(); + init_ai(); + init_base(); + init_chat(); + init_function(); + init_human(); + init_system(); + init_tool(); + } +}); + +// node_modules/@langchain/core/dist/utils/env.js +var env_exports = {}; +__export(env_exports, { + getEnv: () => getEnv, + getEnvironmentVariable: () => getEnvironmentVariable, + getRuntimeEnvironment: () => getRuntimeEnvironment, + getRuntimeEnvironmentSync: () => getRuntimeEnvironmentSync, + isBrowser: () => isBrowser, + isDeno: () => isDeno, + isJsDom: () => isJsDom, + isNode: () => isNode, + isWebWorker: () => isWebWorker +}); +async function getRuntimeEnvironment() { + return getRuntimeEnvironmentSync(); +} +function getRuntimeEnvironmentSync() { + if (runtimeEnvironment === void 0) { + const env = getEnv(); + runtimeEnvironment = { + library: "langchain-js", + runtime: env + }; + } + return runtimeEnvironment; +} +function getEnvironmentVariable(name) { + try { + if (typeof process !== "undefined") { + return process.env?.[name]; + } else if (isDeno()) { + return Deno?.env.get(name); + } else { + return void 0; + } + } catch (e) { + return void 0; + } +} +var isBrowser, isWebWorker, isJsDom, isDeno, isNode, getEnv, runtimeEnvironment; +var init_env = __esm({ + "node_modules/@langchain/core/dist/utils/env.js"() { + isBrowser = () => typeof window !== "undefined" && typeof window.document !== "undefined"; + isWebWorker = () => typeof globalThis === "object" && globalThis.constructor && globalThis.constructor.name === "DedicatedWorkerGlobalScope"; + isJsDom = () => typeof window !== "undefined" && window.name === "nodejs" || typeof navigator !== "undefined" && navigator.userAgent.includes("jsdom"); + isDeno = () => typeof Deno !== "undefined"; + isNode = () => typeof process !== "undefined" && typeof process.versions !== "undefined" && typeof process.versions.node !== "undefined" && !isDeno(); + getEnv = () => { + let env; + if (isBrowser()) { + env = "browser"; + } else if (isNode()) { + env = "node"; + } else if (isWebWorker()) { + env = "webworker"; + } else if (isJsDom()) { + env = "jsdom"; + } else if (isDeno()) { + env = "deno"; + } else { + env = "other"; + } + return env; + }; + } +}); + +// node_modules/@langchain/core/dist/callbacks/base.js +var base_exports2 = {}; +__export(base_exports2, { + BaseCallbackHandler: () => BaseCallbackHandler, + callbackHandlerPrefersStreaming: () => callbackHandlerPrefersStreaming, + isBaseCallbackHandler: () => isBaseCallbackHandler +}); +function callbackHandlerPrefersStreaming(x) { + return "lc_prefer_streaming" in x && x.lc_prefer_streaming; +} +var BaseCallbackHandlerMethodsClass, BaseCallbackHandler, isBaseCallbackHandler; +var init_base2 = __esm({ + "node_modules/@langchain/core/dist/callbacks/base.js"() { + init_esm_browser(); + init_serializable(); + init_env(); + BaseCallbackHandlerMethodsClass = class { + }; + BaseCallbackHandler = class _BaseCallbackHandler extends BaseCallbackHandlerMethodsClass { + get lc_namespace() { + return ["langchain_core", "callbacks", this.name]; + } + get lc_secrets() { + return void 0; + } + get lc_attributes() { + return void 0; + } + get lc_aliases() { + return void 0; + } + get lc_serializable_keys() { + return void 0; + } + /** + * The name of the serializable. Override to provide an alias or + * to preserve the serialized module name in minified environments. + * + * Implemented as a static method to support loading logic. + */ + static lc_name() { + return this.name; + } + /** + * The final serialized identifier for the module. + */ + get lc_id() { + return [ + ...this.lc_namespace, + get_lc_unique_name(this.constructor) + ]; + } + constructor(input) { + super(); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "lc_kwargs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "ignoreLLM", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "ignoreChain", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "ignoreAgent", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "ignoreRetriever", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "ignoreCustomEvent", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "raiseError", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "awaitHandlers", { + enumerable: true, + configurable: true, + writable: true, + value: getEnvironmentVariable("LANGCHAIN_CALLBACKS_BACKGROUND") === "false" + }); + this.lc_kwargs = input || {}; + if (input) { + this.ignoreLLM = input.ignoreLLM ?? this.ignoreLLM; + this.ignoreChain = input.ignoreChain ?? this.ignoreChain; + this.ignoreAgent = input.ignoreAgent ?? this.ignoreAgent; + this.ignoreRetriever = input.ignoreRetriever ?? this.ignoreRetriever; + this.ignoreCustomEvent = input.ignoreCustomEvent ?? this.ignoreCustomEvent; + this.raiseError = input.raiseError ?? this.raiseError; + this.awaitHandlers = this.raiseError || (input._awaitHandler ?? this.awaitHandlers); + } + } + copy() { + return new this.constructor(this); + } + toJSON() { + return Serializable.prototype.toJSON.call(this); + } + toJSONNotImplemented() { + return Serializable.prototype.toJSONNotImplemented.call(this); + } + static fromMethods(methods) { + class Handler extends _BaseCallbackHandler { + constructor() { + super(); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: v4_default() + }); + Object.assign(this, methods); + } + } + return new Handler(); + } + }; + isBaseCallbackHandler = (x) => { + const callbackHandler = x; + return callbackHandler !== void 0 && typeof callbackHandler.copy === "function" && typeof callbackHandler.name === "string" && typeof callbackHandler.awaitHandlers === "boolean"; + }; + } +}); + +// node_modules/ansi-styles/index.js +var require_ansi_styles = __commonJS({ + "node_modules/ansi-styles/index.js"(exports, module) { + "use strict"; + var ANSI_BACKGROUND_OFFSET = 10; + var wrapAnsi256 = (offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`; + var wrapAnsi16m = (offset = 0) => (red, green, blue) => `\x1B[${38 + offset};2;${red};${green};${blue}m`; + function assembleStyles() { + const codes = /* @__PURE__ */ new Map(); + const styles2 = { + modifier: { + reset: [0, 0], + // 21 isn't widely supported and 22 does the same thing + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + overline: [53, 55], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29] + }, + color: { + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + // Bright color + blackBright: [90, 39], + redBright: [91, 39], + greenBright: [92, 39], + yellowBright: [93, 39], + blueBright: [94, 39], + magentaBright: [95, 39], + cyanBright: [96, 39], + whiteBright: [97, 39] + }, + bgColor: { + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], + // Bright color + bgBlackBright: [100, 49], + bgRedBright: [101, 49], + bgGreenBright: [102, 49], + bgYellowBright: [103, 49], + bgBlueBright: [104, 49], + bgMagentaBright: [105, 49], + bgCyanBright: [106, 49], + bgWhiteBright: [107, 49] + } + }; + styles2.color.gray = styles2.color.blackBright; + styles2.bgColor.bgGray = styles2.bgColor.bgBlackBright; + styles2.color.grey = styles2.color.blackBright; + styles2.bgColor.bgGrey = styles2.bgColor.bgBlackBright; + for (const [groupName, group] of Object.entries(styles2)) { + for (const [styleName, style] of Object.entries(group)) { + styles2[styleName] = { + open: `\x1B[${style[0]}m`, + close: `\x1B[${style[1]}m` + }; + group[styleName] = styles2[styleName]; + codes.set(style[0], style[1]); + } + Object.defineProperty(styles2, groupName, { + value: group, + enumerable: false + }); + } + Object.defineProperty(styles2, "codes", { + value: codes, + enumerable: false + }); + styles2.color.close = "\x1B[39m"; + styles2.bgColor.close = "\x1B[49m"; + styles2.color.ansi256 = wrapAnsi256(); + styles2.color.ansi16m = wrapAnsi16m(); + styles2.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET); + styles2.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET); + Object.defineProperties(styles2, { + rgbToAnsi256: { + value: (red, green, blue) => { + if (red === green && green === blue) { + if (red < 8) { + return 16; + } + if (red > 248) { + return 231; + } + return Math.round((red - 8) / 247 * 24) + 232; + } + return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5); + }, + enumerable: false + }, + hexToRgb: { + value: (hex) => { + const matches = /(?[a-f\d]{6}|[a-f\d]{3})/i.exec(hex.toString(16)); + if (!matches) { + return [0, 0, 0]; + } + let { colorString } = matches.groups; + if (colorString.length === 3) { + colorString = colorString.split("").map((character) => character + character).join(""); + } + const integer = Number.parseInt(colorString, 16); + return [ + integer >> 16 & 255, + integer >> 8 & 255, + integer & 255 + ]; + }, + enumerable: false + }, + hexToAnsi256: { + value: (hex) => styles2.rgbToAnsi256(...styles2.hexToRgb(hex)), + enumerable: false + } + }); + return styles2; + } + Object.defineProperty(module, "exports", { + enumerable: true, + get: assembleStyles + }); + } +}); + +// node_modules/langsmith/dist/experimental/otel/constants.js +var GEN_AI_OPERATION_NAME, GEN_AI_SYSTEM, GEN_AI_REQUEST_MODEL, GEN_AI_RESPONSE_MODEL, GEN_AI_USAGE_INPUT_TOKENS, GEN_AI_USAGE_OUTPUT_TOKENS, GEN_AI_USAGE_TOTAL_TOKENS, GEN_AI_REQUEST_MAX_TOKENS, GEN_AI_REQUEST_TEMPERATURE, GEN_AI_REQUEST_TOP_P, GEN_AI_REQUEST_FREQUENCY_PENALTY, GEN_AI_REQUEST_PRESENCE_PENALTY, GEN_AI_RESPONSE_FINISH_REASONS, GENAI_PROMPT, GENAI_COMPLETION, GEN_AI_REQUEST_EXTRA_QUERY, GEN_AI_REQUEST_EXTRA_BODY, GEN_AI_SERIALIZED_NAME, GEN_AI_SERIALIZED_SIGNATURE, GEN_AI_SERIALIZED_DOC, GEN_AI_RESPONSE_ID, GEN_AI_RESPONSE_SERVICE_TIER, GEN_AI_RESPONSE_SYSTEM_FINGERPRINT, GEN_AI_USAGE_INPUT_TOKEN_DETAILS, GEN_AI_USAGE_OUTPUT_TOKEN_DETAILS, LANGSMITH_SESSION_ID, LANGSMITH_SESSION_NAME, LANGSMITH_RUN_TYPE, LANGSMITH_NAME, LANGSMITH_METADATA, LANGSMITH_TAGS, LANGSMITH_REQUEST_STREAMING, LANGSMITH_REQUEST_HEADERS; +var init_constants = __esm({ + "node_modules/langsmith/dist/experimental/otel/constants.js"() { + GEN_AI_OPERATION_NAME = "gen_ai.operation.name"; + GEN_AI_SYSTEM = "gen_ai.system"; + GEN_AI_REQUEST_MODEL = "gen_ai.request.model"; + GEN_AI_RESPONSE_MODEL = "gen_ai.response.model"; + GEN_AI_USAGE_INPUT_TOKENS = "gen_ai.usage.input_tokens"; + GEN_AI_USAGE_OUTPUT_TOKENS = "gen_ai.usage.output_tokens"; + GEN_AI_USAGE_TOTAL_TOKENS = "gen_ai.usage.total_tokens"; + GEN_AI_REQUEST_MAX_TOKENS = "gen_ai.request.max_tokens"; + GEN_AI_REQUEST_TEMPERATURE = "gen_ai.request.temperature"; + GEN_AI_REQUEST_TOP_P = "gen_ai.request.top_p"; + GEN_AI_REQUEST_FREQUENCY_PENALTY = "gen_ai.request.frequency_penalty"; + GEN_AI_REQUEST_PRESENCE_PENALTY = "gen_ai.request.presence_penalty"; + GEN_AI_RESPONSE_FINISH_REASONS = "gen_ai.response.finish_reasons"; + GENAI_PROMPT = "gen_ai.prompt"; + GENAI_COMPLETION = "gen_ai.completion"; + GEN_AI_REQUEST_EXTRA_QUERY = "gen_ai.request.extra_query"; + GEN_AI_REQUEST_EXTRA_BODY = "gen_ai.request.extra_body"; + GEN_AI_SERIALIZED_NAME = "gen_ai.serialized.name"; + GEN_AI_SERIALIZED_SIGNATURE = "gen_ai.serialized.signature"; + GEN_AI_SERIALIZED_DOC = "gen_ai.serialized.doc"; + GEN_AI_RESPONSE_ID = "gen_ai.response.id"; + GEN_AI_RESPONSE_SERVICE_TIER = "gen_ai.response.service_tier"; + GEN_AI_RESPONSE_SYSTEM_FINGERPRINT = "gen_ai.response.system_fingerprint"; + GEN_AI_USAGE_INPUT_TOKEN_DETAILS = "gen_ai.usage.input_token_details"; + GEN_AI_USAGE_OUTPUT_TOKEN_DETAILS = "gen_ai.usage.output_token_details"; + LANGSMITH_SESSION_ID = "langsmith.trace.session_id"; + LANGSMITH_SESSION_NAME = "langsmith.trace.session_name"; + LANGSMITH_RUN_TYPE = "langsmith.span.kind"; + LANGSMITH_NAME = "langsmith.trace.name"; + LANGSMITH_METADATA = "langsmith.metadata"; + LANGSMITH_TAGS = "langsmith.span.tags"; + LANGSMITH_REQUEST_STREAMING = "langsmith.request.streaming"; + LANGSMITH_REQUEST_HEADERS = "langsmith.request.headers"; + } +}); + +// node_modules/langsmith/dist/singletons/fetch.js +var DEFAULT_FETCH_IMPLEMENTATION, LANGSMITH_FETCH_IMPLEMENTATION_KEY, _globalFetchImplementationIsNodeFetch, _getFetchImplementation; +var init_fetch = __esm({ + "node_modules/langsmith/dist/singletons/fetch.js"() { + init_env2(); + DEFAULT_FETCH_IMPLEMENTATION = (...args) => fetch(...args); + LANGSMITH_FETCH_IMPLEMENTATION_KEY = Symbol.for("ls:fetch_implementation"); + _globalFetchImplementationIsNodeFetch = () => { + const fetchImpl = globalThis[LANGSMITH_FETCH_IMPLEMENTATION_KEY]; + if (!fetchImpl) + return false; + return typeof fetchImpl === "function" && "Headers" in fetchImpl && "Request" in fetchImpl && "Response" in fetchImpl; + }; + _getFetchImplementation = (debug) => { + return async (...args) => { + if (debug || getLangSmithEnvironmentVariable("DEBUG") === "true") { + const [url, options] = args; + console.log(`\u2192 ${options?.method || "GET"} ${url}`); + } + const res = await (globalThis[LANGSMITH_FETCH_IMPLEMENTATION_KEY] ?? DEFAULT_FETCH_IMPLEMENTATION)(...args); + if (debug || getLangSmithEnvironmentVariable("DEBUG") === "true") { + console.log(`\u2190 ${res.status} ${res.statusText} ${res.url}`); + } + return res; + }; + }; + } +}); + +// node_modules/langsmith/dist/utils/project.js +var getDefaultProjectName; +var init_project = __esm({ + "node_modules/langsmith/dist/utils/project.js"() { + init_env2(); + getDefaultProjectName = () => { + return getLangSmithEnvironmentVariable("PROJECT") ?? getEnvironmentVariable2("LANGCHAIN_SESSION") ?? // TODO: Deprecate + "default"; + }; + } +}); + +// node_modules/langsmith/dist/index.js +var __version__; +var init_dist = __esm({ + "node_modules/langsmith/dist/index.js"() { + init_client(); + init_run_trees(); + init_fetch(); + init_project(); + __version__ = "0.3.62"; + } +}); + +// node_modules/langsmith/dist/utils/env.js +function getRuntimeEnvironment2() { + if (runtimeEnvironment2 === void 0) { + const env = getEnv2(); + const releaseEnv = getShas(); + runtimeEnvironment2 = { + library: "langsmith", + runtime: env, + sdk: "langsmith-js", + sdk_version: __version__, + ...releaseEnv + }; + } + return runtimeEnvironment2; +} +function getLangChainEnvVarsMetadata() { + const allEnvVars = getEnvironmentVariables() || {}; + const envVars = {}; + const excluded = [ + "LANGCHAIN_API_KEY", + "LANGCHAIN_ENDPOINT", + "LANGCHAIN_TRACING_V2", + "LANGCHAIN_PROJECT", + "LANGCHAIN_SESSION", + "LANGSMITH_API_KEY", + "LANGSMITH_ENDPOINT", + "LANGSMITH_TRACING_V2", + "LANGSMITH_PROJECT", + "LANGSMITH_SESSION" + ]; + for (const [key, value] of Object.entries(allEnvVars)) { + if ((key.startsWith("LANGCHAIN_") || key.startsWith("LANGSMITH_")) && typeof value === "string" && !excluded.includes(key) && !key.toLowerCase().includes("key") && !key.toLowerCase().includes("secret") && !key.toLowerCase().includes("token")) { + if (key === "LANGCHAIN_REVISION_ID") { + envVars["revision_id"] = value; + } else { + envVars[key] = value; + } + } + } + return envVars; +} +function getEnvironmentVariables() { + try { + if (typeof process !== "undefined" && process.env) { + return Object.entries(process.env).reduce((acc, [key, value]) => { + acc[key] = String(value); + return acc; + }, {}); + } + return void 0; + } catch (e) { + return void 0; + } +} +function getEnvironmentVariable2(name) { + try { + return typeof process !== "undefined" ? ( + // eslint-disable-next-line no-process-env + process.env?.[name] + ) : void 0; + } catch (e) { + return void 0; + } +} +function getLangSmithEnvironmentVariable(name) { + return getEnvironmentVariable2(`LANGSMITH_${name}`) || getEnvironmentVariable2(`LANGCHAIN_${name}`); +} +function getShas() { + if (cachedCommitSHAs !== void 0) { + return cachedCommitSHAs; + } + const common_release_envs = [ + "VERCEL_GIT_COMMIT_SHA", + "NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA", + "COMMIT_REF", + "RENDER_GIT_COMMIT", + "CI_COMMIT_SHA", + "CIRCLE_SHA1", + "CF_PAGES_COMMIT_SHA", + "REACT_APP_GIT_SHA", + "SOURCE_VERSION", + "GITHUB_SHA", + "TRAVIS_COMMIT", + "GIT_COMMIT", + "BUILD_VCS_NUMBER", + "bamboo_planRepository_revision", + "Build.SourceVersion", + "BITBUCKET_COMMIT", + "DRONE_COMMIT_SHA", + "SEMAPHORE_GIT_SHA", + "BUILDKITE_COMMIT" + ]; + const shas = {}; + for (const env of common_release_envs) { + const envVar = getEnvironmentVariable2(env); + if (envVar !== void 0) { + shas[env] = envVar; + } + } + cachedCommitSHAs = shas; + return shas; +} +function getOtelEnabled() { + return getEnvironmentVariable2("OTEL_ENABLED") === "true" || getLangSmithEnvironmentVariable("OTEL_ENABLED") === "true"; +} +var globalEnv, isBrowser2, isWebWorker2, isJsDom2, isDeno2, isNode2, getEnv2, runtimeEnvironment2, cachedCommitSHAs; +var init_env2 = __esm({ + "node_modules/langsmith/dist/utils/env.js"() { + init_dist(); + isBrowser2 = () => typeof window !== "undefined" && typeof window.document !== "undefined"; + isWebWorker2 = () => typeof globalThis === "object" && globalThis.constructor && globalThis.constructor.name === "DedicatedWorkerGlobalScope"; + isJsDom2 = () => typeof window !== "undefined" && window.name === "nodejs" || typeof navigator !== "undefined" && navigator.userAgent.includes("jsdom"); + isDeno2 = () => typeof Deno !== "undefined"; + isNode2 = () => typeof process !== "undefined" && typeof process.versions !== "undefined" && typeof process.versions.node !== "undefined" && !isDeno2(); + getEnv2 = () => { + if (globalEnv) { + return globalEnv; + } + if (isBrowser2()) { + globalEnv = "browser"; + } else if (isNode2()) { + globalEnv = "node"; + } else if (isWebWorker2()) { + globalEnv = "webworker"; + } else if (isJsDom2()) { + globalEnv = "jsdom"; + } else if (isDeno2()) { + globalEnv = "deno"; + } else { + globalEnv = "other"; + } + return globalEnv; + }; + } +}); + +// node_modules/langsmith/dist/singletons/otel.js +function getOTELTrace() { + return OTELProviderSingleton.getTraceInstance(); +} +function getOTELContext() { + return OTELProviderSingleton.getContextInstance(); +} +function getDefaultOTLPTracerComponents() { + return OTELProviderSingleton.getDefaultOTLPTracerComponents(); +} +var MockTracer, MockOTELTrace, MockOTELContext, OTEL_TRACE_KEY, OTEL_CONTEXT_KEY, OTEL_GET_DEFAULT_OTLP_TRACER_PROVIDER_KEY, mockOTELTrace, mockOTELContext, OTELProvider, OTELProviderSingleton; +var init_otel = __esm({ + "node_modules/langsmith/dist/singletons/otel.js"() { + init_env2(); + MockTracer = class { + constructor() { + Object.defineProperty(this, "hasWarned", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + } + startActiveSpan(_name, ...args) { + if (!this.hasWarned && getOtelEnabled()) { + console.warn('You have enabled OTEL export via the `OTEL_ENABLED` or `LANGSMITH_OTEL_ENABLED` environment variable, but have not initialized the required OTEL instances. Please add:\n```\nimport { initializeOTEL } from "langsmith/experimental/otel/setup";\ninitializeOTEL();\n```\nat the beginning of your code.'); + this.hasWarned = true; + } + let fn; + if (args.length === 1 && typeof args[0] === "function") { + fn = args[0]; + } else if (args.length === 2 && typeof args[1] === "function") { + fn = args[1]; + } else if (args.length === 3 && typeof args[2] === "function") { + fn = args[2]; + } + if (typeof fn === "function") { + return fn(); + } + return void 0; + } + }; + MockOTELTrace = class { + constructor() { + Object.defineProperty(this, "mockTracer", { + enumerable: true, + configurable: true, + writable: true, + value: new MockTracer() + }); + } + getTracer(_name, _version) { + return this.mockTracer; + } + getActiveSpan() { + return void 0; + } + setSpan(context, _span) { + return context; + } + getSpan(_context) { + return void 0; + } + setSpanContext(context, _spanContext) { + return context; + } + getTracerProvider() { + return void 0; + } + setGlobalTracerProvider(_tracerProvider) { + return false; + } + }; + MockOTELContext = class { + active() { + return {}; + } + with(_context, fn) { + return fn(); + } + }; + OTEL_TRACE_KEY = Symbol.for("ls:otel_trace"); + OTEL_CONTEXT_KEY = Symbol.for("ls:otel_context"); + OTEL_GET_DEFAULT_OTLP_TRACER_PROVIDER_KEY = Symbol.for("ls:otel_get_default_otlp_tracer_provider"); + mockOTELTrace = new MockOTELTrace(); + mockOTELContext = new MockOTELContext(); + OTELProvider = class { + getTraceInstance() { + return globalThis[OTEL_TRACE_KEY] ?? mockOTELTrace; + } + getContextInstance() { + return globalThis[OTEL_CONTEXT_KEY] ?? mockOTELContext; + } + initializeGlobalInstances(otel) { + if (globalThis[OTEL_TRACE_KEY] === void 0) { + globalThis[OTEL_TRACE_KEY] = otel.trace; + } + if (globalThis[OTEL_CONTEXT_KEY] === void 0) { + globalThis[OTEL_CONTEXT_KEY] = otel.context; + } + } + setDefaultOTLPTracerComponents(components) { + globalThis[OTEL_GET_DEFAULT_OTLP_TRACER_PROVIDER_KEY] = components; + } + getDefaultOTLPTracerComponents() { + return globalThis[OTEL_GET_DEFAULT_OTLP_TRACER_PROVIDER_KEY] ?? void 0; + } + }; + OTELProviderSingleton = new OTELProvider(); + } +}); + +// node_modules/langsmith/dist/experimental/otel/translator.js +function getOperationName(runType) { + return WELL_KNOWN_OPERATION_NAMES[runType] || runType; +} +var WELL_KNOWN_OPERATION_NAMES, LangSmithToOTELTranslator; +var init_translator = __esm({ + "node_modules/langsmith/dist/experimental/otel/translator.js"() { + init_constants(); + init_otel(); + WELL_KNOWN_OPERATION_NAMES = { + llm: "chat", + tool: "execute_tool", + retriever: "embeddings", + embedding: "embeddings", + prompt: "chat" + }; + LangSmithToOTELTranslator = class { + constructor() { + Object.defineProperty(this, "spans", { + enumerable: true, + configurable: true, + writable: true, + value: /* @__PURE__ */ new Map() + }); + } + exportBatch(operations, otelContextMap) { + for (const op of operations) { + try { + if (!op.run) { + continue; + } + if (op.operation === "post") { + const span = this.createSpanForRun(op, op.run, otelContextMap.get(op.id)); + if (span && !op.run.end_time) { + this.spans.set(op.id, span); + } + } else { + this.updateSpanForRun(op, op.run); + } + } catch (e) { + console.error(`Error processing operation ${op.id}:`, e); + } + } + } + createSpanForRun(op, runInfo, otelContext) { + const activeSpan = otelContext && getOTELTrace().getSpan(otelContext); + if (!activeSpan) { + return; + } + try { + return this.finishSpanSetup(activeSpan, runInfo, op); + } catch (e) { + console.error(`Failed to create span for run ${op.id}:`, e); + return void 0; + } + } + finishSpanSetup(span, runInfo, op) { + this.setSpanAttributes(span, runInfo, op); + if (runInfo.error) { + span.setStatus({ code: 2 }); + span.recordException(new Error(runInfo.error)); + } else { + span.setStatus({ code: 1 }); + } + if (runInfo.end_time) { + span.end(new Date(runInfo.end_time)); + } + return span; + } + updateSpanForRun(op, runInfo) { + try { + const span = this.spans.get(op.id); + if (!span) { + console.debug(`No span found for run ${op.id} during update`); + return; + } + this.setSpanAttributes(span, runInfo, op); + if (runInfo.error) { + span.setStatus({ code: 2 }); + span.recordException(new Error(runInfo.error)); + } else { + span.setStatus({ code: 1 }); + } + const endTime = runInfo.end_time; + if (endTime) { + span.end(new Date(endTime)); + this.spans.delete(op.id); + } + } catch (e) { + console.error(`Failed to update span for run ${op.id}:`, e); + } + } + extractModelName(runInfo) { + if (runInfo.extra?.metadata) { + const metadata = runInfo.extra.metadata; + if (metadata.ls_model_name) { + return metadata.ls_model_name; + } + if (metadata.invocation_params) { + const invocationParams = metadata.invocation_params; + if (invocationParams.model) { + return invocationParams.model; + } else if (invocationParams.model_name) { + return invocationParams.model_name; + } + } + } + return; + } + setSpanAttributes(span, runInfo, op) { + if ("run_type" in runInfo && runInfo.run_type) { + span.setAttribute(LANGSMITH_RUN_TYPE, runInfo.run_type); + const operationName = getOperationName(runInfo.run_type || "chain"); + span.setAttribute(GEN_AI_OPERATION_NAME, operationName); + } + if ("name" in runInfo && runInfo.name) { + span.setAttribute(LANGSMITH_NAME, runInfo.name); + } + if ("session_id" in runInfo && runInfo.session_id) { + span.setAttribute(LANGSMITH_SESSION_ID, runInfo.session_id); + } + if ("session_name" in runInfo && runInfo.session_name) { + span.setAttribute(LANGSMITH_SESSION_NAME, runInfo.session_name); + } + this.setGenAiSystem(span, runInfo); + const modelName = this.extractModelName(runInfo); + if (modelName) { + span.setAttribute(GEN_AI_REQUEST_MODEL, modelName); + } + if ("prompt_tokens" in runInfo && typeof runInfo.prompt_tokens === "number") { + span.setAttribute(GEN_AI_USAGE_INPUT_TOKENS, runInfo.prompt_tokens); + } + if ("completion_tokens" in runInfo && typeof runInfo.completion_tokens === "number") { + span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS, runInfo.completion_tokens); + } + if ("total_tokens" in runInfo && typeof runInfo.total_tokens === "number") { + span.setAttribute(GEN_AI_USAGE_TOTAL_TOKENS, runInfo.total_tokens); + } + this.setInvocationParameters(span, runInfo); + const metadata = runInfo.extra?.metadata || {}; + for (const [key, value] of Object.entries(metadata)) { + if (value !== null && value !== void 0) { + span.setAttribute(`${LANGSMITH_METADATA}.${key}`, String(value)); + } + } + const tags = runInfo.tags; + if (tags && Array.isArray(tags)) { + span.setAttribute(LANGSMITH_TAGS, tags.join(", ")); + } else if (tags) { + span.setAttribute(LANGSMITH_TAGS, String(tags)); + } + if ("serialized" in runInfo && typeof runInfo.serialized === "object") { + const serialized = runInfo.serialized; + if (serialized.name) { + span.setAttribute(GEN_AI_SERIALIZED_NAME, String(serialized.name)); + } + if (serialized.signature) { + span.setAttribute(GEN_AI_SERIALIZED_SIGNATURE, String(serialized.signature)); + } + if (serialized.doc) { + span.setAttribute(GEN_AI_SERIALIZED_DOC, String(serialized.doc)); + } + } + this.setIOAttributes(span, op); + } + setGenAiSystem(span, runInfo) { + let system = "langchain"; + const modelName = this.extractModelName(runInfo); + if (modelName) { + const modelLower = modelName.toLowerCase(); + if (modelLower.includes("anthropic") || modelLower.startsWith("claude")) { + system = "anthropic"; + } else if (modelLower.includes("bedrock")) { + system = "aws.bedrock"; + } else if (modelLower.includes("azure") && modelLower.includes("openai")) { + system = "az.ai.openai"; + } else if (modelLower.includes("azure") && modelLower.includes("inference")) { + system = "az.ai.inference"; + } else if (modelLower.includes("cohere")) { + system = "cohere"; + } else if (modelLower.includes("deepseek")) { + system = "deepseek"; + } else if (modelLower.includes("gemini")) { + system = "gemini"; + } else if (modelLower.includes("groq")) { + system = "groq"; + } else if (modelLower.includes("watson") || modelLower.includes("ibm")) { + system = "ibm.watsonx.ai"; + } else if (modelLower.includes("mistral")) { + system = "mistral_ai"; + } else if (modelLower.includes("gpt") || modelLower.includes("openai")) { + system = "openai"; + } else if (modelLower.includes("perplexity") || modelLower.includes("sonar")) { + system = "perplexity"; + } else if (modelLower.includes("vertex")) { + system = "vertex_ai"; + } else if (modelLower.includes("xai") || modelLower.includes("grok")) { + system = "xai"; + } + } + span.setAttribute(GEN_AI_SYSTEM, system); + } + setInvocationParameters(span, runInfo) { + if (!runInfo.extra?.metadata?.invocation_params) { + return; + } + const invocationParams = runInfo.extra.metadata.invocation_params; + if (invocationParams.max_tokens !== void 0) { + span.setAttribute(GEN_AI_REQUEST_MAX_TOKENS, invocationParams.max_tokens); + } + if (invocationParams.temperature !== void 0) { + span.setAttribute(GEN_AI_REQUEST_TEMPERATURE, invocationParams.temperature); + } + if (invocationParams.top_p !== void 0) { + span.setAttribute(GEN_AI_REQUEST_TOP_P, invocationParams.top_p); + } + if (invocationParams.frequency_penalty !== void 0) { + span.setAttribute(GEN_AI_REQUEST_FREQUENCY_PENALTY, invocationParams.frequency_penalty); + } + if (invocationParams.presence_penalty !== void 0) { + span.setAttribute(GEN_AI_REQUEST_PRESENCE_PENALTY, invocationParams.presence_penalty); + } + } + setIOAttributes(span, op) { + if (op.run.inputs) { + try { + const inputs = op.run.inputs; + if (typeof inputs === "object" && inputs !== null) { + if (inputs.model && Array.isArray(inputs.messages)) { + span.setAttribute(GEN_AI_REQUEST_MODEL, inputs.model); + } + if (inputs.stream !== void 0) { + span.setAttribute(LANGSMITH_REQUEST_STREAMING, inputs.stream); + } + if (inputs.extra_headers) { + span.setAttribute(LANGSMITH_REQUEST_HEADERS, JSON.stringify(inputs.extra_headers)); + } + if (inputs.extra_query) { + span.setAttribute(GEN_AI_REQUEST_EXTRA_QUERY, JSON.stringify(inputs.extra_query)); + } + if (inputs.extra_body) { + span.setAttribute(GEN_AI_REQUEST_EXTRA_BODY, JSON.stringify(inputs.extra_body)); + } + } + span.setAttribute(GENAI_PROMPT, JSON.stringify(inputs)); + } catch (e) { + console.debug(`Failed to process inputs for run ${op.id}`, e); + } + } + if (op.run.outputs) { + try { + const outputs = op.run.outputs; + const tokenUsage = this.getUnifiedRunTokens(outputs); + if (tokenUsage) { + span.setAttribute(GEN_AI_USAGE_INPUT_TOKENS, tokenUsage[0]); + span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS, tokenUsage[1]); + span.setAttribute(GEN_AI_USAGE_TOTAL_TOKENS, tokenUsage[0] + tokenUsage[1]); + } + if (outputs && typeof outputs === "object") { + if (outputs.model) { + span.setAttribute(GEN_AI_RESPONSE_MODEL, String(outputs.model)); + } + if (outputs.id) { + span.setAttribute(GEN_AI_RESPONSE_ID, outputs.id); + } + if (outputs.choices && Array.isArray(outputs.choices)) { + const finishReasons = outputs.choices.map((choice) => choice.finish_reason).filter((reason) => reason).map(String); + if (finishReasons.length > 0) { + span.setAttribute(GEN_AI_RESPONSE_FINISH_REASONS, finishReasons.join(", ")); + } + } + if (outputs.service_tier) { + span.setAttribute(GEN_AI_RESPONSE_SERVICE_TIER, outputs.service_tier); + } + if (outputs.system_fingerprint) { + span.setAttribute(GEN_AI_RESPONSE_SYSTEM_FINGERPRINT, outputs.system_fingerprint); + } + if (outputs.usage_metadata && typeof outputs.usage_metadata === "object") { + const usageMetadata = outputs.usage_metadata; + if (usageMetadata.input_token_details) { + span.setAttribute(GEN_AI_USAGE_INPUT_TOKEN_DETAILS, JSON.stringify(usageMetadata.input_token_details)); + } + if (usageMetadata.output_token_details) { + span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKEN_DETAILS, JSON.stringify(usageMetadata.output_token_details)); + } + } + } + span.setAttribute(GENAI_COMPLETION, JSON.stringify(outputs)); + } catch (e) { + console.debug(`Failed to process outputs for run ${op.id}`, e); + } + } + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + getUnifiedRunTokens(outputs) { + if (!outputs) { + return null; + } + let tokenUsage = this.extractUnifiedRunTokens(outputs.usage_metadata); + if (tokenUsage) { + return tokenUsage; + } + const keys = Object.keys(outputs); + for (const key of keys) { + const haystack = outputs[key]; + if (!haystack || typeof haystack !== "object") { + continue; + } + tokenUsage = this.extractUnifiedRunTokens(haystack.usage_metadata); + if (tokenUsage) { + return tokenUsage; + } + if (haystack.lc === 1 && haystack.kwargs && typeof haystack.kwargs === "object") { + tokenUsage = this.extractUnifiedRunTokens(haystack.kwargs.usage_metadata); + if (tokenUsage) { + return tokenUsage; + } + } + } + const generations = outputs.generations || []; + if (!Array.isArray(generations)) { + return null; + } + const flatGenerations = Array.isArray(generations[0]) ? generations.flat() : generations; + for (const generation of flatGenerations) { + if (typeof generation === "object" && generation.message && typeof generation.message === "object" && generation.message.kwargs && typeof generation.message.kwargs === "object") { + tokenUsage = this.extractUnifiedRunTokens(generation.message.kwargs.usage_metadata); + if (tokenUsage) { + return tokenUsage; + } + } + } + return null; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + extractUnifiedRunTokens(outputs) { + if (!outputs || typeof outputs !== "object") { + return null; + } + if (typeof outputs.input_tokens !== "number" || typeof outputs.output_tokens !== "number") { + return null; + } + return [outputs.input_tokens, outputs.output_tokens]; + } + }; + } +}); + +// node_modules/retry/lib/retry_operation.js +var require_retry_operation = __commonJS({ + "node_modules/retry/lib/retry_operation.js"(exports, module) { + function RetryOperation(timeouts, options) { + if (typeof options === "boolean") { + options = { forever: options }; + } + this._originalTimeouts = JSON.parse(JSON.stringify(timeouts)); + this._timeouts = timeouts; + this._options = options || {}; + this._maxRetryTime = options && options.maxRetryTime || Infinity; + this._fn = null; + this._errors = []; + this._attempts = 1; + this._operationTimeout = null; + this._operationTimeoutCb = null; + this._timeout = null; + this._operationStart = null; + this._timer = null; + if (this._options.forever) { + this._cachedTimeouts = this._timeouts.slice(0); + } + } + module.exports = RetryOperation; + RetryOperation.prototype.reset = function() { + this._attempts = 1; + this._timeouts = this._originalTimeouts.slice(0); + }; + RetryOperation.prototype.stop = function() { + if (this._timeout) { + clearTimeout(this._timeout); + } + if (this._timer) { + clearTimeout(this._timer); + } + this._timeouts = []; + this._cachedTimeouts = null; + }; + RetryOperation.prototype.retry = function(err) { + if (this._timeout) { + clearTimeout(this._timeout); + } + if (!err) { + return false; + } + var currentTime = (/* @__PURE__ */ new Date()).getTime(); + if (err && currentTime - this._operationStart >= this._maxRetryTime) { + this._errors.push(err); + this._errors.unshift(new Error("RetryOperation timeout occurred")); + return false; + } + this._errors.push(err); + var timeout = this._timeouts.shift(); + if (timeout === void 0) { + if (this._cachedTimeouts) { + this._errors.splice(0, this._errors.length - 1); + timeout = this._cachedTimeouts.slice(-1); + } else { + return false; + } + } + var self2 = this; + this._timer = setTimeout(function() { + self2._attempts++; + if (self2._operationTimeoutCb) { + self2._timeout = setTimeout(function() { + self2._operationTimeoutCb(self2._attempts); + }, self2._operationTimeout); + if (self2._options.unref) { + self2._timeout.unref(); + } + } + self2._fn(self2._attempts); + }, timeout); + if (this._options.unref) { + this._timer.unref(); + } + return true; + }; + RetryOperation.prototype.attempt = function(fn, timeoutOps) { + this._fn = fn; + if (timeoutOps) { + if (timeoutOps.timeout) { + this._operationTimeout = timeoutOps.timeout; + } + if (timeoutOps.cb) { + this._operationTimeoutCb = timeoutOps.cb; + } + } + var self2 = this; + if (this._operationTimeoutCb) { + this._timeout = setTimeout(function() { + self2._operationTimeoutCb(); + }, self2._operationTimeout); + } + this._operationStart = (/* @__PURE__ */ new Date()).getTime(); + this._fn(this._attempts); + }; + RetryOperation.prototype.try = function(fn) { + console.log("Using RetryOperation.try() is deprecated"); + this.attempt(fn); + }; + RetryOperation.prototype.start = function(fn) { + console.log("Using RetryOperation.start() is deprecated"); + this.attempt(fn); + }; + RetryOperation.prototype.start = RetryOperation.prototype.try; + RetryOperation.prototype.errors = function() { + return this._errors; + }; + RetryOperation.prototype.attempts = function() { + return this._attempts; + }; + RetryOperation.prototype.mainError = function() { + if (this._errors.length === 0) { + return null; + } + var counts = {}; + var mainError = null; + var mainErrorCount = 0; + for (var i = 0; i < this._errors.length; i++) { + var error = this._errors[i]; + var message = error.message; + var count = (counts[message] || 0) + 1; + counts[message] = count; + if (count >= mainErrorCount) { + mainError = error; + mainErrorCount = count; + } + } + return mainError; + }; + } +}); + +// node_modules/retry/lib/retry.js +var require_retry = __commonJS({ + "node_modules/retry/lib/retry.js"(exports) { + var RetryOperation = require_retry_operation(); + exports.operation = function(options) { + var timeouts = exports.timeouts(options); + return new RetryOperation(timeouts, { + forever: options && (options.forever || options.retries === Infinity), + unref: options && options.unref, + maxRetryTime: options && options.maxRetryTime + }); + }; + exports.timeouts = function(options) { + if (options instanceof Array) { + return [].concat(options); + } + var opts = { + retries: 10, + factor: 2, + minTimeout: 1 * 1e3, + maxTimeout: Infinity, + randomize: false + }; + for (var key in options) { + opts[key] = options[key]; + } + if (opts.minTimeout > opts.maxTimeout) { + throw new Error("minTimeout is greater than maxTimeout"); + } + var timeouts = []; + for (var i = 0; i < opts.retries; i++) { + timeouts.push(this.createTimeout(i, opts)); + } + if (options && options.forever && !timeouts.length) { + timeouts.push(this.createTimeout(i, opts)); + } + timeouts.sort(function(a, b) { + return a - b; + }); + return timeouts; + }; + exports.createTimeout = function(attempt, opts) { + var random = opts.randomize ? Math.random() + 1 : 1; + var timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt)); + timeout = Math.min(timeout, opts.maxTimeout); + return timeout; + }; + exports.wrap = function(obj, options, methods) { + if (options instanceof Array) { + methods = options; + options = null; + } + if (!methods) { + methods = []; + for (var key in obj) { + if (typeof obj[key] === "function") { + methods.push(key); + } + } + } + for (var i = 0; i < methods.length; i++) { + var method = methods[i]; + var original = obj[method]; + obj[method] = function retryWrapper(original2) { + var op = exports.operation(options); + var args = Array.prototype.slice.call(arguments, 1); + var callback = args.pop(); + args.push(function(err) { + if (op.retry(err)) { + return; + } + if (err) { + arguments[0] = op.mainError(); + } + callback.apply(this, arguments); + }); + op.attempt(function() { + original2.apply(obj, args); + }); + }.bind(obj, original); + obj[method].options = options; + } + }; + } +}); + +// node_modules/retry/index.js +var require_retry2 = __commonJS({ + "node_modules/retry/index.js"(exports, module) { + module.exports = require_retry(); + } +}); + +// node_modules/p-retry/index.js +var require_p_retry = __commonJS({ + "node_modules/p-retry/index.js"(exports, module) { + "use strict"; + var retry = require_retry2(); + var networkErrorMsgs = [ + "Failed to fetch", + // Chrome + "NetworkError when attempting to fetch resource.", + // Firefox + "The Internet connection appears to be offline.", + // Safari + "Network request failed" + // `cross-fetch` + ]; + var AbortError = class extends Error { + constructor(message) { + super(); + if (message instanceof Error) { + this.originalError = message; + ({ message } = message); + } else { + this.originalError = new Error(message); + this.originalError.stack = this.stack; + } + this.name = "AbortError"; + this.message = message; + } + }; + var decorateErrorWithCounts = (error, attemptNumber, options) => { + const retriesLeft = options.retries - (attemptNumber - 1); + error.attemptNumber = attemptNumber; + error.retriesLeft = retriesLeft; + return error; + }; + var isNetworkError = (errorMessage) => networkErrorMsgs.includes(errorMessage); + var pRetry4 = (input, options) => new Promise((resolve, reject) => { + options = { + onFailedAttempt: () => { + }, + retries: 10, + ...options + }; + const operation = retry.operation(options); + operation.attempt(async (attemptNumber) => { + try { + resolve(await input(attemptNumber)); + } catch (error) { + if (!(error instanceof Error)) { + reject(new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`)); + return; + } + if (error instanceof AbortError) { + operation.stop(); + reject(error.originalError); + } else if (error instanceof TypeError && !isNetworkError(error.message)) { + operation.stop(); + reject(error); + } else { + decorateErrorWithCounts(error, attemptNumber, options); + try { + await options.onFailedAttempt(error); + } catch (error2) { + reject(error2); + return; + } + if (!operation.retry(error)) { + reject(operation.mainError()); + } + } + } + }); + }); + module.exports = pRetry4; + module.exports.default = pRetry4; + module.exports.AbortError = AbortError; + } +}); + +// node_modules/eventemitter3/index.js +var require_eventemitter3 = __commonJS({ + "node_modules/eventemitter3/index.js"(exports, module) { + "use strict"; + var has = Object.prototype.hasOwnProperty; + var prefix = "~"; + function Events() { + } + if (Object.create) { + Events.prototype = /* @__PURE__ */ Object.create(null); + if (!new Events().__proto__) prefix = false; + } + function EE(fn, context, once) { + this.fn = fn; + this.context = context; + this.once = once || false; + } + function addListener(emitter, event, fn, context, once) { + if (typeof fn !== "function") { + throw new TypeError("The listener must be a function"); + } + var listener = new EE(fn, context || emitter, once), evt = prefix ? prefix + event : event; + if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++; + else if (!emitter._events[evt].fn) emitter._events[evt].push(listener); + else emitter._events[evt] = [emitter._events[evt], listener]; + return emitter; + } + function clearEvent(emitter, evt) { + if (--emitter._eventsCount === 0) emitter._events = new Events(); + else delete emitter._events[evt]; + } + function EventEmitter() { + this._events = new Events(); + this._eventsCount = 0; + } + EventEmitter.prototype.eventNames = function eventNames() { + var names = [], events, name; + if (this._eventsCount === 0) return names; + for (name in events = this._events) { + if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); + } + if (Object.getOwnPropertySymbols) { + return names.concat(Object.getOwnPropertySymbols(events)); + } + return names; + }; + EventEmitter.prototype.listeners = function listeners(event) { + var evt = prefix ? prefix + event : event, handlers = this._events[evt]; + if (!handlers) return []; + if (handlers.fn) return [handlers.fn]; + for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) { + ee[i] = handlers[i].fn; + } + return ee; + }; + EventEmitter.prototype.listenerCount = function listenerCount(event) { + var evt = prefix ? prefix + event : event, listeners = this._events[evt]; + if (!listeners) return 0; + if (listeners.fn) return 1; + return listeners.length; + }; + EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { + var evt = prefix ? prefix + event : event; + if (!this._events[evt]) return false; + var listeners = this._events[evt], len = arguments.length, args, i; + if (listeners.fn) { + if (listeners.once) this.removeListener(event, listeners.fn, void 0, true); + switch (len) { + case 1: + return listeners.fn.call(listeners.context), true; + case 2: + return listeners.fn.call(listeners.context, a1), true; + case 3: + return listeners.fn.call(listeners.context, a1, a2), true; + case 4: + return listeners.fn.call(listeners.context, a1, a2, a3), true; + case 5: + return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; + case 6: + return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; + } + for (i = 1, args = new Array(len - 1); i < len; i++) { + args[i - 1] = arguments[i]; + } + listeners.fn.apply(listeners.context, args); + } else { + var length = listeners.length, j; + for (i = 0; i < length; i++) { + if (listeners[i].once) this.removeListener(event, listeners[i].fn, void 0, true); + switch (len) { + case 1: + listeners[i].fn.call(listeners[i].context); + break; + case 2: + listeners[i].fn.call(listeners[i].context, a1); + break; + case 3: + listeners[i].fn.call(listeners[i].context, a1, a2); + break; + case 4: + listeners[i].fn.call(listeners[i].context, a1, a2, a3); + break; + default: + if (!args) for (j = 1, args = new Array(len - 1); j < len; j++) { + args[j - 1] = arguments[j]; + } + listeners[i].fn.apply(listeners[i].context, args); + } + } + } + return true; + }; + EventEmitter.prototype.on = function on(event, fn, context) { + return addListener(this, event, fn, context, false); + }; + EventEmitter.prototype.once = function once(event, fn, context) { + return addListener(this, event, fn, context, true); + }; + EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { + var evt = prefix ? prefix + event : event; + if (!this._events[evt]) return this; + if (!fn) { + clearEvent(this, evt); + return this; + } + var listeners = this._events[evt]; + if (listeners.fn) { + if (listeners.fn === fn && (!once || listeners.once) && (!context || listeners.context === context)) { + clearEvent(this, evt); + } + } else { + for (var i = 0, events = [], length = listeners.length; i < length; i++) { + if (listeners[i].fn !== fn || once && !listeners[i].once || context && listeners[i].context !== context) { + events.push(listeners[i]); + } + } + if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; + else clearEvent(this, evt); + } + return this; + }; + EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { + var evt; + if (event) { + evt = prefix ? prefix + event : event; + if (this._events[evt]) clearEvent(this, evt); + } else { + this._events = new Events(); + this._eventsCount = 0; + } + return this; + }; + EventEmitter.prototype.off = EventEmitter.prototype.removeListener; + EventEmitter.prototype.addListener = EventEmitter.prototype.on; + EventEmitter.prefixed = prefix; + EventEmitter.EventEmitter = EventEmitter; + if ("undefined" !== typeof module) { + module.exports = EventEmitter; + } + } +}); + +// node_modules/p-finally/index.js +var require_p_finally = __commonJS({ + "node_modules/p-finally/index.js"(exports, module) { + "use strict"; + module.exports = (promise, onFinally) => { + onFinally = onFinally || (() => { + }); + return promise.then( + (val) => new Promise((resolve) => { + resolve(onFinally()); + }).then(() => val), + (err) => new Promise((resolve) => { + resolve(onFinally()); + }).then(() => { + throw err; + }) + ); + }; + } +}); + +// node_modules/p-timeout/index.js +var require_p_timeout = __commonJS({ + "node_modules/p-timeout/index.js"(exports, module) { + "use strict"; + var pFinally = require_p_finally(); + var TimeoutError = class extends Error { + constructor(message) { + super(message); + this.name = "TimeoutError"; + } + }; + var pTimeout = (promise, milliseconds, fallback) => new Promise((resolve, reject) => { + if (typeof milliseconds !== "number" || milliseconds < 0) { + throw new TypeError("Expected `milliseconds` to be a positive number"); + } + if (milliseconds === Infinity) { + resolve(promise); + return; + } + const timer = setTimeout(() => { + if (typeof fallback === "function") { + try { + resolve(fallback()); + } catch (error) { + reject(error); + } + return; + } + const message = typeof fallback === "string" ? fallback : `Promise timed out after ${milliseconds} milliseconds`; + const timeoutError = fallback instanceof Error ? fallback : new TimeoutError(message); + if (typeof promise.cancel === "function") { + promise.cancel(); + } + reject(timeoutError); + }, milliseconds); + pFinally( + // eslint-disable-next-line promise/prefer-await-to-then + promise.then(resolve, reject), + () => { + clearTimeout(timer); + } + ); + }); + module.exports = pTimeout; + module.exports.default = pTimeout; + module.exports.TimeoutError = TimeoutError; + } +}); + +// node_modules/p-queue/dist/lower-bound.js +var require_lower_bound = __commonJS({ + "node_modules/p-queue/dist/lower-bound.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + function lowerBound(array, value, comparator) { + let first = 0; + let count = array.length; + while (count > 0) { + const step = count / 2 | 0; + let it = first + step; + if (comparator(array[it], value) <= 0) { + first = ++it; + count -= step + 1; + } else { + count = step; + } + } + return first; + } + exports.default = lowerBound; + } +}); + +// node_modules/p-queue/dist/priority-queue.js +var require_priority_queue = __commonJS({ + "node_modules/p-queue/dist/priority-queue.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var lower_bound_1 = require_lower_bound(); + var PriorityQueue = class { + constructor() { + this._queue = []; + } + enqueue(run, options) { + options = Object.assign({ priority: 0 }, options); + const element = { + priority: options.priority, + run + }; + if (this.size && this._queue[this.size - 1].priority >= options.priority) { + this._queue.push(element); + return; + } + const index2 = lower_bound_1.default(this._queue, element, (a, b) => b.priority - a.priority); + this._queue.splice(index2, 0, element); + } + dequeue() { + const item = this._queue.shift(); + return item === null || item === void 0 ? void 0 : item.run; + } + filter(options) { + return this._queue.filter((element) => element.priority === options.priority).map((element) => element.run); + } + get size() { + return this._queue.length; + } + }; + exports.default = PriorityQueue; + } +}); + +// node_modules/p-queue/dist/index.js +var require_dist = __commonJS({ + "node_modules/p-queue/dist/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var EventEmitter = require_eventemitter3(); + var p_timeout_1 = require_p_timeout(); + var priority_queue_1 = require_priority_queue(); + var empty = () => { + }; + var timeoutError = new p_timeout_1.TimeoutError(); + var PQueue = class extends EventEmitter { + constructor(options) { + var _a2, _b, _c, _d; + super(); + this._intervalCount = 0; + this._intervalEnd = 0; + this._pendingCount = 0; + this._resolveEmpty = empty; + this._resolveIdle = empty; + options = Object.assign({ carryoverConcurrencyCount: false, intervalCap: Infinity, interval: 0, concurrency: Infinity, autoStart: true, queueClass: priority_queue_1.default }, options); + if (!(typeof options.intervalCap === "number" && options.intervalCap >= 1)) { + throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(_b = (_a2 = options.intervalCap) === null || _a2 === void 0 ? void 0 : _a2.toString()) !== null && _b !== void 0 ? _b : ""}\` (${typeof options.intervalCap})`); + } + if (options.interval === void 0 || !(Number.isFinite(options.interval) && options.interval >= 0)) { + throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(_d = (_c = options.interval) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : ""}\` (${typeof options.interval})`); + } + this._carryoverConcurrencyCount = options.carryoverConcurrencyCount; + this._isIntervalIgnored = options.intervalCap === Infinity || options.interval === 0; + this._intervalCap = options.intervalCap; + this._interval = options.interval; + this._queue = new options.queueClass(); + this._queueClass = options.queueClass; + this.concurrency = options.concurrency; + this._timeout = options.timeout; + this._throwOnTimeout = options.throwOnTimeout === true; + this._isPaused = options.autoStart === false; + } + get _doesIntervalAllowAnother() { + return this._isIntervalIgnored || this._intervalCount < this._intervalCap; + } + get _doesConcurrentAllowAnother() { + return this._pendingCount < this._concurrency; + } + _next() { + this._pendingCount--; + this._tryToStartAnother(); + this.emit("next"); + } + _resolvePromises() { + this._resolveEmpty(); + this._resolveEmpty = empty; + if (this._pendingCount === 0) { + this._resolveIdle(); + this._resolveIdle = empty; + this.emit("idle"); + } + } + _onResumeInterval() { + this._onInterval(); + this._initializeIntervalIfNeeded(); + this._timeoutId = void 0; + } + _isIntervalPaused() { + const now = Date.now(); + if (this._intervalId === void 0) { + const delay = this._intervalEnd - now; + if (delay < 0) { + this._intervalCount = this._carryoverConcurrencyCount ? this._pendingCount : 0; + } else { + if (this._timeoutId === void 0) { + this._timeoutId = setTimeout(() => { + this._onResumeInterval(); + }, delay); + } + return true; + } + } + return false; + } + _tryToStartAnother() { + if (this._queue.size === 0) { + if (this._intervalId) { + clearInterval(this._intervalId); + } + this._intervalId = void 0; + this._resolvePromises(); + return false; + } + if (!this._isPaused) { + const canInitializeInterval = !this._isIntervalPaused(); + if (this._doesIntervalAllowAnother && this._doesConcurrentAllowAnother) { + const job = this._queue.dequeue(); + if (!job) { + return false; + } + this.emit("active"); + job(); + if (canInitializeInterval) { + this._initializeIntervalIfNeeded(); + } + return true; + } + } + return false; + } + _initializeIntervalIfNeeded() { + if (this._isIntervalIgnored || this._intervalId !== void 0) { + return; + } + this._intervalId = setInterval(() => { + this._onInterval(); + }, this._interval); + this._intervalEnd = Date.now() + this._interval; + } + _onInterval() { + if (this._intervalCount === 0 && this._pendingCount === 0 && this._intervalId) { + clearInterval(this._intervalId); + this._intervalId = void 0; + } + this._intervalCount = this._carryoverConcurrencyCount ? this._pendingCount : 0; + this._processQueue(); + } + /** + Executes all queued functions until it reaches the limit. + */ + _processQueue() { + while (this._tryToStartAnother()) { + } + } + get concurrency() { + return this._concurrency; + } + set concurrency(newConcurrency) { + if (!(typeof newConcurrency === "number" && newConcurrency >= 1)) { + throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${newConcurrency}\` (${typeof newConcurrency})`); + } + this._concurrency = newConcurrency; + this._processQueue(); + } + /** + Adds a sync or async task to the queue. Always returns a promise. + */ + async add(fn, options = {}) { + return new Promise((resolve, reject) => { + const run = async () => { + this._pendingCount++; + this._intervalCount++; + try { + const operation = this._timeout === void 0 && options.timeout === void 0 ? fn() : p_timeout_1.default(Promise.resolve(fn()), options.timeout === void 0 ? this._timeout : options.timeout, () => { + if (options.throwOnTimeout === void 0 ? this._throwOnTimeout : options.throwOnTimeout) { + reject(timeoutError); + } + return void 0; + }); + resolve(await operation); + } catch (error) { + reject(error); + } + this._next(); + }; + this._queue.enqueue(run, options); + this._tryToStartAnother(); + this.emit("add"); + }); + } + /** + Same as `.add()`, but accepts an array of sync or async functions. + + @returns A promise that resolves when all functions are resolved. + */ + async addAll(functions, options) { + return Promise.all(functions.map(async (function_) => this.add(function_, options))); + } + /** + Start (or resume) executing enqueued tasks within concurrency limit. No need to call this if queue is not paused (via `options.autoStart = false` or by `.pause()` method.) + */ + start() { + if (!this._isPaused) { + return this; + } + this._isPaused = false; + this._processQueue(); + return this; + } + /** + Put queue execution on hold. + */ + pause() { + this._isPaused = true; + } + /** + Clear the queue. + */ + clear() { + this._queue = new this._queueClass(); + } + /** + Can be called multiple times. Useful if you for example add additional items at a later time. + + @returns A promise that settles when the queue becomes empty. + */ + async onEmpty() { + if (this._queue.size === 0) { + return; + } + return new Promise((resolve) => { + const existingResolve = this._resolveEmpty; + this._resolveEmpty = () => { + existingResolve(); + resolve(); + }; + }); + } + /** + The difference with `.onEmpty` is that `.onIdle` guarantees that all work from the queue has finished. `.onEmpty` merely signals that the queue is empty, but it could mean that some promises haven't completed yet. + + @returns A promise that settles when the queue becomes empty, and all promises have completed; `queue.size === 0 && queue.pending === 0`. + */ + async onIdle() { + if (this._pendingCount === 0 && this._queue.size === 0) { + return; + } + return new Promise((resolve) => { + const existingResolve = this._resolveIdle; + this._resolveIdle = () => { + existingResolve(); + resolve(); + }; + }); + } + /** + Size of the queue. + */ + get size() { + return this._queue.size; + } + /** + Size of the queue, filtered by the given options. + + For example, this can be used to find the number of items remaining in the queue with a specific priority level. + */ + sizeBy(options) { + return this._queue.filter(options).length; + } + /** + Number of pending promises. + */ + get pending() { + return this._pendingCount; + } + /** + Whether the queue is currently paused. + */ + get isPaused() { + return this._isPaused; + } + get timeout() { + return this._timeout; + } + /** + Set the timeout for future operations. + */ + set timeout(milliseconds) { + this._timeout = milliseconds; + } + }; + exports.default = PQueue; + } +}); + +// node_modules/langsmith/dist/utils/async_caller.js +var import_p_retry, import_p_queue, STATUS_NO_RETRY, STATUS_IGNORE, AsyncCaller; +var init_async_caller = __esm({ + "node_modules/langsmith/dist/utils/async_caller.js"() { + import_p_retry = __toESM(require_p_retry(), 1); + import_p_queue = __toESM(require_dist(), 1); + init_fetch(); + STATUS_NO_RETRY = [ + 400, + // Bad Request + 401, + // Unauthorized + 403, + // Forbidden + 404, + // Not Found + 405, + // Method Not Allowed + 406, + // Not Acceptable + 407, + // Proxy Authentication Required + 408 + // Request Timeout + ]; + STATUS_IGNORE = [ + 409 + // Conflict + ]; + AsyncCaller = class { + constructor(params) { + Object.defineProperty(this, "maxConcurrency", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "maxRetries", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "queue", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "onFailedResponseHook", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "debug", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.maxConcurrency = params.maxConcurrency ?? Infinity; + this.maxRetries = params.maxRetries ?? 6; + this.debug = params.debug; + if ("default" in import_p_queue.default) { + this.queue = new import_p_queue.default.default({ + concurrency: this.maxConcurrency + }); + } else { + this.queue = new import_p_queue.default({ concurrency: this.maxConcurrency }); + } + this.onFailedResponseHook = params?.onFailedResponseHook; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + call(callable, ...args) { + const onFailedResponseHook = this.onFailedResponseHook; + return this.queue.add(() => (0, import_p_retry.default)(() => callable(...args).catch((error) => { + if (error instanceof Error) { + throw error; + } else { + throw new Error(error); + } + }), { + async onFailedAttempt(error) { + if (error.message.startsWith("Cancel") || error.message.startsWith("TimeoutError") || error.name === "TimeoutError" || error.message.startsWith("AbortError")) { + throw error; + } + if (error?.code === "ECONNABORTED") { + throw error; + } + const response = error?.response; + const status = response?.status; + if (status) { + if (STATUS_NO_RETRY.includes(+status)) { + throw error; + } else if (STATUS_IGNORE.includes(+status)) { + return; + } + if (onFailedResponseHook) { + await onFailedResponseHook(response); + } + } + }, + // If needed we can change some of the defaults here, + // but they're quite sensible. + retries: this.maxRetries, + randomize: true + }), { throwOnTimeout: true }); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + callWithOptions(options, callable, ...args) { + if (options.signal) { + return Promise.race([ + this.call(callable, ...args), + new Promise((_, reject) => { + options.signal?.addEventListener("abort", () => { + reject(new Error("AbortError")); + }); + }) + ]); + } + return this.call(callable, ...args); + } + fetch(...args) { + return this.call(() => _getFetchImplementation(this.debug)(...args).then((res) => res.ok ? res : Promise.reject(res))); + } + }; + } +}); + +// node_modules/langsmith/dist/utils/messages.js +function isLangChainMessage(message) { + return typeof message?._getType === "function"; +} +function convertLangChainMessageToExample(message) { + const converted = { + type: message._getType(), + data: { content: message.content } + }; + if (message?.additional_kwargs && Object.keys(message.additional_kwargs).length > 0) { + converted.data.additional_kwargs = { ...message.additional_kwargs }; + } + return converted; +} +var init_messages = __esm({ + "node_modules/langsmith/dist/utils/messages.js"() { + } +}); + +// node_modules/langsmith/dist/utils/_uuid.js +function assertUuid(str, which) { + if (!UUID_REGEX.test(str)) { + const msg = which !== void 0 ? `Invalid UUID for ${which}: ${str}` : `Invalid UUID: ${str}`; + throw new Error(msg); + } + return str; +} +var UUID_REGEX; +var init_uuid = __esm({ + "node_modules/langsmith/dist/utils/_uuid.js"() { + UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + } +}); + +// node_modules/langsmith/dist/utils/warn.js +function warnOnce(message) { + if (!warnedMessages[message]) { + console.warn(message); + warnedMessages[message] = true; + } +} +var warnedMessages; +var init_warn = __esm({ + "node_modules/langsmith/dist/utils/warn.js"() { + warnedMessages = {}; + } +}); + +// node_modules/semver/internal/constants.js +var require_constants = __commonJS({ + "node_modules/semver/internal/constants.js"(exports, module) { + "use strict"; + var SEMVER_SPEC_VERSION = "2.0.0"; + var MAX_LENGTH = 256; + var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */ + 9007199254740991; + var MAX_SAFE_COMPONENT_LENGTH = 16; + var MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6; + var RELEASE_TYPES = [ + "major", + "premajor", + "minor", + "preminor", + "patch", + "prepatch", + "prerelease" + ]; + module.exports = { + MAX_LENGTH, + MAX_SAFE_COMPONENT_LENGTH, + MAX_SAFE_BUILD_LENGTH, + MAX_SAFE_INTEGER, + RELEASE_TYPES, + SEMVER_SPEC_VERSION, + FLAG_INCLUDE_PRERELEASE: 1, + FLAG_LOOSE: 2 + }; + } +}); + +// node_modules/semver/internal/debug.js +var require_debug = __commonJS({ + "node_modules/semver/internal/debug.js"(exports, module) { + "use strict"; + var debug = typeof process === "object" && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ? (...args) => console.error("SEMVER", ...args) : () => { + }; + module.exports = debug; + } +}); + +// node_modules/semver/internal/re.js +var require_re = __commonJS({ + "node_modules/semver/internal/re.js"(exports, module) { + "use strict"; + var { + MAX_SAFE_COMPONENT_LENGTH, + MAX_SAFE_BUILD_LENGTH, + MAX_LENGTH + } = require_constants(); + var debug = require_debug(); + exports = module.exports = {}; + var re = exports.re = []; + var safeRe = exports.safeRe = []; + var src = exports.src = []; + var safeSrc = exports.safeSrc = []; + var t = exports.t = {}; + var R = 0; + var LETTERDASHNUMBER = "[a-zA-Z0-9-]"; + var safeRegexReplacements = [ + ["\\s", 1], + ["\\d", MAX_LENGTH], + [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH] + ]; + var makeSafeRegex = (value) => { + for (const [token, max] of safeRegexReplacements) { + value = value.split(`${token}*`).join(`${token}{0,${max}}`).split(`${token}+`).join(`${token}{1,${max}}`); + } + return value; + }; + var createToken = (name, value, isGlobal) => { + const safe = makeSafeRegex(value); + const index2 = R++; + debug(name, index2, value); + t[name] = index2; + src[index2] = value; + safeSrc[index2] = safe; + re[index2] = new RegExp(value, isGlobal ? "g" : void 0); + safeRe[index2] = new RegExp(safe, isGlobal ? "g" : void 0); + }; + createToken("NUMERICIDENTIFIER", "0|[1-9]\\d*"); + createToken("NUMERICIDENTIFIERLOOSE", "\\d+"); + createToken("NONNUMERICIDENTIFIER", `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`); + createToken("MAINVERSION", `(${src[t.NUMERICIDENTIFIER]})\\.(${src[t.NUMERICIDENTIFIER]})\\.(${src[t.NUMERICIDENTIFIER]})`); + createToken("MAINVERSIONLOOSE", `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.(${src[t.NUMERICIDENTIFIERLOOSE]})\\.(${src[t.NUMERICIDENTIFIERLOOSE]})`); + createToken("PRERELEASEIDENTIFIER", `(?:${src[t.NONNUMERICIDENTIFIER]}|${src[t.NUMERICIDENTIFIER]})`); + createToken("PRERELEASEIDENTIFIERLOOSE", `(?:${src[t.NONNUMERICIDENTIFIER]}|${src[t.NUMERICIDENTIFIERLOOSE]})`); + createToken("PRERELEASE", `(?:-(${src[t.PRERELEASEIDENTIFIER]}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`); + createToken("PRERELEASELOOSE", `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`); + createToken("BUILDIDENTIFIER", `${LETTERDASHNUMBER}+`); + createToken("BUILD", `(?:\\+(${src[t.BUILDIDENTIFIER]}(?:\\.${src[t.BUILDIDENTIFIER]})*))`); + createToken("FULLPLAIN", `v?${src[t.MAINVERSION]}${src[t.PRERELEASE]}?${src[t.BUILD]}?`); + createToken("FULL", `^${src[t.FULLPLAIN]}$`); + createToken("LOOSEPLAIN", `[v=\\s]*${src[t.MAINVERSIONLOOSE]}${src[t.PRERELEASELOOSE]}?${src[t.BUILD]}?`); + createToken("LOOSE", `^${src[t.LOOSEPLAIN]}$`); + createToken("GTLT", "((?:<|>)?=?)"); + createToken("XRANGEIDENTIFIERLOOSE", `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`); + createToken("XRANGEIDENTIFIER", `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`); + createToken("XRANGEPLAIN", `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})(?:\\.(${src[t.XRANGEIDENTIFIER]})(?:\\.(${src[t.XRANGEIDENTIFIER]})(?:${src[t.PRERELEASE]})?${src[t.BUILD]}?)?)?`); + createToken("XRANGEPLAINLOOSE", `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})(?:${src[t.PRERELEASELOOSE]})?${src[t.BUILD]}?)?)?`); + createToken("XRANGE", `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`); + createToken("XRANGELOOSE", `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`); + createToken("COERCEPLAIN", `${"(^|[^\\d])(\\d{1,"}${MAX_SAFE_COMPONENT_LENGTH}})(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`); + createToken("COERCE", `${src[t.COERCEPLAIN]}(?:$|[^\\d])`); + createToken("COERCEFULL", src[t.COERCEPLAIN] + `(?:${src[t.PRERELEASE]})?(?:${src[t.BUILD]})?(?:$|[^\\d])`); + createToken("COERCERTL", src[t.COERCE], true); + createToken("COERCERTLFULL", src[t.COERCEFULL], true); + createToken("LONETILDE", "(?:~>?)"); + createToken("TILDETRIM", `(\\s*)${src[t.LONETILDE]}\\s+`, true); + exports.tildeTrimReplace = "$1~"; + createToken("TILDE", `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`); + createToken("TILDELOOSE", `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`); + createToken("LONECARET", "(?:\\^)"); + createToken("CARETTRIM", `(\\s*)${src[t.LONECARET]}\\s+`, true); + exports.caretTrimReplace = "$1^"; + createToken("CARET", `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`); + createToken("CARETLOOSE", `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`); + createToken("COMPARATORLOOSE", `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`); + createToken("COMPARATOR", `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`); + createToken("COMPARATORTRIM", `(\\s*)${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true); + exports.comparatorTrimReplace = "$1$2$3"; + createToken("HYPHENRANGE", `^\\s*(${src[t.XRANGEPLAIN]})\\s+-\\s+(${src[t.XRANGEPLAIN]})\\s*$`); + createToken("HYPHENRANGELOOSE", `^\\s*(${src[t.XRANGEPLAINLOOSE]})\\s+-\\s+(${src[t.XRANGEPLAINLOOSE]})\\s*$`); + createToken("STAR", "(<|>)?=?\\s*\\*"); + createToken("GTE0", "^\\s*>=\\s*0\\.0\\.0\\s*$"); + createToken("GTE0PRE", "^\\s*>=\\s*0\\.0\\.0-0\\s*$"); + } +}); + +// node_modules/semver/internal/parse-options.js +var require_parse_options = __commonJS({ + "node_modules/semver/internal/parse-options.js"(exports, module) { + "use strict"; + var looseOption = Object.freeze({ loose: true }); + var emptyOpts = Object.freeze({}); + var parseOptions = (options) => { + if (!options) { + return emptyOpts; + } + if (typeof options !== "object") { + return looseOption; + } + return options; + }; + module.exports = parseOptions; + } +}); + +// node_modules/semver/internal/identifiers.js +var require_identifiers = __commonJS({ + "node_modules/semver/internal/identifiers.js"(exports, module) { + "use strict"; + var numeric = /^[0-9]+$/; + var compareIdentifiers = (a, b) => { + const anum = numeric.test(a); + const bnum = numeric.test(b); + if (anum && bnum) { + a = +a; + b = +b; + } + return a === b ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : 1; + }; + var rcompareIdentifiers = (a, b) => compareIdentifiers(b, a); + module.exports = { + compareIdentifiers, + rcompareIdentifiers + }; + } +}); + +// node_modules/semver/classes/semver.js +var require_semver = __commonJS({ + "node_modules/semver/classes/semver.js"(exports, module) { + "use strict"; + var debug = require_debug(); + var { MAX_LENGTH, MAX_SAFE_INTEGER } = require_constants(); + var { safeRe: re, t } = require_re(); + var parseOptions = require_parse_options(); + var { compareIdentifiers } = require_identifiers(); + var SemVer = class _SemVer { + constructor(version2, options) { + options = parseOptions(options); + if (version2 instanceof _SemVer) { + if (version2.loose === !!options.loose && version2.includePrerelease === !!options.includePrerelease) { + return version2; + } else { + version2 = version2.version; + } + } else if (typeof version2 !== "string") { + throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version2}".`); + } + if (version2.length > MAX_LENGTH) { + throw new TypeError( + `version is longer than ${MAX_LENGTH} characters` + ); + } + debug("SemVer", version2, options); + this.options = options; + this.loose = !!options.loose; + this.includePrerelease = !!options.includePrerelease; + const m = version2.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]); + if (!m) { + throw new TypeError(`Invalid Version: ${version2}`); + } + this.raw = version2; + this.major = +m[1]; + this.minor = +m[2]; + this.patch = +m[3]; + if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError("Invalid major version"); + } + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError("Invalid minor version"); + } + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError("Invalid patch version"); + } + if (!m[4]) { + this.prerelease = []; + } else { + this.prerelease = m[4].split(".").map((id) => { + if (/^[0-9]+$/.test(id)) { + const num = +id; + if (num >= 0 && num < MAX_SAFE_INTEGER) { + return num; + } + } + return id; + }); + } + this.build = m[5] ? m[5].split(".") : []; + this.format(); + } + format() { + this.version = `${this.major}.${this.minor}.${this.patch}`; + if (this.prerelease.length) { + this.version += `-${this.prerelease.join(".")}`; + } + return this.version; + } + toString() { + return this.version; + } + compare(other) { + debug("SemVer.compare", this.version, this.options, other); + if (!(other instanceof _SemVer)) { + if (typeof other === "string" && other === this.version) { + return 0; + } + other = new _SemVer(other, this.options); + } + if (other.version === this.version) { + return 0; + } + return this.compareMain(other) || this.comparePre(other); + } + compareMain(other) { + if (!(other instanceof _SemVer)) { + other = new _SemVer(other, this.options); + } + return compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch); + } + comparePre(other) { + if (!(other instanceof _SemVer)) { + other = new _SemVer(other, this.options); + } + if (this.prerelease.length && !other.prerelease.length) { + return -1; + } else if (!this.prerelease.length && other.prerelease.length) { + return 1; + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0; + } + let i = 0; + do { + const a = this.prerelease[i]; + const b = other.prerelease[i]; + debug("prerelease compare", i, a, b); + if (a === void 0 && b === void 0) { + return 0; + } else if (b === void 0) { + return 1; + } else if (a === void 0) { + return -1; + } else if (a === b) { + continue; + } else { + return compareIdentifiers(a, b); + } + } while (++i); + } + compareBuild(other) { + if (!(other instanceof _SemVer)) { + other = new _SemVer(other, this.options); + } + let i = 0; + do { + const a = this.build[i]; + const b = other.build[i]; + debug("build compare", i, a, b); + if (a === void 0 && b === void 0) { + return 0; + } else if (b === void 0) { + return 1; + } else if (a === void 0) { + return -1; + } else if (a === b) { + continue; + } else { + return compareIdentifiers(a, b); + } + } while (++i); + } + // preminor will bump the version up to the next minor release, and immediately + // down to pre-release. premajor and prepatch work the same way. + inc(release, identifier, identifierBase) { + if (release.startsWith("pre")) { + if (!identifier && identifierBase === false) { + throw new Error("invalid increment argument: identifier is empty"); + } + if (identifier) { + const match = `-${identifier}`.match(this.options.loose ? re[t.PRERELEASELOOSE] : re[t.PRERELEASE]); + if (!match || match[1] !== identifier) { + throw new Error(`invalid identifier: ${identifier}`); + } + } + } + switch (release) { + case "premajor": + this.prerelease.length = 0; + this.patch = 0; + this.minor = 0; + this.major++; + this.inc("pre", identifier, identifierBase); + break; + case "preminor": + this.prerelease.length = 0; + this.patch = 0; + this.minor++; + this.inc("pre", identifier, identifierBase); + break; + case "prepatch": + this.prerelease.length = 0; + this.inc("patch", identifier, identifierBase); + this.inc("pre", identifier, identifierBase); + break; + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case "prerelease": + if (this.prerelease.length === 0) { + this.inc("patch", identifier, identifierBase); + } + this.inc("pre", identifier, identifierBase); + break; + case "release": + if (this.prerelease.length === 0) { + throw new Error(`version ${this.raw} is not a prerelease`); + } + this.prerelease.length = 0; + break; + case "major": + if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) { + this.major++; + } + this.minor = 0; + this.patch = 0; + this.prerelease = []; + break; + case "minor": + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++; + } + this.patch = 0; + this.prerelease = []; + break; + case "patch": + if (this.prerelease.length === 0) { + this.patch++; + } + this.prerelease = []; + break; + // This probably shouldn't be used publicly. + // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. + case "pre": { + const base = Number(identifierBase) ? 1 : 0; + if (this.prerelease.length === 0) { + this.prerelease = [base]; + } else { + let i = this.prerelease.length; + while (--i >= 0) { + if (typeof this.prerelease[i] === "number") { + this.prerelease[i]++; + i = -2; + } + } + if (i === -1) { + if (identifier === this.prerelease.join(".") && identifierBase === false) { + throw new Error("invalid increment argument: identifier already exists"); + } + this.prerelease.push(base); + } + } + if (identifier) { + let prerelease = [identifier, base]; + if (identifierBase === false) { + prerelease = [identifier]; + } + if (compareIdentifiers(this.prerelease[0], identifier) === 0) { + if (isNaN(this.prerelease[1])) { + this.prerelease = prerelease; + } + } else { + this.prerelease = prerelease; + } + } + break; + } + default: + throw new Error(`invalid increment argument: ${release}`); + } + this.raw = this.format(); + if (this.build.length) { + this.raw += `+${this.build.join(".")}`; + } + return this; + } + }; + module.exports = SemVer; + } +}); + +// node_modules/semver/functions/parse.js +var require_parse = __commonJS({ + "node_modules/semver/functions/parse.js"(exports, module) { + "use strict"; + var SemVer = require_semver(); + var parse5 = (version2, options, throwErrors = false) => { + if (version2 instanceof SemVer) { + return version2; + } + try { + return new SemVer(version2, options); + } catch (er) { + if (!throwErrors) { + return null; + } + throw er; + } + }; + module.exports = parse5; + } +}); + +// node_modules/semver/functions/valid.js +var require_valid = __commonJS({ + "node_modules/semver/functions/valid.js"(exports, module) { + "use strict"; + var parse5 = require_parse(); + var valid = (version2, options) => { + const v = parse5(version2, options); + return v ? v.version : null; + }; + module.exports = valid; + } +}); + +// node_modules/semver/functions/clean.js +var require_clean = __commonJS({ + "node_modules/semver/functions/clean.js"(exports, module) { + "use strict"; + var parse5 = require_parse(); + var clean = (version2, options) => { + const s = parse5(version2.trim().replace(/^[=v]+/, ""), options); + return s ? s.version : null; + }; + module.exports = clean; + } +}); + +// node_modules/semver/functions/inc.js +var require_inc = __commonJS({ + "node_modules/semver/functions/inc.js"(exports, module) { + "use strict"; + var SemVer = require_semver(); + var inc = (version2, release, options, identifier, identifierBase) => { + if (typeof options === "string") { + identifierBase = identifier; + identifier = options; + options = void 0; + } + try { + return new SemVer( + version2 instanceof SemVer ? version2.version : version2, + options + ).inc(release, identifier, identifierBase).version; + } catch (er) { + return null; + } + }; + module.exports = inc; + } +}); + +// node_modules/semver/functions/diff.js +var require_diff = __commonJS({ + "node_modules/semver/functions/diff.js"(exports, module) { + "use strict"; + var parse5 = require_parse(); + var diff = (version1, version2) => { + const v12 = parse5(version1, null, true); + const v2 = parse5(version2, null, true); + const comparison = v12.compare(v2); + if (comparison === 0) { + return null; + } + const v1Higher = comparison > 0; + const highVersion = v1Higher ? v12 : v2; + const lowVersion = v1Higher ? v2 : v12; + const highHasPre = !!highVersion.prerelease.length; + const lowHasPre = !!lowVersion.prerelease.length; + if (lowHasPre && !highHasPre) { + if (!lowVersion.patch && !lowVersion.minor) { + return "major"; + } + if (lowVersion.compareMain(highVersion) === 0) { + if (lowVersion.minor && !lowVersion.patch) { + return "minor"; + } + return "patch"; + } + } + const prefix = highHasPre ? "pre" : ""; + if (v12.major !== v2.major) { + return prefix + "major"; + } + if (v12.minor !== v2.minor) { + return prefix + "minor"; + } + if (v12.patch !== v2.patch) { + return prefix + "patch"; + } + return "prerelease"; + }; + module.exports = diff; + } +}); + +// node_modules/semver/functions/major.js +var require_major = __commonJS({ + "node_modules/semver/functions/major.js"(exports, module) { + "use strict"; + var SemVer = require_semver(); + var major = (a, loose) => new SemVer(a, loose).major; + module.exports = major; + } +}); + +// node_modules/semver/functions/minor.js +var require_minor = __commonJS({ + "node_modules/semver/functions/minor.js"(exports, module) { + "use strict"; + var SemVer = require_semver(); + var minor = (a, loose) => new SemVer(a, loose).minor; + module.exports = minor; + } +}); + +// node_modules/semver/functions/patch.js +var require_patch = __commonJS({ + "node_modules/semver/functions/patch.js"(exports, module) { + "use strict"; + var SemVer = require_semver(); + var patch = (a, loose) => new SemVer(a, loose).patch; + module.exports = patch; + } +}); + +// node_modules/semver/functions/prerelease.js +var require_prerelease = __commonJS({ + "node_modules/semver/functions/prerelease.js"(exports, module) { + "use strict"; + var parse5 = require_parse(); + var prerelease = (version2, options) => { + const parsed = parse5(version2, options); + return parsed && parsed.prerelease.length ? parsed.prerelease : null; + }; + module.exports = prerelease; + } +}); + +// node_modules/semver/functions/compare.js +var require_compare = __commonJS({ + "node_modules/semver/functions/compare.js"(exports, module) { + "use strict"; + var SemVer = require_semver(); + var compare2 = (a, b, loose) => new SemVer(a, loose).compare(new SemVer(b, loose)); + module.exports = compare2; + } +}); + +// node_modules/semver/functions/rcompare.js +var require_rcompare = __commonJS({ + "node_modules/semver/functions/rcompare.js"(exports, module) { + "use strict"; + var compare2 = require_compare(); + var rcompare = (a, b, loose) => compare2(b, a, loose); + module.exports = rcompare; + } +}); + +// node_modules/semver/functions/compare-loose.js +var require_compare_loose = __commonJS({ + "node_modules/semver/functions/compare-loose.js"(exports, module) { + "use strict"; + var compare2 = require_compare(); + var compareLoose = (a, b) => compare2(a, b, true); + module.exports = compareLoose; + } +}); + +// node_modules/semver/functions/compare-build.js +var require_compare_build = __commonJS({ + "node_modules/semver/functions/compare-build.js"(exports, module) { + "use strict"; + var SemVer = require_semver(); + var compareBuild = (a, b, loose) => { + const versionA = new SemVer(a, loose); + const versionB = new SemVer(b, loose); + return versionA.compare(versionB) || versionA.compareBuild(versionB); + }; + module.exports = compareBuild; + } +}); + +// node_modules/semver/functions/sort.js +var require_sort = __commonJS({ + "node_modules/semver/functions/sort.js"(exports, module) { + "use strict"; + var compareBuild = require_compare_build(); + var sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose)); + module.exports = sort; + } +}); + +// node_modules/semver/functions/rsort.js +var require_rsort = __commonJS({ + "node_modules/semver/functions/rsort.js"(exports, module) { + "use strict"; + var compareBuild = require_compare_build(); + var rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)); + module.exports = rsort; + } +}); + +// node_modules/semver/functions/gt.js +var require_gt = __commonJS({ + "node_modules/semver/functions/gt.js"(exports, module) { + "use strict"; + var compare2 = require_compare(); + var gt = (a, b, loose) => compare2(a, b, loose) > 0; + module.exports = gt; + } +}); + +// node_modules/semver/functions/lt.js +var require_lt = __commonJS({ + "node_modules/semver/functions/lt.js"(exports, module) { + "use strict"; + var compare2 = require_compare(); + var lt = (a, b, loose) => compare2(a, b, loose) < 0; + module.exports = lt; + } +}); + +// node_modules/semver/functions/eq.js +var require_eq = __commonJS({ + "node_modules/semver/functions/eq.js"(exports, module) { + "use strict"; + var compare2 = require_compare(); + var eq = (a, b, loose) => compare2(a, b, loose) === 0; + module.exports = eq; + } +}); + +// node_modules/semver/functions/neq.js +var require_neq = __commonJS({ + "node_modules/semver/functions/neq.js"(exports, module) { + "use strict"; + var compare2 = require_compare(); + var neq = (a, b, loose) => compare2(a, b, loose) !== 0; + module.exports = neq; + } +}); + +// node_modules/semver/functions/gte.js +var require_gte = __commonJS({ + "node_modules/semver/functions/gte.js"(exports, module) { + "use strict"; + var compare2 = require_compare(); + var gte = (a, b, loose) => compare2(a, b, loose) >= 0; + module.exports = gte; + } +}); + +// node_modules/semver/functions/lte.js +var require_lte = __commonJS({ + "node_modules/semver/functions/lte.js"(exports, module) { + "use strict"; + var compare2 = require_compare(); + var lte = (a, b, loose) => compare2(a, b, loose) <= 0; + module.exports = lte; + } +}); + +// node_modules/semver/functions/cmp.js +var require_cmp = __commonJS({ + "node_modules/semver/functions/cmp.js"(exports, module) { + "use strict"; + var eq = require_eq(); + var neq = require_neq(); + var gt = require_gt(); + var gte = require_gte(); + var lt = require_lt(); + var lte = require_lte(); + var cmp = (a, op, b, loose) => { + switch (op) { + case "===": + if (typeof a === "object") { + a = a.version; + } + if (typeof b === "object") { + b = b.version; + } + return a === b; + case "!==": + if (typeof a === "object") { + a = a.version; + } + if (typeof b === "object") { + b = b.version; + } + return a !== b; + case "": + case "=": + case "==": + return eq(a, b, loose); + case "!=": + return neq(a, b, loose); + case ">": + return gt(a, b, loose); + case ">=": + return gte(a, b, loose); + case "<": + return lt(a, b, loose); + case "<=": + return lte(a, b, loose); + default: + throw new TypeError(`Invalid operator: ${op}`); + } + }; + module.exports = cmp; + } +}); + +// node_modules/semver/functions/coerce.js +var require_coerce = __commonJS({ + "node_modules/semver/functions/coerce.js"(exports, module) { + "use strict"; + var SemVer = require_semver(); + var parse5 = require_parse(); + var { safeRe: re, t } = require_re(); + var coerce2 = (version2, options) => { + if (version2 instanceof SemVer) { + return version2; + } + if (typeof version2 === "number") { + version2 = String(version2); + } + if (typeof version2 !== "string") { + return null; + } + options = options || {}; + let match = null; + if (!options.rtl) { + match = version2.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE]); + } else { + const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL]; + let next; + while ((next = coerceRtlRegex.exec(version2)) && (!match || match.index + match[0].length !== version2.length)) { + if (!match || next.index + next[0].length !== match.index + match[0].length) { + match = next; + } + coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length; + } + coerceRtlRegex.lastIndex = -1; + } + if (match === null) { + return null; + } + const major = match[2]; + const minor = match[3] || "0"; + const patch = match[4] || "0"; + const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : ""; + const build = options.includePrerelease && match[6] ? `+${match[6]}` : ""; + return parse5(`${major}.${minor}.${patch}${prerelease}${build}`, options); + }; + module.exports = coerce2; + } +}); + +// node_modules/semver/internal/lrucache.js +var require_lrucache = __commonJS({ + "node_modules/semver/internal/lrucache.js"(exports, module) { + "use strict"; + var LRUCache = class { + constructor() { + this.max = 1e3; + this.map = /* @__PURE__ */ new Map(); + } + get(key) { + const value = this.map.get(key); + if (value === void 0) { + return void 0; + } else { + this.map.delete(key); + this.map.set(key, value); + return value; + } + } + delete(key) { + return this.map.delete(key); + } + set(key, value) { + const deleted = this.delete(key); + if (!deleted && value !== void 0) { + if (this.map.size >= this.max) { + const firstKey = this.map.keys().next().value; + this.delete(firstKey); + } + this.map.set(key, value); + } + return this; + } + }; + module.exports = LRUCache; + } +}); + +// node_modules/semver/classes/range.js +var require_range = __commonJS({ + "node_modules/semver/classes/range.js"(exports, module) { + "use strict"; + var SPACE_CHARACTERS = /\s+/g; + var Range = class _Range { + constructor(range, options) { + options = parseOptions(options); + if (range instanceof _Range) { + if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) { + return range; + } else { + return new _Range(range.raw, options); + } + } + if (range instanceof Comparator) { + this.raw = range.value; + this.set = [[range]]; + this.formatted = void 0; + return this; + } + this.options = options; + this.loose = !!options.loose; + this.includePrerelease = !!options.includePrerelease; + this.raw = range.trim().replace(SPACE_CHARACTERS, " "); + this.set = this.raw.split("||").map((r) => this.parseRange(r.trim())).filter((c) => c.length); + if (!this.set.length) { + throw new TypeError(`Invalid SemVer Range: ${this.raw}`); + } + if (this.set.length > 1) { + const first = this.set[0]; + this.set = this.set.filter((c) => !isNullSet(c[0])); + if (this.set.length === 0) { + this.set = [first]; + } else if (this.set.length > 1) { + for (const c of this.set) { + if (c.length === 1 && isAny(c[0])) { + this.set = [c]; + break; + } + } + } + } + this.formatted = void 0; + } + get range() { + if (this.formatted === void 0) { + this.formatted = ""; + for (let i = 0; i < this.set.length; i++) { + if (i > 0) { + this.formatted += "||"; + } + const comps = this.set[i]; + for (let k = 0; k < comps.length; k++) { + if (k > 0) { + this.formatted += " "; + } + this.formatted += comps[k].toString().trim(); + } + } + } + return this.formatted; + } + format() { + return this.range; + } + toString() { + return this.range; + } + parseRange(range) { + const memoOpts = (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | (this.options.loose && FLAG_LOOSE); + const memoKey = memoOpts + ":" + range; + const cached2 = cache2.get(memoKey); + if (cached2) { + return cached2; + } + const loose = this.options.loose; + const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE]; + range = range.replace(hr, hyphenReplace(this.options.includePrerelease)); + debug("hyphen replace", range); + range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace); + debug("comparator trim", range); + range = range.replace(re[t.TILDETRIM], tildeTrimReplace); + debug("tilde trim", range); + range = range.replace(re[t.CARETTRIM], caretTrimReplace); + debug("caret trim", range); + let rangeList = range.split(" ").map((comp) => parseComparator(comp, this.options)).join(" ").split(/\s+/).map((comp) => replaceGTE0(comp, this.options)); + if (loose) { + rangeList = rangeList.filter((comp) => { + debug("loose invalid filter", comp, this.options); + return !!comp.match(re[t.COMPARATORLOOSE]); + }); + } + debug("range list", rangeList); + const rangeMap = /* @__PURE__ */ new Map(); + const comparators = rangeList.map((comp) => new Comparator(comp, this.options)); + for (const comp of comparators) { + if (isNullSet(comp)) { + return [comp]; + } + rangeMap.set(comp.value, comp); + } + if (rangeMap.size > 1 && rangeMap.has("")) { + rangeMap.delete(""); + } + const result = [...rangeMap.values()]; + cache2.set(memoKey, result); + return result; + } + intersects(range, options) { + if (!(range instanceof _Range)) { + throw new TypeError("a Range is required"); + } + return this.set.some((thisComparators) => { + return isSatisfiable(thisComparators, options) && range.set.some((rangeComparators) => { + return isSatisfiable(rangeComparators, options) && thisComparators.every((thisComparator) => { + return rangeComparators.every((rangeComparator) => { + return thisComparator.intersects(rangeComparator, options); + }); + }); + }); + }); + } + // if ANY of the sets match ALL of its comparators, then pass + test(version2) { + if (!version2) { + return false; + } + if (typeof version2 === "string") { + try { + version2 = new SemVer(version2, this.options); + } catch (er) { + return false; + } + } + for (let i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version2, this.options)) { + return true; + } + } + return false; + } + }; + module.exports = Range; + var LRU = require_lrucache(); + var cache2 = new LRU(); + var parseOptions = require_parse_options(); + var Comparator = require_comparator(); + var debug = require_debug(); + var SemVer = require_semver(); + var { + safeRe: re, + t, + comparatorTrimReplace, + tildeTrimReplace, + caretTrimReplace + } = require_re(); + var { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require_constants(); + var isNullSet = (c) => c.value === "<0.0.0-0"; + var isAny = (c) => c.value === ""; + var isSatisfiable = (comparators, options) => { + let result = true; + const remainingComparators = comparators.slice(); + let testComparator = remainingComparators.pop(); + while (result && remainingComparators.length) { + result = remainingComparators.every((otherComparator) => { + return testComparator.intersects(otherComparator, options); + }); + testComparator = remainingComparators.pop(); + } + return result; + }; + var parseComparator = (comp, options) => { + debug("comp", comp, options); + comp = replaceCarets(comp, options); + debug("caret", comp); + comp = replaceTildes(comp, options); + debug("tildes", comp); + comp = replaceXRanges(comp, options); + debug("xrange", comp); + comp = replaceStars(comp, options); + debug("stars", comp); + return comp; + }; + var isX = (id) => !id || id.toLowerCase() === "x" || id === "*"; + var replaceTildes = (comp, options) => { + return comp.trim().split(/\s+/).map((c) => replaceTilde(c, options)).join(" "); + }; + var replaceTilde = (comp, options) => { + const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE]; + return comp.replace(r, (_, M, m, p, pr) => { + debug("tilde", comp, _, M, m, p, pr); + let ret; + if (isX(M)) { + ret = ""; + } else if (isX(m)) { + ret = `>=${M}.0.0 <${+M + 1}.0.0-0`; + } else if (isX(p)) { + ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`; + } else if (pr) { + debug("replaceTilde pr", pr); + ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`; + } else { + ret = `>=${M}.${m}.${p} <${M}.${+m + 1}.0-0`; + } + debug("tilde return", ret); + return ret; + }); + }; + var replaceCarets = (comp, options) => { + return comp.trim().split(/\s+/).map((c) => replaceCaret(c, options)).join(" "); + }; + var replaceCaret = (comp, options) => { + debug("caret", comp, options); + const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET]; + const z = options.includePrerelease ? "-0" : ""; + return comp.replace(r, (_, M, m, p, pr) => { + debug("caret", comp, _, M, m, p, pr); + let ret; + if (isX(M)) { + ret = ""; + } else if (isX(m)) { + ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`; + } else if (isX(p)) { + if (M === "0") { + ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`; + } else { + ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`; + } + } else if (pr) { + debug("replaceCaret pr", pr); + if (M === "0") { + if (m === "0") { + ret = `>=${M}.${m}.${p}-${pr} <${M}.${m}.${+p + 1}-0`; + } else { + ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`; + } + } else { + ret = `>=${M}.${m}.${p}-${pr} <${+M + 1}.0.0-0`; + } + } else { + debug("no pr"); + if (M === "0") { + if (m === "0") { + ret = `>=${M}.${m}.${p}${z} <${M}.${m}.${+p + 1}-0`; + } else { + ret = `>=${M}.${m}.${p}${z} <${M}.${+m + 1}.0-0`; + } + } else { + ret = `>=${M}.${m}.${p} <${+M + 1}.0.0-0`; + } + } + debug("caret return", ret); + return ret; + }); + }; + var replaceXRanges = (comp, options) => { + debug("replaceXRanges", comp, options); + return comp.split(/\s+/).map((c) => replaceXRange(c, options)).join(" "); + }; + var replaceXRange = (comp, options) => { + comp = comp.trim(); + const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE]; + return comp.replace(r, (ret, gtlt, M, m, p, pr) => { + debug("xRange", comp, ret, gtlt, M, m, p, pr); + const xM = isX(M); + const xm = xM || isX(m); + const xp = xm || isX(p); + const anyX = xp; + if (gtlt === "=" && anyX) { + gtlt = ""; + } + pr = options.includePrerelease ? "-0" : ""; + if (xM) { + if (gtlt === ">" || gtlt === "<") { + ret = "<0.0.0-0"; + } else { + ret = "*"; + } + } else if (gtlt && anyX) { + if (xm) { + m = 0; + } + p = 0; + if (gtlt === ">") { + gtlt = ">="; + if (xm) { + M = +M + 1; + m = 0; + p = 0; + } else { + m = +m + 1; + p = 0; + } + } else if (gtlt === "<=") { + gtlt = "<"; + if (xm) { + M = +M + 1; + } else { + m = +m + 1; + } + } + if (gtlt === "<") { + pr = "-0"; + } + ret = `${gtlt + M}.${m}.${p}${pr}`; + } else if (xm) { + ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`; + } else if (xp) { + ret = `>=${M}.${m}.0${pr} <${M}.${+m + 1}.0-0`; + } + debug("xRange return", ret); + return ret; + }); + }; + var replaceStars = (comp, options) => { + debug("replaceStars", comp, options); + return comp.trim().replace(re[t.STAR], ""); + }; + var replaceGTE0 = (comp, options) => { + debug("replaceGTE0", comp, options); + return comp.trim().replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], ""); + }; + var hyphenReplace = (incPr) => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr) => { + if (isX(fM)) { + from = ""; + } else if (isX(fm)) { + from = `>=${fM}.0.0${incPr ? "-0" : ""}`; + } else if (isX(fp)) { + from = `>=${fM}.${fm}.0${incPr ? "-0" : ""}`; + } else if (fpr) { + from = `>=${from}`; + } else { + from = `>=${from}${incPr ? "-0" : ""}`; + } + if (isX(tM)) { + to = ""; + } else if (isX(tm)) { + to = `<${+tM + 1}.0.0-0`; + } else if (isX(tp)) { + to = `<${tM}.${+tm + 1}.0-0`; + } else if (tpr) { + to = `<=${tM}.${tm}.${tp}-${tpr}`; + } else if (incPr) { + to = `<${tM}.${tm}.${+tp + 1}-0`; + } else { + to = `<=${to}`; + } + return `${from} ${to}`.trim(); + }; + var testSet = (set, version2, options) => { + for (let i = 0; i < set.length; i++) { + if (!set[i].test(version2)) { + return false; + } + } + if (version2.prerelease.length && !options.includePrerelease) { + for (let i = 0; i < set.length; i++) { + debug(set[i].semver); + if (set[i].semver === Comparator.ANY) { + continue; + } + if (set[i].semver.prerelease.length > 0) { + const allowed = set[i].semver; + if (allowed.major === version2.major && allowed.minor === version2.minor && allowed.patch === version2.patch) { + return true; + } + } + } + return false; + } + return true; + }; + } +}); + +// node_modules/semver/classes/comparator.js +var require_comparator = __commonJS({ + "node_modules/semver/classes/comparator.js"(exports, module) { + "use strict"; + var ANY = Symbol("SemVer ANY"); + var Comparator = class _Comparator { + static get ANY() { + return ANY; + } + constructor(comp, options) { + options = parseOptions(options); + if (comp instanceof _Comparator) { + if (comp.loose === !!options.loose) { + return comp; + } else { + comp = comp.value; + } + } + comp = comp.trim().split(/\s+/).join(" "); + debug("comparator", comp, options); + this.options = options; + this.loose = !!options.loose; + this.parse(comp); + if (this.semver === ANY) { + this.value = ""; + } else { + this.value = this.operator + this.semver.version; + } + debug("comp", this); + } + parse(comp) { + const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]; + const m = comp.match(r); + if (!m) { + throw new TypeError(`Invalid comparator: ${comp}`); + } + this.operator = m[1] !== void 0 ? m[1] : ""; + if (this.operator === "=") { + this.operator = ""; + } + if (!m[2]) { + this.semver = ANY; + } else { + this.semver = new SemVer(m[2], this.options.loose); + } + } + toString() { + return this.value; + } + test(version2) { + debug("Comparator.test", version2, this.options.loose); + if (this.semver === ANY || version2 === ANY) { + return true; + } + if (typeof version2 === "string") { + try { + version2 = new SemVer(version2, this.options); + } catch (er) { + return false; + } + } + return cmp(version2, this.operator, this.semver, this.options); + } + intersects(comp, options) { + if (!(comp instanceof _Comparator)) { + throw new TypeError("a Comparator is required"); + } + if (this.operator === "") { + if (this.value === "") { + return true; + } + return new Range(comp.value, options).test(this.value); + } else if (comp.operator === "") { + if (comp.value === "") { + return true; + } + return new Range(this.value, options).test(comp.semver); + } + options = parseOptions(options); + if (options.includePrerelease && (this.value === "<0.0.0-0" || comp.value === "<0.0.0-0")) { + return false; + } + if (!options.includePrerelease && (this.value.startsWith("<0.0.0") || comp.value.startsWith("<0.0.0"))) { + return false; + } + if (this.operator.startsWith(">") && comp.operator.startsWith(">")) { + return true; + } + if (this.operator.startsWith("<") && comp.operator.startsWith("<")) { + return true; + } + if (this.semver.version === comp.semver.version && this.operator.includes("=") && comp.operator.includes("=")) { + return true; + } + if (cmp(this.semver, "<", comp.semver, options) && this.operator.startsWith(">") && comp.operator.startsWith("<")) { + return true; + } + if (cmp(this.semver, ">", comp.semver, options) && this.operator.startsWith("<") && comp.operator.startsWith(">")) { + return true; + } + return false; + } + }; + module.exports = Comparator; + var parseOptions = require_parse_options(); + var { safeRe: re, t } = require_re(); + var cmp = require_cmp(); + var debug = require_debug(); + var SemVer = require_semver(); + var Range = require_range(); + } +}); + +// node_modules/semver/functions/satisfies.js +var require_satisfies = __commonJS({ + "node_modules/semver/functions/satisfies.js"(exports, module) { + "use strict"; + var Range = require_range(); + var satisfies = (version2, range, options) => { + try { + range = new Range(range, options); + } catch (er) { + return false; + } + return range.test(version2); + }; + module.exports = satisfies; + } +}); + +// node_modules/semver/ranges/to-comparators.js +var require_to_comparators = __commonJS({ + "node_modules/semver/ranges/to-comparators.js"(exports, module) { + "use strict"; + var Range = require_range(); + var toComparators = (range, options) => new Range(range, options).set.map((comp) => comp.map((c) => c.value).join(" ").trim().split(" ")); + module.exports = toComparators; + } +}); + +// node_modules/semver/ranges/max-satisfying.js +var require_max_satisfying = __commonJS({ + "node_modules/semver/ranges/max-satisfying.js"(exports, module) { + "use strict"; + var SemVer = require_semver(); + var Range = require_range(); + var maxSatisfying = (versions, range, options) => { + let max = null; + let maxSV = null; + let rangeObj = null; + try { + rangeObj = new Range(range, options); + } catch (er) { + return null; + } + versions.forEach((v) => { + if (rangeObj.test(v)) { + if (!max || maxSV.compare(v) === -1) { + max = v; + maxSV = new SemVer(max, options); + } + } + }); + return max; + }; + module.exports = maxSatisfying; + } +}); + +// node_modules/semver/ranges/min-satisfying.js +var require_min_satisfying = __commonJS({ + "node_modules/semver/ranges/min-satisfying.js"(exports, module) { + "use strict"; + var SemVer = require_semver(); + var Range = require_range(); + var minSatisfying = (versions, range, options) => { + let min = null; + let minSV = null; + let rangeObj = null; + try { + rangeObj = new Range(range, options); + } catch (er) { + return null; + } + versions.forEach((v) => { + if (rangeObj.test(v)) { + if (!min || minSV.compare(v) === 1) { + min = v; + minSV = new SemVer(min, options); + } + } + }); + return min; + }; + module.exports = minSatisfying; + } +}); + +// node_modules/semver/ranges/min-version.js +var require_min_version = __commonJS({ + "node_modules/semver/ranges/min-version.js"(exports, module) { + "use strict"; + var SemVer = require_semver(); + var Range = require_range(); + var gt = require_gt(); + var minVersion = (range, loose) => { + range = new Range(range, loose); + let minver = new SemVer("0.0.0"); + if (range.test(minver)) { + return minver; + } + minver = new SemVer("0.0.0-0"); + if (range.test(minver)) { + return minver; + } + minver = null; + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i]; + let setMin = null; + comparators.forEach((comparator) => { + const compver = new SemVer(comparator.semver.version); + switch (comparator.operator) { + case ">": + if (compver.prerelease.length === 0) { + compver.patch++; + } else { + compver.prerelease.push(0); + } + compver.raw = compver.format(); + /* fallthrough */ + case "": + case ">=": + if (!setMin || gt(compver, setMin)) { + setMin = compver; + } + break; + case "<": + case "<=": + break; + /* istanbul ignore next */ + default: + throw new Error(`Unexpected operation: ${comparator.operator}`); + } + }); + if (setMin && (!minver || gt(minver, setMin))) { + minver = setMin; + } + } + if (minver && range.test(minver)) { + return minver; + } + return null; + }; + module.exports = minVersion; + } +}); + +// node_modules/semver/ranges/valid.js +var require_valid2 = __commonJS({ + "node_modules/semver/ranges/valid.js"(exports, module) { + "use strict"; + var Range = require_range(); + var validRange = (range, options) => { + try { + return new Range(range, options).range || "*"; + } catch (er) { + return null; + } + }; + module.exports = validRange; + } +}); + +// node_modules/semver/ranges/outside.js +var require_outside = __commonJS({ + "node_modules/semver/ranges/outside.js"(exports, module) { + "use strict"; + var SemVer = require_semver(); + var Comparator = require_comparator(); + var { ANY } = Comparator; + var Range = require_range(); + var satisfies = require_satisfies(); + var gt = require_gt(); + var lt = require_lt(); + var lte = require_lte(); + var gte = require_gte(); + var outside = (version2, range, hilo, options) => { + version2 = new SemVer(version2, options); + range = new Range(range, options); + let gtfn, ltefn, ltfn, comp, ecomp; + switch (hilo) { + case ">": + gtfn = gt; + ltefn = lte; + ltfn = lt; + comp = ">"; + ecomp = ">="; + break; + case "<": + gtfn = lt; + ltefn = gte; + ltfn = gt; + comp = "<"; + ecomp = "<="; + break; + default: + throw new TypeError('Must provide a hilo val of "<" or ">"'); + } + if (satisfies(version2, range, options)) { + return false; + } + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i]; + let high = null; + let low = null; + comparators.forEach((comparator) => { + if (comparator.semver === ANY) { + comparator = new Comparator(">=0.0.0"); + } + high = high || comparator; + low = low || comparator; + if (gtfn(comparator.semver, high.semver, options)) { + high = comparator; + } else if (ltfn(comparator.semver, low.semver, options)) { + low = comparator; + } + }); + if (high.operator === comp || high.operator === ecomp) { + return false; + } + if ((!low.operator || low.operator === comp) && ltefn(version2, low.semver)) { + return false; + } else if (low.operator === ecomp && ltfn(version2, low.semver)) { + return false; + } + } + return true; + }; + module.exports = outside; + } +}); + +// node_modules/semver/ranges/gtr.js +var require_gtr = __commonJS({ + "node_modules/semver/ranges/gtr.js"(exports, module) { + "use strict"; + var outside = require_outside(); + var gtr = (version2, range, options) => outside(version2, range, ">", options); + module.exports = gtr; + } +}); + +// node_modules/semver/ranges/ltr.js +var require_ltr = __commonJS({ + "node_modules/semver/ranges/ltr.js"(exports, module) { + "use strict"; + var outside = require_outside(); + var ltr = (version2, range, options) => outside(version2, range, "<", options); + module.exports = ltr; + } +}); + +// node_modules/semver/ranges/intersects.js +var require_intersects = __commonJS({ + "node_modules/semver/ranges/intersects.js"(exports, module) { + "use strict"; + var Range = require_range(); + var intersects = (r1, r2, options) => { + r1 = new Range(r1, options); + r2 = new Range(r2, options); + return r1.intersects(r2, options); + }; + module.exports = intersects; + } +}); + +// node_modules/semver/ranges/simplify.js +var require_simplify = __commonJS({ + "node_modules/semver/ranges/simplify.js"(exports, module) { + "use strict"; + var satisfies = require_satisfies(); + var compare2 = require_compare(); + module.exports = (versions, range, options) => { + const set = []; + let first = null; + let prev = null; + const v = versions.sort((a, b) => compare2(a, b, options)); + for (const version2 of v) { + const included = satisfies(version2, range, options); + if (included) { + prev = version2; + if (!first) { + first = version2; + } + } else { + if (prev) { + set.push([first, prev]); + } + prev = null; + first = null; + } + } + if (first) { + set.push([first, null]); + } + const ranges = []; + for (const [min, max] of set) { + if (min === max) { + ranges.push(min); + } else if (!max && min === v[0]) { + ranges.push("*"); + } else if (!max) { + ranges.push(`>=${min}`); + } else if (min === v[0]) { + ranges.push(`<=${max}`); + } else { + ranges.push(`${min} - ${max}`); + } + } + const simplified = ranges.join(" || "); + const original = typeof range.raw === "string" ? range.raw : String(range); + return simplified.length < original.length ? simplified : range; + }; + } +}); + +// node_modules/semver/ranges/subset.js +var require_subset = __commonJS({ + "node_modules/semver/ranges/subset.js"(exports, module) { + "use strict"; + var Range = require_range(); + var Comparator = require_comparator(); + var { ANY } = Comparator; + var satisfies = require_satisfies(); + var compare2 = require_compare(); + var subset = (sub, dom, options = {}) => { + if (sub === dom) { + return true; + } + sub = new Range(sub, options); + dom = new Range(dom, options); + let sawNonNull = false; + OUTER: for (const simpleSub of sub.set) { + for (const simpleDom of dom.set) { + const isSub = simpleSubset(simpleSub, simpleDom, options); + sawNonNull = sawNonNull || isSub !== null; + if (isSub) { + continue OUTER; + } + } + if (sawNonNull) { + return false; + } + } + return true; + }; + var minimumVersionWithPreRelease = [new Comparator(">=0.0.0-0")]; + var minimumVersion = [new Comparator(">=0.0.0")]; + var simpleSubset = (sub, dom, options) => { + if (sub === dom) { + return true; + } + if (sub.length === 1 && sub[0].semver === ANY) { + if (dom.length === 1 && dom[0].semver === ANY) { + return true; + } else if (options.includePrerelease) { + sub = minimumVersionWithPreRelease; + } else { + sub = minimumVersion; + } + } + if (dom.length === 1 && dom[0].semver === ANY) { + if (options.includePrerelease) { + return true; + } else { + dom = minimumVersion; + } + } + const eqSet = /* @__PURE__ */ new Set(); + let gt, lt; + for (const c of sub) { + if (c.operator === ">" || c.operator === ">=") { + gt = higherGT(gt, c, options); + } else if (c.operator === "<" || c.operator === "<=") { + lt = lowerLT(lt, c, options); + } else { + eqSet.add(c.semver); + } + } + if (eqSet.size > 1) { + return null; + } + let gtltComp; + if (gt && lt) { + gtltComp = compare2(gt.semver, lt.semver, options); + if (gtltComp > 0) { + return null; + } else if (gtltComp === 0 && (gt.operator !== ">=" || lt.operator !== "<=")) { + return null; + } + } + for (const eq of eqSet) { + if (gt && !satisfies(eq, String(gt), options)) { + return null; + } + if (lt && !satisfies(eq, String(lt), options)) { + return null; + } + for (const c of dom) { + if (!satisfies(eq, String(c), options)) { + return false; + } + } + return true; + } + let higher, lower; + let hasDomLT, hasDomGT; + let needDomLTPre = lt && !options.includePrerelease && lt.semver.prerelease.length ? lt.semver : false; + let needDomGTPre = gt && !options.includePrerelease && gt.semver.prerelease.length ? gt.semver : false; + if (needDomLTPre && needDomLTPre.prerelease.length === 1 && lt.operator === "<" && needDomLTPre.prerelease[0] === 0) { + needDomLTPre = false; + } + for (const c of dom) { + hasDomGT = hasDomGT || c.operator === ">" || c.operator === ">="; + hasDomLT = hasDomLT || c.operator === "<" || c.operator === "<="; + if (gt) { + if (needDomGTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomGTPre.major && c.semver.minor === needDomGTPre.minor && c.semver.patch === needDomGTPre.patch) { + needDomGTPre = false; + } + } + if (c.operator === ">" || c.operator === ">=") { + higher = higherGT(gt, c, options); + if (higher === c && higher !== gt) { + return false; + } + } else if (gt.operator === ">=" && !satisfies(gt.semver, String(c), options)) { + return false; + } + } + if (lt) { + if (needDomLTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomLTPre.major && c.semver.minor === needDomLTPre.minor && c.semver.patch === needDomLTPre.patch) { + needDomLTPre = false; + } + } + if (c.operator === "<" || c.operator === "<=") { + lower = lowerLT(lt, c, options); + if (lower === c && lower !== lt) { + return false; + } + } else if (lt.operator === "<=" && !satisfies(lt.semver, String(c), options)) { + return false; + } + } + if (!c.operator && (lt || gt) && gtltComp !== 0) { + return false; + } + } + if (gt && hasDomLT && !lt && gtltComp !== 0) { + return false; + } + if (lt && hasDomGT && !gt && gtltComp !== 0) { + return false; + } + if (needDomGTPre || needDomLTPre) { + return false; + } + return true; + }; + var higherGT = (a, b, options) => { + if (!a) { + return b; + } + const comp = compare2(a.semver, b.semver, options); + return comp > 0 ? a : comp < 0 ? b : b.operator === ">" && a.operator === ">=" ? b : a; + }; + var lowerLT = (a, b, options) => { + if (!a) { + return b; + } + const comp = compare2(a.semver, b.semver, options); + return comp < 0 ? a : comp > 0 ? b : b.operator === "<" && a.operator === "<=" ? b : a; + }; + module.exports = subset; + } +}); + +// node_modules/semver/index.js +var require_semver2 = __commonJS({ + "node_modules/semver/index.js"(exports, module) { + "use strict"; + var internalRe = require_re(); + var constants = require_constants(); + var SemVer = require_semver(); + var identifiers = require_identifiers(); + var parse5 = require_parse(); + var valid = require_valid(); + var clean = require_clean(); + var inc = require_inc(); + var diff = require_diff(); + var major = require_major(); + var minor = require_minor(); + var patch = require_patch(); + var prerelease = require_prerelease(); + var compare2 = require_compare(); + var rcompare = require_rcompare(); + var compareLoose = require_compare_loose(); + var compareBuild = require_compare_build(); + var sort = require_sort(); + var rsort = require_rsort(); + var gt = require_gt(); + var lt = require_lt(); + var eq = require_eq(); + var neq = require_neq(); + var gte = require_gte(); + var lte = require_lte(); + var cmp = require_cmp(); + var coerce2 = require_coerce(); + var Comparator = require_comparator(); + var Range = require_range(); + var satisfies = require_satisfies(); + var toComparators = require_to_comparators(); + var maxSatisfying = require_max_satisfying(); + var minSatisfying = require_min_satisfying(); + var minVersion = require_min_version(); + var validRange = require_valid2(); + var outside = require_outside(); + var gtr = require_gtr(); + var ltr = require_ltr(); + var intersects = require_intersects(); + var simplifyRange = require_simplify(); + var subset = require_subset(); + module.exports = { + parse: parse5, + valid, + clean, + inc, + diff, + major, + minor, + patch, + prerelease, + compare: compare2, + rcompare, + compareLoose, + compareBuild, + sort, + rsort, + gt, + lt, + eq, + neq, + gte, + lte, + cmp, + coerce: coerce2, + Comparator, + Range, + satisfies, + toComparators, + maxSatisfying, + minSatisfying, + minVersion, + validRange, + outside, + gtr, + ltr, + intersects, + simplifyRange, + subset, + SemVer, + re: internalRe.re, + src: internalRe.src, + tokens: internalRe.t, + SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, + RELEASE_TYPES: constants.RELEASE_TYPES, + compareIdentifiers: identifiers.compareIdentifiers, + rcompareIdentifiers: identifiers.rcompareIdentifiers + }; + } +}); + +// node_modules/langsmith/dist/utils/prompts.js +function parsePromptIdentifier(identifier) { + if (!identifier || identifier.split("/").length > 2 || identifier.startsWith("/") || identifier.endsWith("/") || identifier.split(":").length > 2) { + throw new Error(`Invalid identifier format: ${identifier}`); + } + const [ownerNamePart, commitPart] = identifier.split(":"); + const commit = commitPart || "latest"; + if (ownerNamePart.includes("/")) { + const [owner, name] = ownerNamePart.split("/", 2); + if (!owner || !name) { + throw new Error(`Invalid identifier format: ${identifier}`); + } + return [owner, name, commit]; + } else { + if (!ownerNamePart) { + throw new Error(`Invalid identifier format: ${identifier}`); + } + return ["-", ownerNamePart, commit]; + } +} +var import_semver; +var init_prompts = __esm({ + "node_modules/langsmith/dist/utils/prompts.js"() { + import_semver = __toESM(require_semver2(), 1); + } +}); + +// node_modules/langsmith/dist/utils/error.js +async function raiseForStatus(response, context, consume) { + let errorBody; + if (response.ok) { + if (consume) { + errorBody = await response.text(); + } + return; + } + errorBody = await response.text(); + const fullMessage = `Failed to ${context}. Received status [${response.status}]: ${response.statusText}. Server response: ${errorBody}`; + if (response.status === 409) { + throw new LangSmithConflictError(fullMessage); + } + const err = new Error(fullMessage); + err.status = response.status; + throw err; +} +function isConflictingEndpointsError(err) { + return typeof err === "object" && err !== null && err.code === ERR_CONFLICTING_ENDPOINTS; +} +var LangSmithConflictError, ERR_CONFLICTING_ENDPOINTS, ConflictingEndpointsError; +var init_error = __esm({ + "node_modules/langsmith/dist/utils/error.js"() { + LangSmithConflictError = class extends Error { + constructor(message) { + super(message); + Object.defineProperty(this, "status", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.name = "LangSmithConflictError"; + this.status = 409; + } + }; + ERR_CONFLICTING_ENDPOINTS = "ERR_CONFLICTING_ENDPOINTS"; + ConflictingEndpointsError = class extends Error { + constructor() { + super("You cannot provide both LANGSMITH_ENDPOINT / LANGCHAIN_ENDPOINT and LANGSMITH_RUNS_ENDPOINTS."); + Object.defineProperty(this, "code", { + enumerable: true, + configurable: true, + writable: true, + value: ERR_CONFLICTING_ENDPOINTS + }); + this.name = "ConflictingEndpointsError"; + } + }; + } +}); + +// node_modules/langsmith/dist/utils/fast-safe-stringify/index.js +function defaultOptions() { + return { + depthLimit: Number.MAX_SAFE_INTEGER, + edgesLimit: Number.MAX_SAFE_INTEGER + }; +} +function encodeString(str) { + return encoder.encode(str); +} +function serializeWellKnownTypes(val) { + if (val && typeof val === "object" && val !== null) { + if (val instanceof Map) { + return Object.fromEntries(val); + } else if (val instanceof Set) { + return Array.from(val); + } else if (val instanceof Date) { + return val.toISOString(); + } else if (val instanceof RegExp) { + return val.toString(); + } else if (val instanceof Error) { + return { + name: val.name, + message: val.message + }; + } + } else if (typeof val === "bigint") { + return val.toString(); + } + return val; +} +function createDefaultReplacer(userReplacer) { + return function(key, val) { + if (userReplacer) { + const userResult = userReplacer.call(this, key, val); + if (userResult !== void 0) { + return userResult; + } + } + return serializeWellKnownTypes(val); + }; +} +function serialize(obj, errorContext, replacer, spacer, options) { + try { + const str = JSON.stringify(obj, createDefaultReplacer(replacer), spacer); + return encodeString(str); + } catch (e) { + if (!e.message?.includes("Converting circular structure to JSON")) { + console.warn(`[WARNING]: LangSmith received unserializable value.${errorContext ? ` +Context: ${errorContext}` : ""}`); + return encodeString("[Unserializable]"); + } + getLangSmithEnvironmentVariable("SUPPRESS_CIRCULAR_JSON_WARNINGS") !== "true" && console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${errorContext ? ` +Context: ${errorContext}` : ""}`); + if (typeof options === "undefined") { + options = defaultOptions(); + } + decirc(obj, "", 0, [], void 0, 0, options); + let res; + try { + if (replacerStack.length === 0) { + res = JSON.stringify(obj, replacer, spacer); + } else { + res = JSON.stringify(obj, replaceGetterValues(replacer), spacer); + } + } catch (_) { + return encodeString("[unable to serialize, circular reference is too complex to analyze]"); + } finally { + while (arr.length !== 0) { + const part = arr.pop(); + if (part.length === 4) { + Object.defineProperty(part[0], part[1], part[3]); + } else { + part[0][part[1]] = part[2]; + } + } + } + return encodeString(res); + } +} +function setReplace(replace, val, k, parent) { + var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k); + if (propertyDescriptor.get !== void 0) { + if (propertyDescriptor.configurable) { + Object.defineProperty(parent, k, { value: replace }); + arr.push([parent, k, val, propertyDescriptor]); + } else { + replacerStack.push([val, k, replace]); + } + } else { + parent[k] = replace; + arr.push([parent, k, val]); + } +} +function decirc(val, k, edgeIndex, stack, parent, depth, options) { + depth += 1; + var i; + if (typeof val === "object" && val !== null) { + for (i = 0; i < stack.length; i++) { + if (stack[i] === val) { + setReplace(CIRCULAR_REPLACE_NODE, val, k, parent); + return; + } + } + if (typeof options.depthLimit !== "undefined" && depth > options.depthLimit) { + setReplace(LIMIT_REPLACE_NODE, val, k, parent); + return; + } + if (typeof options.edgesLimit !== "undefined" && edgeIndex + 1 > options.edgesLimit) { + setReplace(LIMIT_REPLACE_NODE, val, k, parent); + return; + } + stack.push(val); + if (Array.isArray(val)) { + for (i = 0; i < val.length; i++) { + decirc(val[i], i, i, stack, val, depth, options); + } + } else { + val = serializeWellKnownTypes(val); + var keys = Object.keys(val); + for (i = 0; i < keys.length; i++) { + var key = keys[i]; + decirc(val[key], key, i, stack, val, depth, options); + } + } + stack.pop(); + } +} +function replaceGetterValues(replacer) { + replacer = typeof replacer !== "undefined" ? replacer : function(k, v) { + return v; + }; + return function(key, val) { + if (replacerStack.length > 0) { + for (var i = 0; i < replacerStack.length; i++) { + var part = replacerStack[i]; + if (part[1] === key && part[0] === val) { + val = part[2]; + replacerStack.splice(i, 1); + break; + } + } + } + return replacer.call(this, key, val); + }; +} +var LIMIT_REPLACE_NODE, CIRCULAR_REPLACE_NODE, arr, replacerStack, encoder; +var init_fast_safe_stringify = __esm({ + "node_modules/langsmith/dist/utils/fast-safe-stringify/index.js"() { + init_env2(); + LIMIT_REPLACE_NODE = "[...]"; + CIRCULAR_REPLACE_NODE = { result: "[Circular]" }; + arr = []; + replacerStack = []; + encoder = new TextEncoder(); + } +}); + +// node_modules/langsmith/dist/client.js +function mergeRuntimeEnvIntoRun(run) { + const runtimeEnv = getRuntimeEnvironment2(); + const envVars = getLangChainEnvVarsMetadata(); + const extra = run.extra ?? {}; + const metadata = extra.metadata; + run.extra = { + ...extra, + runtime: { + ...runtimeEnv, + ...extra?.runtime + }, + metadata: { + ...envVars, + ...envVars.revision_id || "revision_id" in run && run.revision_id ? { + revision_id: ("revision_id" in run ? run.revision_id : void 0) ?? envVars.revision_id + } : {}, + ...metadata + } + }; + return run; +} +async function toArray(iterable) { + const result = []; + for await (const item of iterable) { + result.push(item); + } + return result; +} +function trimQuotes(str) { + if (str === void 0) { + return void 0; + } + return str.trim().replace(/^"(.*)"$/, "$1").replace(/^'(.*)'$/, "$1"); +} +function _formatFeedbackScore(score) { + if (typeof score === "number") { + return Number(score.toFixed(4)); + } + return score; +} +function isExampleCreate(input) { + return "dataset_id" in input || "dataset_name" in input; +} +var getTracingSamplingRate, isLocalhost, handle429, AutoBatchQueue, DEFAULT_UNCOMPRESSED_BATCH_SIZE_LIMIT_BYTES, SERVER_INFO_REQUEST_TIMEOUT_MS, DEFAULT_API_URL, Client; +var init_client = __esm({ + "node_modules/langsmith/dist/client.js"() { + init_esm_browser(); + init_translator(); + init_otel(); + init_async_caller(); + init_messages(); + init_env2(); + init_dist(); + init_uuid(); + init_warn(); + init_prompts(); + init_error(); + init_fetch(); + init_fast_safe_stringify(); + getTracingSamplingRate = (configRate) => { + const samplingRateStr = configRate?.toString() ?? getLangSmithEnvironmentVariable("TRACING_SAMPLING_RATE"); + if (samplingRateStr === void 0) { + return void 0; + } + const samplingRate = parseFloat(samplingRateStr); + if (samplingRate < 0 || samplingRate > 1) { + throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${samplingRate}`); + } + return samplingRate; + }; + isLocalhost = (url) => { + const strippedUrl = url.replace("http://", "").replace("https://", ""); + const hostname = strippedUrl.split("/")[0].split(":")[0]; + return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1"; + }; + handle429 = async (response) => { + if (response?.status === 429) { + const retryAfter = parseInt(response.headers.get("retry-after") ?? "10", 10) * 1e3; + if (retryAfter > 0) { + await new Promise((resolve) => setTimeout(resolve, retryAfter)); + return true; + } + } + return false; + }; + AutoBatchQueue = class { + constructor() { + Object.defineProperty(this, "items", { + enumerable: true, + configurable: true, + writable: true, + value: [] + }); + Object.defineProperty(this, "sizeBytes", { + enumerable: true, + configurable: true, + writable: true, + value: 0 + }); + } + peek() { + return this.items[0]; + } + push(item) { + let itemPromiseResolve; + const itemPromise = new Promise((resolve) => { + itemPromiseResolve = resolve; + }); + const size = serialize(item.item, `Serializing run with id: ${item.item.id}`).length; + this.items.push({ + action: item.action, + payload: item.item, + otelContext: item.otelContext, + apiKey: item.apiKey, + apiUrl: item.apiUrl, + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + itemPromiseResolve, + itemPromise, + size + }); + this.sizeBytes += size; + return itemPromise; + } + pop(upToSizeBytes) { + if (upToSizeBytes < 1) { + throw new Error("Number of bytes to pop off may not be less than 1."); + } + const popped = []; + let poppedSizeBytes = 0; + while (poppedSizeBytes + (this.peek()?.size ?? 0) < upToSizeBytes && this.items.length > 0) { + const item = this.items.shift(); + if (item) { + popped.push(item); + poppedSizeBytes += item.size; + this.sizeBytes -= item.size; + } + } + if (popped.length === 0 && this.items.length > 0) { + const item = this.items.shift(); + popped.push(item); + poppedSizeBytes += item.size; + this.sizeBytes -= item.size; + } + return [ + popped.map((it) => ({ + action: it.action, + item: it.payload, + otelContext: it.otelContext, + apiKey: it.apiKey, + apiUrl: it.apiUrl + })), + () => popped.forEach((it) => it.itemPromiseResolve()) + ]; + } + }; + DEFAULT_UNCOMPRESSED_BATCH_SIZE_LIMIT_BYTES = 32 * 1024 * 1024; + SERVER_INFO_REQUEST_TIMEOUT_MS = 1e4; + DEFAULT_API_URL = "https://api.smith.langchain.com"; + Client = class _Client { + constructor(config2 = {}) { + Object.defineProperty(this, "apiKey", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "apiUrl", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "webUrl", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "caller", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "batchIngestCaller", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "timeout_ms", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "_tenantId", { + enumerable: true, + configurable: true, + writable: true, + value: null + }); + Object.defineProperty(this, "hideInputs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "hideOutputs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "tracingSampleRate", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "filteredPostUuids", { + enumerable: true, + configurable: true, + writable: true, + value: /* @__PURE__ */ new Set() + }); + Object.defineProperty(this, "autoBatchTracing", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "autoBatchQueue", { + enumerable: true, + configurable: true, + writable: true, + value: new AutoBatchQueue() + }); + Object.defineProperty(this, "autoBatchTimeout", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "autoBatchAggregationDelayMs", { + enumerable: true, + configurable: true, + writable: true, + value: 250 + }); + Object.defineProperty(this, "batchSizeBytesLimit", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "fetchOptions", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "settings", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "blockOnRootRunFinalization", { + enumerable: true, + configurable: true, + writable: true, + value: getEnvironmentVariable2("LANGSMITH_TRACING_BACKGROUND") === "false" + }); + Object.defineProperty(this, "traceBatchConcurrency", { + enumerable: true, + configurable: true, + writable: true, + value: 5 + }); + Object.defineProperty(this, "_serverInfo", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "_getServerInfoPromise", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "manualFlushMode", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "langSmithToOTELTranslator", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "multipartStreamingDisabled", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "debug", { + enumerable: true, + configurable: true, + writable: true, + value: getEnvironmentVariable2("LANGSMITH_DEBUG") === "true" + }); + const defaultConfig = _Client.getDefaultClientConfig(); + this.tracingSampleRate = getTracingSamplingRate(config2.tracingSamplingRate); + this.apiUrl = trimQuotes(config2.apiUrl ?? defaultConfig.apiUrl) ?? ""; + if (this.apiUrl.endsWith("/")) { + this.apiUrl = this.apiUrl.slice(0, -1); + } + this.apiKey = trimQuotes(config2.apiKey ?? defaultConfig.apiKey); + this.webUrl = trimQuotes(config2.webUrl ?? defaultConfig.webUrl); + if (this.webUrl?.endsWith("/")) { + this.webUrl = this.webUrl.slice(0, -1); + } + this.timeout_ms = config2.timeout_ms ?? 9e4; + this.caller = new AsyncCaller({ + ...config2.callerOptions ?? {}, + debug: config2.debug ?? this.debug + }); + this.traceBatchConcurrency = config2.traceBatchConcurrency ?? this.traceBatchConcurrency; + if (this.traceBatchConcurrency < 1) { + throw new Error("Trace batch concurrency must be positive."); + } + this.debug = config2.debug ?? this.debug; + this.batchIngestCaller = new AsyncCaller({ + maxRetries: 2, + maxConcurrency: this.traceBatchConcurrency, + ...config2.callerOptions ?? {}, + onFailedResponseHook: handle429, + debug: config2.debug ?? this.debug + }); + this.hideInputs = config2.hideInputs ?? config2.anonymizer ?? defaultConfig.hideInputs; + this.hideOutputs = config2.hideOutputs ?? config2.anonymizer ?? defaultConfig.hideOutputs; + this.autoBatchTracing = config2.autoBatchTracing ?? this.autoBatchTracing; + this.blockOnRootRunFinalization = config2.blockOnRootRunFinalization ?? this.blockOnRootRunFinalization; + this.batchSizeBytesLimit = config2.batchSizeBytesLimit; + this.fetchOptions = config2.fetchOptions || {}; + this.manualFlushMode = config2.manualFlushMode ?? this.manualFlushMode; + if (getOtelEnabled()) { + this.langSmithToOTELTranslator = new LangSmithToOTELTranslator(); + } + } + static getDefaultClientConfig() { + const apiKey = getLangSmithEnvironmentVariable("API_KEY"); + const apiUrl = getLangSmithEnvironmentVariable("ENDPOINT") ?? DEFAULT_API_URL; + const hideInputs = getLangSmithEnvironmentVariable("HIDE_INPUTS") === "true"; + const hideOutputs = getLangSmithEnvironmentVariable("HIDE_OUTPUTS") === "true"; + return { + apiUrl, + apiKey, + webUrl: void 0, + hideInputs, + hideOutputs + }; + } + getHostUrl() { + if (this.webUrl) { + return this.webUrl; + } else if (isLocalhost(this.apiUrl)) { + this.webUrl = "http://localhost:3000"; + return this.webUrl; + } else if (this.apiUrl.endsWith("/api/v1")) { + this.webUrl = this.apiUrl.replace("/api/v1", ""); + return this.webUrl; + } else if (this.apiUrl.includes("/api") && !this.apiUrl.split(".", 1)[0].endsWith("api")) { + this.webUrl = this.apiUrl.replace("/api", ""); + return this.webUrl; + } else if (this.apiUrl.split(".", 1)[0].includes("dev")) { + this.webUrl = "https://dev.smith.langchain.com"; + return this.webUrl; + } else if (this.apiUrl.split(".", 1)[0].includes("eu")) { + this.webUrl = "https://eu.smith.langchain.com"; + return this.webUrl; + } else if (this.apiUrl.split(".", 1)[0].includes("beta")) { + this.webUrl = "https://beta.smith.langchain.com"; + return this.webUrl; + } else { + this.webUrl = "https://smith.langchain.com"; + return this.webUrl; + } + } + get headers() { + const headers = { + "User-Agent": `langsmith-js/${__version__}` + }; + if (this.apiKey) { + headers["x-api-key"] = `${this.apiKey}`; + } + return headers; + } + _getPlatformEndpointPath(path) { + const needsV1Prefix = this.apiUrl.slice(-3) !== "/v1" && this.apiUrl.slice(-4) !== "/v1/"; + return needsV1Prefix ? `/v1/platform/${path}` : `/platform/${path}`; + } + async processInputs(inputs) { + if (this.hideInputs === false) { + return inputs; + } + if (this.hideInputs === true) { + return {}; + } + if (typeof this.hideInputs === "function") { + return this.hideInputs(inputs); + } + return inputs; + } + async processOutputs(outputs) { + if (this.hideOutputs === false) { + return outputs; + } + if (this.hideOutputs === true) { + return {}; + } + if (typeof this.hideOutputs === "function") { + return this.hideOutputs(outputs); + } + return outputs; + } + async prepareRunCreateOrUpdateInputs(run) { + const runParams = { ...run }; + if (runParams.inputs !== void 0) { + runParams.inputs = await this.processInputs(runParams.inputs); + } + if (runParams.outputs !== void 0) { + runParams.outputs = await this.processOutputs(runParams.outputs); + } + return runParams; + } + async _getResponse(path, queryParams) { + const paramsString = queryParams?.toString() ?? ""; + const url = `${this.apiUrl}${path}?${paramsString}`; + const response = await this.caller.call(_getFetchImplementation(this.debug), url, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, `Failed to fetch ${path}`); + return response; + } + async _get(path, queryParams) { + const response = await this._getResponse(path, queryParams); + return response.json(); + } + async *_getPaginated(path, queryParams = new URLSearchParams(), transform) { + let offset = Number(queryParams.get("offset")) || 0; + const limit = Number(queryParams.get("limit")) || 100; + while (true) { + queryParams.set("offset", String(offset)); + queryParams.set("limit", String(limit)); + const url = `${this.apiUrl}${path}?${queryParams}`; + const response = await this.caller.call(_getFetchImplementation(this.debug), url, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, `Failed to fetch ${path}`); + const items = transform ? transform(await response.json()) : await response.json(); + if (items.length === 0) { + break; + } + yield items; + if (items.length < limit) { + break; + } + offset += items.length; + } + } + async *_getCursorPaginatedList(path, body = null, requestMethod = "POST", dataKey = "runs") { + const bodyParams = body ? { ...body } : {}; + while (true) { + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}${path}`, { + method: requestMethod, + headers: { ...this.headers, "Content-Type": "application/json" }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body: JSON.stringify(bodyParams) + }); + const responseBody = await response.json(); + if (!responseBody) { + break; + } + if (!responseBody[dataKey]) { + break; + } + yield responseBody[dataKey]; + const cursors = responseBody.cursors; + if (!cursors) { + break; + } + if (!cursors.next) { + break; + } + bodyParams.cursor = cursors.next; + } + } + // Allows mocking for tests + _shouldSample() { + if (this.tracingSampleRate === void 0) { + return true; + } + return Math.random() < this.tracingSampleRate; + } + _filterForSampling(runs, patch = false) { + if (this.tracingSampleRate === void 0) { + return runs; + } + if (patch) { + const sampled = []; + for (const run of runs) { + if (!this.filteredPostUuids.has(run.trace_id)) { + sampled.push(run); + } else if (run.id === run.trace_id) { + this.filteredPostUuids.delete(run.trace_id); + } + } + return sampled; + } else { + const sampled = []; + for (const run of runs) { + const traceId = run.trace_id ?? run.id; + if (this.filteredPostUuids.has(traceId)) { + continue; + } + if (run.id === traceId) { + if (this._shouldSample()) { + sampled.push(run); + } else { + this.filteredPostUuids.add(traceId); + } + } else { + sampled.push(run); + } + } + return sampled; + } + } + async _getBatchSizeLimitBytes() { + const serverInfo = await this._ensureServerInfo(); + return this.batchSizeBytesLimit ?? serverInfo.batch_ingest_config?.size_limit_bytes ?? DEFAULT_UNCOMPRESSED_BATCH_SIZE_LIMIT_BYTES; + } + async _getDatasetExamplesMultiPartSupport() { + const serverInfo = await this._ensureServerInfo(); + return serverInfo.instance_flags?.dataset_examples_multipart_enabled ?? false; + } + drainAutoBatchQueue(batchSizeLimit) { + const promises = []; + while (this.autoBatchQueue.items.length > 0) { + const [batch, done] = this.autoBatchQueue.pop(batchSizeLimit); + if (!batch.length) { + done(); + break; + } + const batchesByDestination = batch.reduce((acc, item) => { + const apiUrl = item.apiUrl ?? this.apiUrl; + const apiKey = item.apiKey ?? this.apiKey; + const isDefault = item.apiKey === this.apiKey && item.apiUrl === this.apiUrl; + const batchKey = isDefault ? "default" : `${apiUrl}|${apiKey}`; + if (!acc[batchKey]) { + acc[batchKey] = []; + } + acc[batchKey].push(item); + return acc; + }, {}); + const batchPromises = []; + for (const [batchKey, batch2] of Object.entries(batchesByDestination)) { + const batchPromise = this._processBatch(batch2, { + apiUrl: batchKey === "default" ? void 0 : batchKey.split("|")[0], + apiKey: batchKey === "default" ? void 0 : batchKey.split("|")[1] + }); + batchPromises.push(batchPromise); + } + const allBatchesPromise = Promise.all(batchPromises).finally(done); + promises.push(allBatchesPromise); + } + return Promise.all(promises); + } + async _processBatch(batch, options) { + if (!batch.length) { + return; + } + try { + if (this.langSmithToOTELTranslator !== void 0) { + this._sendBatchToOTELTranslator(batch); + } else { + const ingestParams = { + runCreates: batch.filter((item) => item.action === "create").map((item) => item.item), + runUpdates: batch.filter((item) => item.action === "update").map((item) => item.item) + }; + const serverInfo = await this._ensureServerInfo(); + if (serverInfo?.batch_ingest_config?.use_multipart_endpoint) { + const useGzip = serverInfo?.instance_flags?.gzip_body_enabled; + await this.multipartIngestRuns(ingestParams, { ...options, useGzip }); + } else { + await this.batchIngestRuns(ingestParams, options); + } + } + } catch (e) { + console.error("Error exporting batch:", e); + } + } + _sendBatchToOTELTranslator(batch) { + if (this.langSmithToOTELTranslator !== void 0) { + const otelContextMap = /* @__PURE__ */ new Map(); + const operations = []; + for (const item of batch) { + if (item.item.id && item.otelContext) { + otelContextMap.set(item.item.id, item.otelContext); + if (item.action === "create") { + operations.push({ + operation: "post", + id: item.item.id, + trace_id: item.item.trace_id ?? item.item.id, + run: item.item + }); + } else { + operations.push({ + operation: "patch", + id: item.item.id, + trace_id: item.item.trace_id ?? item.item.id, + run: item.item + }); + } + } + } + this.langSmithToOTELTranslator.exportBatch(operations, otelContextMap); + } + } + async processRunOperation(item) { + clearTimeout(this.autoBatchTimeout); + this.autoBatchTimeout = void 0; + item.item = mergeRuntimeEnvIntoRun(item.item); + const itemPromise = this.autoBatchQueue.push(item); + if (this.manualFlushMode) { + return itemPromise; + } + const sizeLimitBytes = await this._getBatchSizeLimitBytes(); + if (this.autoBatchQueue.sizeBytes > sizeLimitBytes) { + void this.drainAutoBatchQueue(sizeLimitBytes); + } + if (this.autoBatchQueue.items.length > 0) { + this.autoBatchTimeout = setTimeout(() => { + this.autoBatchTimeout = void 0; + void this.drainAutoBatchQueue(sizeLimitBytes); + }, this.autoBatchAggregationDelayMs); + } + return itemPromise; + } + async _getServerInfo() { + const response = await this.caller.call(async () => { + const res = await _getFetchImplementation(this.debug)(`${this.apiUrl}/info`, { + method: "GET", + headers: { Accept: "application/json" }, + signal: AbortSignal.timeout(SERVER_INFO_REQUEST_TIMEOUT_MS), + ...this.fetchOptions + }); + await raiseForStatus(res, "get server info"); + return res; + }); + const json = await response.json(); + if (this.debug) { + console.log("\n=== LangSmith Server Configuration ===\n" + JSON.stringify(json, null, 2) + "\n"); + } + return json; + } + async _ensureServerInfo() { + if (this._getServerInfoPromise === void 0) { + this._getServerInfoPromise = (async () => { + if (this._serverInfo === void 0) { + try { + this._serverInfo = await this._getServerInfo(); + } catch (e) { + console.warn(`[WARNING]: LangSmith failed to fetch info on supported operations with status code ${e.status}. Falling back to batch operations and default limits.`); + } + } + return this._serverInfo ?? {}; + })(); + } + return this._getServerInfoPromise.then((serverInfo) => { + if (this._serverInfo === void 0) { + this._getServerInfoPromise = void 0; + } + return serverInfo; + }); + } + async _getSettings() { + if (!this.settings) { + this.settings = this._get("/settings"); + } + return await this.settings; + } + /** + * Flushes current queued traces. + */ + async flush() { + const sizeLimitBytes = await this._getBatchSizeLimitBytes(); + await this.drainAutoBatchQueue(sizeLimitBytes); + } + _cloneCurrentOTELContext() { + const otel_trace = getOTELTrace(); + const otel_context = getOTELContext(); + if (this.langSmithToOTELTranslator !== void 0) { + const currentSpan = otel_trace.getActiveSpan(); + if (currentSpan) { + return otel_trace.setSpan(otel_context.active(), currentSpan); + } + } + return void 0; + } + async createRun(run, options) { + if (!this._filterForSampling([run]).length) { + return; + } + const headers = { + ...this.headers, + "Content-Type": "application/json" + }; + const session_name = run.project_name; + delete run.project_name; + const runCreate = await this.prepareRunCreateOrUpdateInputs({ + session_name, + ...run, + start_time: run.start_time ?? Date.now() + }); + if (this.autoBatchTracing && runCreate.trace_id !== void 0 && runCreate.dotted_order !== void 0) { + const otelContext = this._cloneCurrentOTELContext(); + void this.processRunOperation({ + action: "create", + item: runCreate, + otelContext, + apiKey: options?.apiKey, + apiUrl: options?.apiUrl + }).catch(console.error); + return; + } + const mergedRunCreateParam = mergeRuntimeEnvIntoRun(runCreate); + if (options?.apiKey !== void 0) { + headers["x-api-key"] = options.apiKey; + } + const response = await this.caller.call(_getFetchImplementation(this.debug), `${options?.apiUrl ?? this.apiUrl}/runs`, { + method: "POST", + headers, + body: serialize(mergedRunCreateParam, `Creating run with id: ${mergedRunCreateParam.id}`), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, "create run", true); + } + /** + * Batch ingest/upsert multiple runs in the Langsmith system. + * @param runs + */ + async batchIngestRuns({ runCreates, runUpdates }, options) { + if (runCreates === void 0 && runUpdates === void 0) { + return; + } + let preparedCreateParams = await Promise.all(runCreates?.map((create) => this.prepareRunCreateOrUpdateInputs(create)) ?? []); + let preparedUpdateParams = await Promise.all(runUpdates?.map((update) => this.prepareRunCreateOrUpdateInputs(update)) ?? []); + if (preparedCreateParams.length > 0 && preparedUpdateParams.length > 0) { + const createById = preparedCreateParams.reduce((params, run) => { + if (!run.id) { + return params; + } + params[run.id] = run; + return params; + }, {}); + const standaloneUpdates = []; + for (const updateParam of preparedUpdateParams) { + if (updateParam.id !== void 0 && createById[updateParam.id]) { + createById[updateParam.id] = { + ...createById[updateParam.id], + ...updateParam + }; + } else { + standaloneUpdates.push(updateParam); + } + } + preparedCreateParams = Object.values(createById); + preparedUpdateParams = standaloneUpdates; + } + const rawBatch = { + post: preparedCreateParams, + patch: preparedUpdateParams + }; + if (!rawBatch.post.length && !rawBatch.patch.length) { + return; + } + const batchChunks = { + post: [], + patch: [] + }; + for (const k of ["post", "patch"]) { + const key = k; + const batchItems = rawBatch[key].reverse(); + let batchItem = batchItems.pop(); + while (batchItem !== void 0) { + batchChunks[key].push(batchItem); + batchItem = batchItems.pop(); + } + } + if (batchChunks.post.length > 0 || batchChunks.patch.length > 0) { + const runIds = batchChunks.post.map((item) => item.id).concat(batchChunks.patch.map((item) => item.id)).join(","); + await this._postBatchIngestRuns(serialize(batchChunks, `Ingesting runs with ids: ${runIds}`), options); + } + } + async _postBatchIngestRuns(body, options) { + const headers = { + ...this.headers, + "Content-Type": "application/json", + Accept: "application/json" + }; + if (options?.apiKey !== void 0) { + headers["x-api-key"] = options.apiKey; + } + const response = await this.batchIngestCaller.call(_getFetchImplementation(this.debug), `${options?.apiUrl ?? this.apiUrl}/runs/batch`, { + method: "POST", + headers, + body, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, "batch create run", true); + } + /** + * Batch ingest/upsert multiple runs in the Langsmith system. + * @param runs + */ + async multipartIngestRuns({ runCreates, runUpdates }, options) { + if (runCreates === void 0 && runUpdates === void 0) { + return; + } + const allAttachments = {}; + let preparedCreateParams = []; + for (const create of runCreates ?? []) { + const preparedCreate = await this.prepareRunCreateOrUpdateInputs(create); + if (preparedCreate.id !== void 0 && preparedCreate.attachments !== void 0) { + allAttachments[preparedCreate.id] = preparedCreate.attachments; + } + delete preparedCreate.attachments; + preparedCreateParams.push(preparedCreate); + } + let preparedUpdateParams = []; + for (const update of runUpdates ?? []) { + preparedUpdateParams.push(await this.prepareRunCreateOrUpdateInputs(update)); + } + const invalidRunCreate = preparedCreateParams.find((runCreate) => { + return runCreate.trace_id === void 0 || runCreate.dotted_order === void 0; + }); + if (invalidRunCreate !== void 0) { + throw new Error(`Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run`); + } + const invalidRunUpdate = preparedUpdateParams.find((runUpdate) => { + return runUpdate.trace_id === void 0 || runUpdate.dotted_order === void 0; + }); + if (invalidRunUpdate !== void 0) { + throw new Error(`Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run`); + } + if (preparedCreateParams.length > 0 && preparedUpdateParams.length > 0) { + const createById = preparedCreateParams.reduce((params, run) => { + if (!run.id) { + return params; + } + params[run.id] = run; + return params; + }, {}); + const standaloneUpdates = []; + for (const updateParam of preparedUpdateParams) { + if (updateParam.id !== void 0 && createById[updateParam.id]) { + createById[updateParam.id] = { + ...createById[updateParam.id], + ...updateParam + }; + } else { + standaloneUpdates.push(updateParam); + } + } + preparedCreateParams = Object.values(createById); + preparedUpdateParams = standaloneUpdates; + } + if (preparedCreateParams.length === 0 && preparedUpdateParams.length === 0) { + return; + } + const accumulatedContext = []; + const accumulatedParts = []; + for (const [method, payloads] of [ + ["post", preparedCreateParams], + ["patch", preparedUpdateParams] + ]) { + for (const originalPayload of payloads) { + const { inputs, outputs, events, extra, error, serialized, attachments, ...payload } = originalPayload; + const fields = { inputs, outputs, events, extra, error, serialized }; + const stringifiedPayload = serialize(payload, `Serializing for multipart ingestion of run with id: ${payload.id}`); + accumulatedParts.push({ + name: `${method}.${payload.id}`, + payload: new Blob([stringifiedPayload], { + type: `application/json; length=${stringifiedPayload.length}` + // encoding=gzip + }) + }); + for (const [key, value] of Object.entries(fields)) { + if (value === void 0) { + continue; + } + const stringifiedValue = serialize(value, `Serializing ${key} for multipart ingestion of run with id: ${payload.id}`); + accumulatedParts.push({ + name: `${method}.${payload.id}.${key}`, + payload: new Blob([stringifiedValue], { + type: `application/json; length=${stringifiedValue.length}` + }) + }); + } + if (payload.id !== void 0) { + const attachments2 = allAttachments[payload.id]; + if (attachments2) { + delete allAttachments[payload.id]; + for (const [name, attachment] of Object.entries(attachments2)) { + let contentType; + let content; + if (Array.isArray(attachment)) { + [contentType, content] = attachment; + } else { + contentType = attachment.mimeType; + content = attachment.data; + } + if (name.includes(".")) { + console.warn(`Skipping attachment '${name}' for run ${payload.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`); + continue; + } + accumulatedParts.push({ + name: `attachment.${payload.id}.${name}`, + payload: new Blob([content], { + type: `${contentType}; length=${content.byteLength}` + }) + }); + } + } + } + accumulatedContext.push(`trace=${payload.trace_id},id=${payload.id}`); + } + } + await this._sendMultipartRequest(accumulatedParts, accumulatedContext.join("; "), options); + } + async _createNodeFetchBody(parts, boundary) { + const chunks = []; + for (const part of parts) { + chunks.push(new Blob([`--${boundary}\r +`])); + chunks.push(new Blob([ + `Content-Disposition: form-data; name="${part.name}"\r +`, + `Content-Type: ${part.payload.type}\r +\r +` + ])); + chunks.push(part.payload); + chunks.push(new Blob(["\r\n"])); + } + chunks.push(new Blob([`--${boundary}--\r +`])); + const body = new Blob(chunks); + const arrayBuffer = await body.arrayBuffer(); + return arrayBuffer; + } + async _createMultipartStream(parts, boundary) { + const encoder2 = new TextEncoder(); + const stream = new ReadableStream({ + async start(controller) { + const writeChunk = async (chunk) => { + if (typeof chunk === "string") { + controller.enqueue(encoder2.encode(chunk)); + } else { + controller.enqueue(chunk); + } + }; + for (const part of parts) { + await writeChunk(`--${boundary}\r +`); + await writeChunk(`Content-Disposition: form-data; name="${part.name}"\r +`); + await writeChunk(`Content-Type: ${part.payload.type}\r +\r +`); + const payloadStream = part.payload.stream(); + const reader = payloadStream.getReader(); + try { + let result; + while (!(result = await reader.read()).done) { + controller.enqueue(result.value); + } + } finally { + reader.releaseLock(); + } + await writeChunk("\r\n"); + } + await writeChunk(`--${boundary}--\r +`); + controller.close(); + } + }); + return stream; + } + async _sendMultipartRequest(parts, context, options) { + const boundary = "----LangSmithFormBoundary" + Math.random().toString(36).slice(2); + const isNodeFetch = _globalFetchImplementationIsNodeFetch(); + const buildBuffered = () => this._createNodeFetchBody(parts, boundary); + const buildStream = () => this._createMultipartStream(parts, boundary); + const send = async (body) => { + const headers = { + ...this.headers, + "Content-Type": `multipart/form-data; boundary=${boundary}` + }; + if (options?.apiKey !== void 0) { + headers["x-api-key"] = options.apiKey; + } + let transformedBody = body; + if (options?.useGzip && typeof body === "object" && "pipeThrough" in body) { + transformedBody = body.pipeThrough(new CompressionStream("gzip")); + headers["Content-Encoding"] = "gzip"; + } + return this.batchIngestCaller.call(_getFetchImplementation(this.debug), `${options?.apiUrl ?? this.apiUrl}/runs/multipart`, { + method: "POST", + headers, + body: transformedBody, + duplex: "half", + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + }; + try { + let res; + let streamedAttempt = false; + if (!isNodeFetch && !this.multipartStreamingDisabled) { + streamedAttempt = true; + res = await send(await buildStream()); + } else { + res = await send(await buildBuffered()); + } + if ((!this.multipartStreamingDisabled || streamedAttempt) && res.status === 422 && (options?.apiUrl ?? this.apiUrl) !== DEFAULT_API_URL) { + console.warn(`Streaming multipart upload to ${options?.apiUrl ?? this.apiUrl}/runs/multipart failed. This usually means the host does not support chunked uploads. Retrying with a buffered upload for operation "${context}".`); + this.multipartStreamingDisabled = true; + res = await send(await buildBuffered()); + } + await raiseForStatus(res, "ingest multipart runs", true); + } catch (e) { + console.warn(`${e.message.trim()} + +Context: ${context}`); + } + } + async updateRun(runId, run, options) { + assertUuid(runId); + if (run.inputs) { + run.inputs = await this.processInputs(run.inputs); + } + if (run.outputs) { + run.outputs = await this.processOutputs(run.outputs); + } + const data = { ...run, id: runId }; + if (!this._filterForSampling([data], true).length) { + return; + } + if (this.autoBatchTracing && data.trace_id !== void 0 && data.dotted_order !== void 0) { + const otelContext = this._cloneCurrentOTELContext(); + if (run.end_time !== void 0 && data.parent_run_id === void 0 && this.blockOnRootRunFinalization && !this.manualFlushMode) { + await this.processRunOperation({ + action: "update", + item: data, + otelContext, + apiKey: options?.apiKey, + apiUrl: options?.apiUrl + }).catch(console.error); + return; + } else { + void this.processRunOperation({ + action: "update", + item: data, + otelContext, + apiKey: options?.apiKey, + apiUrl: options?.apiUrl + }).catch(console.error); + } + return; + } + const headers = { + ...this.headers, + "Content-Type": "application/json" + }; + if (options?.apiKey !== void 0) { + headers["x-api-key"] = options.apiKey; + } + const response = await this.caller.call(_getFetchImplementation(this.debug), `${options?.apiUrl ?? this.apiUrl}/runs/${runId}`, { + method: "PATCH", + headers, + body: serialize(run, `Serializing payload to update run with id: ${runId}`), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, "update run", true); + } + async readRun(runId, { loadChildRuns } = { loadChildRuns: false }) { + assertUuid(runId); + let run = await this._get(`/runs/${runId}`); + if (loadChildRuns) { + run = await this._loadChildRuns(run); + } + return run; + } + async getRunUrl({ runId, run, projectOpts }) { + if (run !== void 0) { + let sessionId; + if (run.session_id) { + sessionId = run.session_id; + } else if (projectOpts?.projectName) { + sessionId = (await this.readProject({ projectName: projectOpts?.projectName })).id; + } else if (projectOpts?.projectId) { + sessionId = projectOpts?.projectId; + } else { + const project = await this.readProject({ + projectName: getLangSmithEnvironmentVariable("PROJECT") || "default" + }); + sessionId = project.id; + } + const tenantId = await this._getTenantId(); + return `${this.getHostUrl()}/o/${tenantId}/projects/p/${sessionId}/r/${run.id}?poll=true`; + } else if (runId !== void 0) { + const run_ = await this.readRun(runId); + if (!run_.app_path) { + throw new Error(`Run ${runId} has no app_path`); + } + const baseUrl = this.getHostUrl(); + return `${baseUrl}${run_.app_path}`; + } else { + throw new Error("Must provide either runId or run"); + } + } + async _loadChildRuns(run) { + const childRuns = await toArray(this.listRuns({ + isRoot: false, + projectId: run.session_id, + traceId: run.trace_id + })); + const treemap = {}; + const runs = {}; + childRuns.sort((a, b) => (a?.dotted_order ?? "").localeCompare(b?.dotted_order ?? "")); + for (const childRun of childRuns) { + if (childRun.parent_run_id === null || childRun.parent_run_id === void 0) { + throw new Error(`Child run ${childRun.id} has no parent`); + } + if (childRun.dotted_order?.startsWith(run.dotted_order ?? "") && childRun.id !== run.id) { + if (!(childRun.parent_run_id in treemap)) { + treemap[childRun.parent_run_id] = []; + } + treemap[childRun.parent_run_id].push(childRun); + runs[childRun.id] = childRun; + } + } + run.child_runs = treemap[run.id] || []; + for (const runId in treemap) { + if (runId !== run.id) { + runs[runId].child_runs = treemap[runId]; + } + } + return run; + } + /** + * List runs from the LangSmith server. + * @param projectId - The ID of the project to filter by. + * @param projectName - The name of the project to filter by. + * @param parentRunId - The ID of the parent run to filter by. + * @param traceId - The ID of the trace to filter by. + * @param referenceExampleId - The ID of the reference example to filter by. + * @param startTime - The start time to filter by. + * @param isRoot - Indicates whether to only return root runs. + * @param runType - The run type to filter by. + * @param error - Indicates whether to filter by error runs. + * @param id - The ID of the run to filter by. + * @param query - The query string to filter by. + * @param filter - The filter string to apply to the run spans. + * @param traceFilter - The filter string to apply on the root run of the trace. + * @param treeFilter - The filter string to apply on other runs in the trace. + * @param limit - The maximum number of runs to retrieve. + * @returns {AsyncIterable} - The runs. + * + * @example + * // List all runs in a project + * const projectRuns = client.listRuns({ projectName: "" }); + * + * @example + * // List LLM and Chat runs in the last 24 hours + * const todaysLLMRuns = client.listRuns({ + * projectName: "", + * start_time: new Date(Date.now() - 24 * 60 * 60 * 1000), + * run_type: "llm", + * }); + * + * @example + * // List traces in a project + * const rootRuns = client.listRuns({ + * projectName: "", + * execution_order: 1, + * }); + * + * @example + * // List runs without errors + * const correctRuns = client.listRuns({ + * projectName: "", + * error: false, + * }); + * + * @example + * // List runs by run ID + * const runIds = [ + * "a36092d2-4ad5-4fb4-9c0d-0dba9a2ed836", + * "9398e6be-964f-4aa4-8ae9-ad78cd4b7074", + * ]; + * const selectedRuns = client.listRuns({ run_ids: runIds }); + * + * @example + * // List all "chain" type runs that took more than 10 seconds and had `total_tokens` greater than 5000 + * const chainRuns = client.listRuns({ + * projectName: "", + * filter: 'and(eq(run_type, "chain"), gt(latency, 10), gt(total_tokens, 5000))', + * }); + * + * @example + * // List all runs called "extractor" whose root of the trace was assigned feedback "user_score" score of 1 + * const goodExtractorRuns = client.listRuns({ + * projectName: "", + * filter: 'eq(name, "extractor")', + * traceFilter: 'and(eq(feedback_key, "user_score"), eq(feedback_score, 1))', + * }); + * + * @example + * // List all runs that started after a specific timestamp and either have "error" not equal to null or a "Correctness" feedback score equal to 0 + * const complexRuns = client.listRuns({ + * projectName: "", + * filter: 'and(gt(start_time, "2023-07-15T12:34:56Z"), or(neq(error, null), and(eq(feedback_key, "Correctness"), eq(feedback_score, 0.0))))', + * }); + * + * @example + * // List all runs where `tags` include "experimental" or "beta" and `latency` is greater than 2 seconds + * const taggedRuns = client.listRuns({ + * projectName: "", + * filter: 'and(or(has(tags, "experimental"), has(tags, "beta")), gt(latency, 2))', + * }); + */ + async *listRuns(props) { + const { projectId, projectName, parentRunId, traceId, referenceExampleId, startTime, executionOrder, isRoot, runType, error, id, query, filter, traceFilter, treeFilter, limit, select, order } = props; + let projectIds = []; + if (projectId) { + projectIds = Array.isArray(projectId) ? projectId : [projectId]; + } + if (projectName) { + const projectNames = Array.isArray(projectName) ? projectName : [projectName]; + const projectIds_ = await Promise.all(projectNames.map((name) => this.readProject({ projectName: name }).then((project) => project.id))); + projectIds.push(...projectIds_); + } + const default_select = [ + "app_path", + "completion_cost", + "completion_tokens", + "dotted_order", + "end_time", + "error", + "events", + "extra", + "feedback_stats", + "first_token_time", + "id", + "inputs", + "name", + "outputs", + "parent_run_id", + "parent_run_ids", + "prompt_cost", + "prompt_tokens", + "reference_example_id", + "run_type", + "session_id", + "start_time", + "status", + "tags", + "total_cost", + "total_tokens", + "trace_id" + ]; + const body = { + session: projectIds.length ? projectIds : null, + run_type: runType, + reference_example: referenceExampleId, + query, + filter, + trace_filter: traceFilter, + tree_filter: treeFilter, + execution_order: executionOrder, + parent_run: parentRunId, + start_time: startTime ? startTime.toISOString() : null, + error, + id, + limit, + trace: traceId, + select: select ? select : default_select, + is_root: isRoot, + order + }; + let runsYielded = 0; + for await (const runs of this._getCursorPaginatedList("/runs/query", body)) { + if (limit) { + if (runsYielded >= limit) { + break; + } + if (runs.length + runsYielded > limit) { + const newRuns = runs.slice(0, limit - runsYielded); + yield* newRuns; + break; + } + runsYielded += runs.length; + yield* runs; + } else { + yield* runs; + } + } + } + async *listGroupRuns(props) { + const { projectId, projectName, groupBy, filter, startTime, endTime, limit, offset } = props; + const sessionId = projectId || (await this.readProject({ projectName })).id; + const baseBody = { + session_id: sessionId, + group_by: groupBy, + filter, + start_time: startTime ? startTime.toISOString() : null, + end_time: endTime ? endTime.toISOString() : null, + limit: Number(limit) || 100 + }; + let currentOffset = Number(offset) || 0; + const path = "/runs/group"; + const url = `${this.apiUrl}${path}`; + while (true) { + const currentBody = { + ...baseBody, + offset: currentOffset + }; + const filteredPayload = Object.fromEntries(Object.entries(currentBody).filter(([_, value]) => value !== void 0)); + const response = await this.caller.call(_getFetchImplementation(), url, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(filteredPayload), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, `Failed to fetch ${path}`); + const items = await response.json(); + const { groups, total } = items; + if (groups.length === 0) { + break; + } + for (const thread of groups) { + yield thread; + } + currentOffset += groups.length; + if (currentOffset >= total) { + break; + } + } + } + async getRunStats({ id, trace, parentRun, runType, projectNames, projectIds, referenceExampleIds, startTime, endTime, error, query, filter, traceFilter, treeFilter, isRoot, dataSourceType }) { + let projectIds_ = projectIds || []; + if (projectNames) { + projectIds_ = [ + ...projectIds || [], + ...await Promise.all(projectNames.map((name) => this.readProject({ projectName: name }).then((project) => project.id))) + ]; + } + const payload = { + id, + trace, + parent_run: parentRun, + run_type: runType, + session: projectIds_, + reference_example: referenceExampleIds, + start_time: startTime, + end_time: endTime, + error, + query, + filter, + trace_filter: traceFilter, + tree_filter: treeFilter, + is_root: isRoot, + data_source_type: dataSourceType + }; + const filteredPayload = Object.fromEntries(Object.entries(payload).filter(([_, value]) => value !== void 0)); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/runs/stats`, { + method: "POST", + headers: this.headers, + body: JSON.stringify(filteredPayload), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + const result = await response.json(); + return result; + } + async shareRun(runId, { shareId } = {}) { + const data = { + run_id: runId, + share_token: shareId || v4_default() + }; + assertUuid(runId); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/runs/${runId}/share`, { + method: "PUT", + headers: this.headers, + body: JSON.stringify(data), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + const result = await response.json(); + if (result === null || !("share_token" in result)) { + throw new Error("Invalid response from server"); + } + return `${this.getHostUrl()}/public/${result["share_token"]}/r`; + } + async unshareRun(runId) { + assertUuid(runId); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/runs/${runId}/share`, { + method: "DELETE", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, "unshare run", true); + } + async readRunSharedLink(runId) { + assertUuid(runId); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/runs/${runId}/share`, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + const result = await response.json(); + if (result === null || !("share_token" in result)) { + return void 0; + } + return `${this.getHostUrl()}/public/${result["share_token"]}/r`; + } + async listSharedRuns(shareToken, { runIds } = {}) { + const queryParams = new URLSearchParams({ + share_token: shareToken + }); + if (runIds !== void 0) { + for (const runId of runIds) { + queryParams.append("id", runId); + } + } + assertUuid(shareToken); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/public/${shareToken}/runs${queryParams}`, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + const runs = await response.json(); + return runs; + } + async readDatasetSharedSchema(datasetId, datasetName) { + if (!datasetId && !datasetName) { + throw new Error("Either datasetId or datasetName must be given"); + } + if (!datasetId) { + const dataset = await this.readDataset({ datasetName }); + datasetId = dataset.id; + } + assertUuid(datasetId); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${datasetId}/share`, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + const shareSchema = await response.json(); + shareSchema.url = `${this.getHostUrl()}/public/${shareSchema.share_token}/d`; + return shareSchema; + } + async shareDataset(datasetId, datasetName) { + if (!datasetId && !datasetName) { + throw new Error("Either datasetId or datasetName must be given"); + } + if (!datasetId) { + const dataset = await this.readDataset({ datasetName }); + datasetId = dataset.id; + } + const data = { + dataset_id: datasetId + }; + assertUuid(datasetId); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${datasetId}/share`, { + method: "PUT", + headers: this.headers, + body: JSON.stringify(data), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + const shareSchema = await response.json(); + shareSchema.url = `${this.getHostUrl()}/public/${shareSchema.share_token}/d`; + return shareSchema; + } + async unshareDataset(datasetId) { + assertUuid(datasetId); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${datasetId}/share`, { + method: "DELETE", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, "unshare dataset", true); + } + async readSharedDataset(shareToken) { + assertUuid(shareToken); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/public/${shareToken}/datasets`, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + const dataset = await response.json(); + return dataset; + } + /** + * Get shared examples. + * + * @param {string} shareToken The share token to get examples for. A share token is the UUID (or LangSmith URL, including UUID) generated when explicitly marking an example as public. + * @param {Object} [options] Additional options for listing the examples. + * @param {string[] | undefined} [options.exampleIds] A list of example IDs to filter by. + * @returns {Promise} The shared examples. + */ + async listSharedExamples(shareToken, options) { + const params = {}; + if (options?.exampleIds) { + params.id = options.exampleIds; + } + const urlParams = new URLSearchParams(); + Object.entries(params).forEach(([key, value]) => { + if (Array.isArray(value)) { + value.forEach((v) => urlParams.append(key, v)); + } else { + urlParams.append(key, value); + } + }); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/public/${shareToken}/examples?${urlParams.toString()}`, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + const result = await response.json(); + if (!response.ok) { + if ("detail" in result) { + throw new Error(`Failed to list shared examples. +Status: ${response.status} +Message: ${Array.isArray(result.detail) ? result.detail.join("\n") : "Unspecified error"}`); + } + throw new Error(`Failed to list shared examples: ${response.status} ${response.statusText}`); + } + return result.map((example) => ({ + ...example, + _hostUrl: this.getHostUrl() + })); + } + async createProject({ projectName, description = null, metadata = null, upsert = false, projectExtra = null, referenceDatasetId = null }) { + const upsert_ = upsert ? `?upsert=true` : ""; + const endpoint = `${this.apiUrl}/sessions${upsert_}`; + const extra = projectExtra || {}; + if (metadata) { + extra["metadata"] = metadata; + } + const body = { + name: projectName, + extra, + description + }; + if (referenceDatasetId !== null) { + body["reference_dataset_id"] = referenceDatasetId; + } + const response = await this.caller.call(_getFetchImplementation(this.debug), endpoint, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(body), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, "create project"); + const result = await response.json(); + return result; + } + async updateProject(projectId, { name = null, description = null, metadata = null, projectExtra = null, endTime = null }) { + const endpoint = `${this.apiUrl}/sessions/${projectId}`; + let extra = projectExtra; + if (metadata) { + extra = { ...extra || {}, metadata }; + } + const body = { + name, + extra, + description, + end_time: endTime ? new Date(endTime).toISOString() : null + }; + const response = await this.caller.call(_getFetchImplementation(this.debug), endpoint, { + method: "PATCH", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(body), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, "update project"); + const result = await response.json(); + return result; + } + async hasProject({ projectId, projectName }) { + let path = "/sessions"; + const params = new URLSearchParams(); + if (projectId !== void 0 && projectName !== void 0) { + throw new Error("Must provide either projectName or projectId, not both"); + } else if (projectId !== void 0) { + assertUuid(projectId); + path += `/${projectId}`; + } else if (projectName !== void 0) { + params.append("name", projectName); + } else { + throw new Error("Must provide projectName or projectId"); + } + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}${path}?${params}`, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + try { + const result = await response.json(); + if (!response.ok) { + return false; + } + if (Array.isArray(result)) { + return result.length > 0; + } + return true; + } catch (e) { + return false; + } + } + async readProject({ projectId, projectName, includeStats }) { + let path = "/sessions"; + const params = new URLSearchParams(); + if (projectId !== void 0 && projectName !== void 0) { + throw new Error("Must provide either projectName or projectId, not both"); + } else if (projectId !== void 0) { + assertUuid(projectId); + path += `/${projectId}`; + } else if (projectName !== void 0) { + params.append("name", projectName); + } else { + throw new Error("Must provide projectName or projectId"); + } + if (includeStats !== void 0) { + params.append("include_stats", includeStats.toString()); + } + const response = await this._get(path, params); + let result; + if (Array.isArray(response)) { + if (response.length === 0) { + throw new Error(`Project[id=${projectId}, name=${projectName}] not found`); + } + result = response[0]; + } else { + result = response; + } + return result; + } + async getProjectUrl({ projectId, projectName }) { + if (projectId === void 0 && projectName === void 0) { + throw new Error("Must provide either projectName or projectId"); + } + const project = await this.readProject({ projectId, projectName }); + const tenantId = await this._getTenantId(); + return `${this.getHostUrl()}/o/${tenantId}/projects/p/${project.id}`; + } + async getDatasetUrl({ datasetId, datasetName }) { + if (datasetId === void 0 && datasetName === void 0) { + throw new Error("Must provide either datasetName or datasetId"); + } + const dataset = await this.readDataset({ datasetId, datasetName }); + const tenantId = await this._getTenantId(); + return `${this.getHostUrl()}/o/${tenantId}/datasets/${dataset.id}`; + } + async _getTenantId() { + if (this._tenantId !== null) { + return this._tenantId; + } + const queryParams = new URLSearchParams({ limit: "1" }); + for await (const projects of this._getPaginated("/sessions", queryParams)) { + this._tenantId = projects[0].tenant_id; + return projects[0].tenant_id; + } + throw new Error("No projects found to resolve tenant."); + } + async *listProjects({ projectIds, name, nameContains, referenceDatasetId, referenceDatasetName, referenceFree, metadata } = {}) { + const params = new URLSearchParams(); + if (projectIds !== void 0) { + for (const projectId of projectIds) { + params.append("id", projectId); + } + } + if (name !== void 0) { + params.append("name", name); + } + if (nameContains !== void 0) { + params.append("name_contains", nameContains); + } + if (referenceDatasetId !== void 0) { + params.append("reference_dataset", referenceDatasetId); + } else if (referenceDatasetName !== void 0) { + const dataset = await this.readDataset({ + datasetName: referenceDatasetName + }); + params.append("reference_dataset", dataset.id); + } + if (referenceFree !== void 0) { + params.append("reference_free", referenceFree.toString()); + } + if (metadata !== void 0) { + params.append("metadata", JSON.stringify(metadata)); + } + for await (const projects of this._getPaginated("/sessions", params)) { + yield* projects; + } + } + async deleteProject({ projectId, projectName }) { + let projectId_; + if (projectId === void 0 && projectName === void 0) { + throw new Error("Must provide projectName or projectId"); + } else if (projectId !== void 0 && projectName !== void 0) { + throw new Error("Must provide either projectName or projectId, not both"); + } else if (projectId === void 0) { + projectId_ = (await this.readProject({ projectName })).id; + } else { + projectId_ = projectId; + } + assertUuid(projectId_); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/sessions/${projectId_}`, { + method: "DELETE", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, `delete session ${projectId_} (${projectName})`, true); + } + async uploadCsv({ csvFile, fileName, inputKeys, outputKeys, description, dataType, name }) { + const url = `${this.apiUrl}/datasets/upload`; + const formData = new FormData(); + formData.append("file", csvFile, fileName); + inputKeys.forEach((key) => { + formData.append("input_keys", key); + }); + outputKeys.forEach((key) => { + formData.append("output_keys", key); + }); + if (description) { + formData.append("description", description); + } + if (dataType) { + formData.append("data_type", dataType); + } + if (name) { + formData.append("name", name); + } + const response = await this.caller.call(_getFetchImplementation(this.debug), url, { + method: "POST", + headers: this.headers, + body: formData, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, "upload CSV"); + const result = await response.json(); + return result; + } + async createDataset(name, { description, dataType, inputsSchema, outputsSchema, metadata } = {}) { + const body = { + name, + description, + extra: metadata ? { metadata } : void 0 + }; + if (dataType) { + body.data_type = dataType; + } + if (inputsSchema) { + body.inputs_schema_definition = inputsSchema; + } + if (outputsSchema) { + body.outputs_schema_definition = outputsSchema; + } + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets`, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(body), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, "create dataset"); + const result = await response.json(); + return result; + } + async readDataset({ datasetId, datasetName }) { + let path = "/datasets"; + const params = new URLSearchParams({ limit: "1" }); + if (datasetId && datasetName) { + throw new Error("Must provide either datasetName or datasetId, not both"); + } else if (datasetId) { + assertUuid(datasetId); + path += `/${datasetId}`; + } else if (datasetName) { + params.append("name", datasetName); + } else { + throw new Error("Must provide datasetName or datasetId"); + } + const response = await this._get(path, params); + let result; + if (Array.isArray(response)) { + if (response.length === 0) { + throw new Error(`Dataset[id=${datasetId}, name=${datasetName}] not found`); + } + result = response[0]; + } else { + result = response; + } + return result; + } + async hasDataset({ datasetId, datasetName }) { + try { + await this.readDataset({ datasetId, datasetName }); + return true; + } catch (e) { + if ( + // eslint-disable-next-line no-instanceof/no-instanceof + e instanceof Error && e.message.toLocaleLowerCase().includes("not found") + ) { + return false; + } + throw e; + } + } + async diffDatasetVersions({ datasetId, datasetName, fromVersion, toVersion }) { + let datasetId_ = datasetId; + if (datasetId_ === void 0 && datasetName === void 0) { + throw new Error("Must provide either datasetName or datasetId"); + } else if (datasetId_ !== void 0 && datasetName !== void 0) { + throw new Error("Must provide either datasetName or datasetId, not both"); + } else if (datasetId_ === void 0) { + const dataset = await this.readDataset({ datasetName }); + datasetId_ = dataset.id; + } + const urlParams = new URLSearchParams({ + from_version: typeof fromVersion === "string" ? fromVersion : fromVersion.toISOString(), + to_version: typeof toVersion === "string" ? toVersion : toVersion.toISOString() + }); + const response = await this._get(`/datasets/${datasetId_}/versions/diff`, urlParams); + return response; + } + async readDatasetOpenaiFinetuning({ datasetId, datasetName }) { + const path = "/datasets"; + if (datasetId !== void 0) { + } else if (datasetName !== void 0) { + datasetId = (await this.readDataset({ datasetName })).id; + } else { + throw new Error("Must provide either datasetName or datasetId"); + } + const response = await this._getResponse(`${path}/${datasetId}/openai_ft`); + const datasetText = await response.text(); + const dataset = datasetText.trim().split("\n").map((line) => JSON.parse(line)); + return dataset; + } + async *listDatasets({ limit = 100, offset = 0, datasetIds, datasetName, datasetNameContains, metadata } = {}) { + const path = "/datasets"; + const params = new URLSearchParams({ + limit: limit.toString(), + offset: offset.toString() + }); + if (datasetIds !== void 0) { + for (const id_ of datasetIds) { + params.append("id", id_); + } + } + if (datasetName !== void 0) { + params.append("name", datasetName); + } + if (datasetNameContains !== void 0) { + params.append("name_contains", datasetNameContains); + } + if (metadata !== void 0) { + params.append("metadata", JSON.stringify(metadata)); + } + for await (const datasets of this._getPaginated(path, params)) { + yield* datasets; + } + } + /** + * Update a dataset + * @param props The dataset details to update + * @returns The updated dataset + */ + async updateDataset(props) { + const { datasetId, datasetName, ...update } = props; + if (!datasetId && !datasetName) { + throw new Error("Must provide either datasetName or datasetId"); + } + const _datasetId = datasetId ?? (await this.readDataset({ datasetName })).id; + assertUuid(_datasetId); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${_datasetId}`, { + method: "PATCH", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(update), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, "update dataset"); + return await response.json(); + } + /** + * Updates a tag on a dataset. + * + * If the tag is already assigned to a different version of this dataset, + * the tag will be moved to the new version. The as_of parameter is used to + * determine which version of the dataset to apply the new tags to. + * + * It must be an exact version of the dataset to succeed. You can + * use the "readDatasetVersion" method to find the exact version + * to apply the tags to. + * @param params.datasetId The ID of the dataset to update. Must be provided if "datasetName" is not provided. + * @param params.datasetName The name of the dataset to update. Must be provided if "datasetId" is not provided. + * @param params.asOf The timestamp of the dataset to apply the new tags to. + * @param params.tag The new tag to apply to the dataset. + */ + async updateDatasetTag(props) { + const { datasetId, datasetName, asOf, tag } = props; + if (!datasetId && !datasetName) { + throw new Error("Must provide either datasetName or datasetId"); + } + const _datasetId = datasetId ?? (await this.readDataset({ datasetName })).id; + assertUuid(_datasetId); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${_datasetId}/tags`, { + method: "PUT", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify({ + as_of: typeof asOf === "string" ? asOf : asOf.toISOString(), + tag + }), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, "update dataset tags"); + } + async deleteDataset({ datasetId, datasetName }) { + let path = "/datasets"; + let datasetId_ = datasetId; + if (datasetId !== void 0 && datasetName !== void 0) { + throw new Error("Must provide either datasetName or datasetId, not both"); + } else if (datasetName !== void 0) { + const dataset = await this.readDataset({ datasetName }); + datasetId_ = dataset.id; + } + if (datasetId_ !== void 0) { + assertUuid(datasetId_); + path += `/${datasetId_}`; + } else { + throw new Error("Must provide datasetName or datasetId"); + } + const response = await this.caller.call(_getFetchImplementation(this.debug), this.apiUrl + path, { + method: "DELETE", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, `delete ${path}`); + await response.json(); + } + async indexDataset({ datasetId, datasetName, tag }) { + let datasetId_ = datasetId; + if (!datasetId_ && !datasetName) { + throw new Error("Must provide either datasetName or datasetId"); + } else if (datasetId_ && datasetName) { + throw new Error("Must provide either datasetName or datasetId, not both"); + } else if (!datasetId_) { + const dataset = await this.readDataset({ datasetName }); + datasetId_ = dataset.id; + } + assertUuid(datasetId_); + const data = { + tag + }; + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${datasetId_}/index`, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(data), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, "index dataset"); + await response.json(); + } + /** + * Lets you run a similarity search query on a dataset. + * + * Requires the dataset to be indexed. Please see the `indexDataset` method to set up indexing. + * + * @param inputs The input on which to run the similarity search. Must have the + * same schema as the dataset. + * + * @param datasetId The dataset to search for similar examples. + * + * @param limit The maximum number of examples to return. Will return the top `limit` most + * similar examples in order of most similar to least similar. If no similar + * examples are found, random examples will be returned. + * + * @param filter A filter string to apply to the search. Only examples will be returned that + * match the filter string. Some examples of filters + * + * - eq(metadata.mykey, "value") + * - and(neq(metadata.my.nested.key, "value"), neq(metadata.mykey, "value")) + * - or(eq(metadata.mykey, "value"), eq(metadata.mykey, "othervalue")) + * + * @returns A list of similar examples. + * + * + * @example + * dataset_id = "123e4567-e89b-12d3-a456-426614174000" + * inputs = {"text": "How many people live in Berlin?"} + * limit = 5 + * examples = await client.similarExamples(inputs, dataset_id, limit) + */ + async similarExamples(inputs, datasetId, limit, { filter } = {}) { + const data = { + limit, + inputs + }; + if (filter !== void 0) { + data["filter"] = filter; + } + assertUuid(datasetId); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${datasetId}/search`, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(data), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, "fetch similar examples"); + const result = await response.json(); + return result["examples"]; + } + async createExample(inputsOrUpdate, outputs, options) { + if (isExampleCreate(inputsOrUpdate)) { + if (outputs !== void 0 || options !== void 0) { + throw new Error("Cannot provide outputs or options when using ExampleCreate object"); + } + } + let datasetId_ = outputs ? options?.datasetId : inputsOrUpdate.dataset_id; + const datasetName_ = outputs ? options?.datasetName : inputsOrUpdate.dataset_name; + if (datasetId_ === void 0 && datasetName_ === void 0) { + throw new Error("Must provide either datasetName or datasetId"); + } else if (datasetId_ !== void 0 && datasetName_ !== void 0) { + throw new Error("Must provide either datasetName or datasetId, not both"); + } else if (datasetId_ === void 0) { + const dataset = await this.readDataset({ datasetName: datasetName_ }); + datasetId_ = dataset.id; + } + const createdAt_ = (outputs ? options?.createdAt : inputsOrUpdate.created_at) || /* @__PURE__ */ new Date(); + let data; + if (!isExampleCreate(inputsOrUpdate)) { + data = { + inputs: inputsOrUpdate, + outputs, + created_at: createdAt_?.toISOString(), + id: options?.exampleId, + metadata: options?.metadata, + split: options?.split, + source_run_id: options?.sourceRunId, + use_source_run_io: options?.useSourceRunIO, + use_source_run_attachments: options?.useSourceRunAttachments, + attachments: options?.attachments + }; + } else { + data = inputsOrUpdate; + } + const response = await this._uploadExamplesMultipart(datasetId_, [data]); + const example = await this.readExample(response.example_ids?.[0] ?? v4_default()); + return example; + } + async createExamples(propsOrUploads) { + if (Array.isArray(propsOrUploads)) { + if (propsOrUploads.length === 0) { + return []; + } + const uploads = propsOrUploads; + let datasetId_2 = uploads[0].dataset_id; + const datasetName_2 = uploads[0].dataset_name; + if (datasetId_2 === void 0 && datasetName_2 === void 0) { + throw new Error("Must provide either datasetName or datasetId"); + } else if (datasetId_2 !== void 0 && datasetName_2 !== void 0) { + throw new Error("Must provide either datasetName or datasetId, not both"); + } else if (datasetId_2 === void 0) { + const dataset = await this.readDataset({ datasetName: datasetName_2 }); + datasetId_2 = dataset.id; + } + const response2 = await this._uploadExamplesMultipart(datasetId_2, uploads); + const examples2 = await Promise.all(response2.example_ids.map((id) => this.readExample(id))); + return examples2; + } + const { inputs, outputs, metadata, splits, sourceRunIds, useSourceRunIOs, useSourceRunAttachments, attachments, exampleIds, datasetId, datasetName } = propsOrUploads; + if (inputs === void 0) { + throw new Error("Must provide inputs when using legacy parameters"); + } + let datasetId_ = datasetId; + const datasetName_ = datasetName; + if (datasetId_ === void 0 && datasetName_ === void 0) { + throw new Error("Must provide either datasetName or datasetId"); + } else if (datasetId_ !== void 0 && datasetName_ !== void 0) { + throw new Error("Must provide either datasetName or datasetId, not both"); + } else if (datasetId_ === void 0) { + const dataset = await this.readDataset({ datasetName: datasetName_ }); + datasetId_ = dataset.id; + } + const formattedExamples = inputs.map((input, idx) => { + return { + dataset_id: datasetId_, + inputs: input, + outputs: outputs?.[idx], + metadata: metadata?.[idx], + split: splits?.[idx], + id: exampleIds?.[idx], + attachments: attachments?.[idx], + source_run_id: sourceRunIds?.[idx], + use_source_run_io: useSourceRunIOs?.[idx], + use_source_run_attachments: useSourceRunAttachments?.[idx] + }; + }); + const response = await this._uploadExamplesMultipart(datasetId_, formattedExamples); + const examples = await Promise.all(response.example_ids.map((id) => this.readExample(id))); + return examples; + } + async createLLMExample(input, generation, options) { + return this.createExample({ input }, { output: generation }, options); + } + async createChatExample(input, generations, options) { + const finalInput = input.map((message) => { + if (isLangChainMessage(message)) { + return convertLangChainMessageToExample(message); + } + return message; + }); + const finalOutput = isLangChainMessage(generations) ? convertLangChainMessageToExample(generations) : generations; + return this.createExample({ input: finalInput }, { output: finalOutput }, options); + } + async readExample(exampleId) { + assertUuid(exampleId); + const path = `/examples/${exampleId}`; + const rawExample = await this._get(path); + const { attachment_urls, ...rest } = rawExample; + const example = rest; + if (attachment_urls) { + example.attachments = Object.entries(attachment_urls).reduce((acc, [key, value]) => { + acc[key.slice("attachment.".length)] = { + presigned_url: value.presigned_url, + mime_type: value.mime_type + }; + return acc; + }, {}); + } + return example; + } + async *listExamples({ datasetId, datasetName, exampleIds, asOf, splits, inlineS3Urls, metadata, limit, offset, filter, includeAttachments } = {}) { + let datasetId_; + if (datasetId !== void 0 && datasetName !== void 0) { + throw new Error("Must provide either datasetName or datasetId, not both"); + } else if (datasetId !== void 0) { + datasetId_ = datasetId; + } else if (datasetName !== void 0) { + const dataset = await this.readDataset({ datasetName }); + datasetId_ = dataset.id; + } else { + throw new Error("Must provide a datasetName or datasetId"); + } + const params = new URLSearchParams({ dataset: datasetId_ }); + const dataset_version = asOf ? typeof asOf === "string" ? asOf : asOf?.toISOString() : void 0; + if (dataset_version) { + params.append("as_of", dataset_version); + } + const inlineS3Urls_ = inlineS3Urls ?? true; + params.append("inline_s3_urls", inlineS3Urls_.toString()); + if (exampleIds !== void 0) { + for (const id_ of exampleIds) { + params.append("id", id_); + } + } + if (splits !== void 0) { + for (const split of splits) { + params.append("splits", split); + } + } + if (metadata !== void 0) { + const serializedMetadata = JSON.stringify(metadata); + params.append("metadata", serializedMetadata); + } + if (limit !== void 0) { + params.append("limit", limit.toString()); + } + if (offset !== void 0) { + params.append("offset", offset.toString()); + } + if (filter !== void 0) { + params.append("filter", filter); + } + if (includeAttachments === true) { + ["attachment_urls", "outputs", "metadata"].forEach((field) => params.append("select", field)); + } + let i = 0; + for await (const rawExamples of this._getPaginated("/examples", params)) { + for (const rawExample of rawExamples) { + const { attachment_urls, ...rest } = rawExample; + const example = rest; + if (attachment_urls) { + example.attachments = Object.entries(attachment_urls).reduce((acc, [key, value]) => { + acc[key.slice("attachment.".length)] = { + presigned_url: value.presigned_url, + mime_type: value.mime_type || void 0 + }; + return acc; + }, {}); + } + yield example; + i++; + } + if (limit !== void 0 && i >= limit) { + break; + } + } + } + async deleteExample(exampleId) { + assertUuid(exampleId); + const path = `/examples/${exampleId}`; + const response = await this.caller.call(_getFetchImplementation(this.debug), this.apiUrl + path, { + method: "DELETE", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, `delete ${path}`); + await response.json(); + } + async updateExample(exampleIdOrUpdate, update) { + let exampleId; + if (update) { + exampleId = exampleIdOrUpdate; + } else { + exampleId = exampleIdOrUpdate.id; + } + assertUuid(exampleId); + let updateToUse; + if (update) { + updateToUse = { id: exampleId, ...update }; + } else { + updateToUse = exampleIdOrUpdate; + } + let datasetId; + if (updateToUse.dataset_id !== void 0) { + datasetId = updateToUse.dataset_id; + } else { + const example = await this.readExample(exampleId); + datasetId = example.dataset_id; + } + return this._updateExamplesMultipart(datasetId, [updateToUse]); + } + async updateExamples(update) { + let datasetId; + if (update[0].dataset_id === void 0) { + const example = await this.readExample(update[0].id); + datasetId = example.dataset_id; + } else { + datasetId = update[0].dataset_id; + } + return this._updateExamplesMultipart(datasetId, update); + } + /** + * Get dataset version by closest date or exact tag. + * + * Use this to resolve the nearest version to a given timestamp or for a given tag. + * + * @param options The options for getting the dataset version + * @param options.datasetId The ID of the dataset + * @param options.datasetName The name of the dataset + * @param options.asOf The timestamp of the dataset to retrieve + * @param options.tag The tag of the dataset to retrieve + * @returns The dataset version + */ + async readDatasetVersion({ datasetId, datasetName, asOf, tag }) { + let resolvedDatasetId; + if (!datasetId) { + const dataset = await this.readDataset({ datasetName }); + resolvedDatasetId = dataset.id; + } else { + resolvedDatasetId = datasetId; + } + assertUuid(resolvedDatasetId); + if (asOf && tag || !asOf && !tag) { + throw new Error("Exactly one of asOf and tag must be specified."); + } + const params = new URLSearchParams(); + if (asOf !== void 0) { + params.append("as_of", typeof asOf === "string" ? asOf : asOf.toISOString()); + } + if (tag !== void 0) { + params.append("tag", tag); + } + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${resolvedDatasetId}/version?${params.toString()}`, { + method: "GET", + headers: { ...this.headers }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, "read dataset version"); + return await response.json(); + } + async listDatasetSplits({ datasetId, datasetName, asOf }) { + let datasetId_; + if (datasetId === void 0 && datasetName === void 0) { + throw new Error("Must provide dataset name or ID"); + } else if (datasetId !== void 0 && datasetName !== void 0) { + throw new Error("Must provide either datasetName or datasetId, not both"); + } else if (datasetId === void 0) { + const dataset = await this.readDataset({ datasetName }); + datasetId_ = dataset.id; + } else { + datasetId_ = datasetId; + } + assertUuid(datasetId_); + const params = new URLSearchParams(); + const dataset_version = asOf ? typeof asOf === "string" ? asOf : asOf?.toISOString() : void 0; + if (dataset_version) { + params.append("as_of", dataset_version); + } + const response = await this._get(`/datasets/${datasetId_}/splits`, params); + return response; + } + async updateDatasetSplits({ datasetId, datasetName, splitName, exampleIds, remove: remove2 = false }) { + let datasetId_; + if (datasetId === void 0 && datasetName === void 0) { + throw new Error("Must provide dataset name or ID"); + } else if (datasetId !== void 0 && datasetName !== void 0) { + throw new Error("Must provide either datasetName or datasetId, not both"); + } else if (datasetId === void 0) { + const dataset = await this.readDataset({ datasetName }); + datasetId_ = dataset.id; + } else { + datasetId_ = datasetId; + } + assertUuid(datasetId_); + const data = { + split_name: splitName, + examples: exampleIds.map((id) => { + assertUuid(id); + return id; + }), + remove: remove2 + }; + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${datasetId_}/splits`, { + method: "PUT", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(data), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, "update dataset splits", true); + } + /** + * @deprecated This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead. + */ + async evaluateRun(run, evaluator, { sourceInfo, loadChildRuns, referenceExample } = { loadChildRuns: false }) { + warnOnce("This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead."); + let run_; + if (typeof run === "string") { + run_ = await this.readRun(run, { loadChildRuns }); + } else if (typeof run === "object" && "id" in run) { + run_ = run; + } else { + throw new Error(`Invalid run type: ${typeof run}`); + } + if (run_.reference_example_id !== null && run_.reference_example_id !== void 0) { + referenceExample = await this.readExample(run_.reference_example_id); + } + const feedbackResult = await evaluator.evaluateRun(run_, referenceExample); + const [_, feedbacks] = await this._logEvaluationFeedback(feedbackResult, run_, sourceInfo); + return feedbacks[0]; + } + async createFeedback(runId, key, { score, value, correction, comment, sourceInfo, feedbackSourceType = "api", sourceRunId, feedbackId, feedbackConfig, projectId, comparativeExperimentId }) { + if (!runId && !projectId) { + throw new Error("One of runId or projectId must be provided"); + } + if (runId && projectId) { + throw new Error("Only one of runId or projectId can be provided"); + } + const feedback_source = { + type: feedbackSourceType ?? "api", + metadata: sourceInfo ?? {} + }; + if (sourceRunId !== void 0 && feedback_source?.metadata !== void 0 && !feedback_source.metadata["__run"]) { + feedback_source.metadata["__run"] = { run_id: sourceRunId }; + } + if (feedback_source?.metadata !== void 0 && feedback_source.metadata["__run"]?.run_id !== void 0) { + assertUuid(feedback_source.metadata["__run"].run_id); + } + const feedback = { + id: feedbackId ?? v4_default(), + run_id: runId, + key, + score: _formatFeedbackScore(score), + value, + correction, + comment, + feedback_source, + comparative_experiment_id: comparativeExperimentId, + feedbackConfig, + session_id: projectId + }; + const url = `${this.apiUrl}/feedback`; + const response = await this.caller.call(_getFetchImplementation(this.debug), url, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(feedback), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, "create feedback", true); + return feedback; + } + async updateFeedback(feedbackId, { score, value, correction, comment }) { + const feedbackUpdate = {}; + if (score !== void 0 && score !== null) { + feedbackUpdate["score"] = _formatFeedbackScore(score); + } + if (value !== void 0 && value !== null) { + feedbackUpdate["value"] = value; + } + if (correction !== void 0 && correction !== null) { + feedbackUpdate["correction"] = correction; + } + if (comment !== void 0 && comment !== null) { + feedbackUpdate["comment"] = comment; + } + assertUuid(feedbackId); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/feedback/${feedbackId}`, { + method: "PATCH", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(feedbackUpdate), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, "update feedback", true); + } + async readFeedback(feedbackId) { + assertUuid(feedbackId); + const path = `/feedback/${feedbackId}`; + const response = await this._get(path); + return response; + } + async deleteFeedback(feedbackId) { + assertUuid(feedbackId); + const path = `/feedback/${feedbackId}`; + const response = await this.caller.call(_getFetchImplementation(this.debug), this.apiUrl + path, { + method: "DELETE", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, `delete ${path}`); + await response.json(); + } + async *listFeedback({ runIds, feedbackKeys, feedbackSourceTypes } = {}) { + const queryParams = new URLSearchParams(); + if (runIds) { + queryParams.append("run", runIds.join(",")); + } + if (feedbackKeys) { + for (const key of feedbackKeys) { + queryParams.append("key", key); + } + } + if (feedbackSourceTypes) { + for (const type of feedbackSourceTypes) { + queryParams.append("source", type); + } + } + for await (const feedbacks of this._getPaginated("/feedback", queryParams)) { + yield* feedbacks; + } + } + /** + * Creates a presigned feedback token and URL. + * + * The token can be used to authorize feedback metrics without + * needing an API key. This is useful for giving browser-based + * applications the ability to submit feedback without needing + * to expose an API key. + * + * @param runId The ID of the run. + * @param feedbackKey The feedback key. + * @param options Additional options for the token. + * @param options.expiration The expiration time for the token. + * + * @returns A promise that resolves to a FeedbackIngestToken. + */ + async createPresignedFeedbackToken(runId, feedbackKey, { expiration, feedbackConfig } = {}) { + const body = { + run_id: runId, + feedback_key: feedbackKey, + feedback_config: feedbackConfig + }; + if (expiration) { + if (typeof expiration === "string") { + body["expires_at"] = expiration; + } else if (expiration?.hours || expiration?.minutes || expiration?.days) { + body["expires_in"] = expiration; + } + } else { + body["expires_in"] = { + hours: 3 + }; + } + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/feedback/tokens`, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(body), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + const result = await response.json(); + return result; + } + async createComparativeExperiment({ name, experimentIds, referenceDatasetId, createdAt, description, metadata, id }) { + if (experimentIds.length === 0) { + throw new Error("At least one experiment is required"); + } + if (!referenceDatasetId) { + referenceDatasetId = (await this.readProject({ + projectId: experimentIds[0] + })).reference_dataset_id; + } + if (!referenceDatasetId == null) { + throw new Error("A reference dataset is required"); + } + const body = { + id, + name, + experiment_ids: experimentIds, + reference_dataset_id: referenceDatasetId, + description, + created_at: (createdAt ?? /* @__PURE__ */ new Date())?.toISOString(), + extra: {} + }; + if (metadata) + body.extra["metadata"] = metadata; + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/comparative`, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(body), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + return await response.json(); + } + /** + * Retrieves a list of presigned feedback tokens for a given run ID. + * @param runId The ID of the run. + * @returns An async iterable of FeedbackIngestToken objects. + */ + async *listPresignedFeedbackTokens(runId) { + assertUuid(runId); + const params = new URLSearchParams({ run_id: runId }); + for await (const tokens of this._getPaginated("/feedback/tokens", params)) { + yield* tokens; + } + } + _selectEvalResults(results) { + let results_; + if ("results" in results) { + results_ = results.results; + } else if (Array.isArray(results)) { + results_ = results; + } else { + results_ = [results]; + } + return results_; + } + async _logEvaluationFeedback(evaluatorResponse, run, sourceInfo) { + const evalResults = this._selectEvalResults(evaluatorResponse); + const feedbacks = []; + for (const res of evalResults) { + let sourceInfo_ = sourceInfo || {}; + if (res.evaluatorInfo) { + sourceInfo_ = { ...res.evaluatorInfo, ...sourceInfo_ }; + } + let runId_ = null; + if (res.targetRunId) { + runId_ = res.targetRunId; + } else if (run) { + runId_ = run.id; + } + feedbacks.push(await this.createFeedback(runId_, res.key, { + score: res.score, + value: res.value, + comment: res.comment, + correction: res.correction, + sourceInfo: sourceInfo_, + sourceRunId: res.sourceRunId, + feedbackConfig: res.feedbackConfig, + feedbackSourceType: "model" + })); + } + return [evalResults, feedbacks]; + } + async logEvaluationFeedback(evaluatorResponse, run, sourceInfo) { + const [results] = await this._logEvaluationFeedback(evaluatorResponse, run, sourceInfo); + return results; + } + /** + * API for managing annotation queues + */ + /** + * List the annotation queues on the LangSmith API. + * @param options - The options for listing annotation queues + * @param options.queueIds - The IDs of the queues to filter by + * @param options.name - The name of the queue to filter by + * @param options.nameContains - The substring that the queue name should contain + * @param options.limit - The maximum number of queues to return + * @returns An iterator of AnnotationQueue objects + */ + async *listAnnotationQueues(options = {}) { + const { queueIds, name, nameContains, limit } = options; + const params = new URLSearchParams(); + if (queueIds) { + queueIds.forEach((id, i) => { + assertUuid(id, `queueIds[${i}]`); + params.append("ids", id); + }); + } + if (name) + params.append("name", name); + if (nameContains) + params.append("name_contains", nameContains); + params.append("limit", (limit !== void 0 ? Math.min(limit, 100) : 100).toString()); + let count = 0; + for await (const queues of this._getPaginated("/annotation-queues", params)) { + yield* queues; + count++; + if (limit !== void 0 && count >= limit) + break; + } + } + /** + * Create an annotation queue on the LangSmith API. + * @param options - The options for creating an annotation queue + * @param options.name - The name of the annotation queue + * @param options.description - The description of the annotation queue + * @param options.queueId - The ID of the annotation queue + * @returns The created AnnotationQueue object + */ + async createAnnotationQueue(options) { + const { name, description, queueId, rubricInstructions } = options; + const body = { + name, + description, + id: queueId || v4_default(), + rubric_instructions: rubricInstructions + }; + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/annotation-queues`, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(Object.fromEntries(Object.entries(body).filter(([_, v]) => v !== void 0))), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, "create annotation queue"); + const data = await response.json(); + return data; + } + /** + * Read an annotation queue with the specified queue ID. + * @param queueId - The ID of the annotation queue to read + * @returns The AnnotationQueueWithDetails object + */ + async readAnnotationQueue(queueId) { + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}`, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, "read annotation queue"); + const data = await response.json(); + return data; + } + /** + * Update an annotation queue with the specified queue ID. + * @param queueId - The ID of the annotation queue to update + * @param options - The options for updating the annotation queue + * @param options.name - The new name for the annotation queue + * @param options.description - The new description for the annotation queue + */ + async updateAnnotationQueue(queueId, options) { + const { name, description, rubricInstructions } = options; + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}`, { + method: "PATCH", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify({ + name, + description, + rubric_instructions: rubricInstructions + }), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, "update annotation queue"); + } + /** + * Delete an annotation queue with the specified queue ID. + * @param queueId - The ID of the annotation queue to delete + */ + async deleteAnnotationQueue(queueId) { + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}`, { + method: "DELETE", + headers: { ...this.headers, Accept: "application/json" }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, "delete annotation queue"); + } + /** + * Add runs to an annotation queue with the specified queue ID. + * @param queueId - The ID of the annotation queue + * @param runIds - The IDs of the runs to be added to the annotation queue + */ + async addRunsToAnnotationQueue(queueId, runIds) { + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}/runs`, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(runIds.map((id, i) => assertUuid(id, `runIds[${i}]`).toString())), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, "add runs to annotation queue"); + } + /** + * Get a run from an annotation queue at the specified index. + * @param queueId - The ID of the annotation queue + * @param index - The index of the run to retrieve + * @returns A Promise that resolves to a RunWithAnnotationQueueInfo object + * @throws {Error} If the run is not found at the given index or for other API-related errors + */ + async getRunFromAnnotationQueue(queueId, index2) { + const baseUrl = `/annotation-queues/${assertUuid(queueId, "queueId")}/run`; + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}${baseUrl}/${index2}`, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, "get run from annotation queue"); + return await response.json(); + } + /** + * Delete a run from an an annotation queue. + * @param queueId - The ID of the annotation queue to delete the run from + * @param queueRunId - The ID of the run to delete from the annotation queue + */ + async deleteRunFromAnnotationQueue(queueId, queueRunId) { + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}/runs/${assertUuid(queueRunId, "queueRunId")}`, { + method: "DELETE", + headers: { ...this.headers, Accept: "application/json" }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, "delete run from annotation queue"); + } + /** + * Get the size of an annotation queue. + * @param queueId - The ID of the annotation queue + */ + async getSizeFromAnnotationQueue(queueId) { + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}/size`, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, "get size from annotation queue"); + return await response.json(); + } + async _currentTenantIsOwner(owner) { + const settings = await this._getSettings(); + return owner == "-" || settings.tenant_handle === owner; + } + async _ownerConflictError(action, owner) { + const settings = await this._getSettings(); + return new Error(`Cannot ${action} for another tenant. + + Current tenant: ${settings.tenant_handle} + + Requested tenant: ${owner}`); + } + async _getLatestCommitHash(promptOwnerAndName) { + const res = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/commits/${promptOwnerAndName}/?limit=${1}&offset=${0}`, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + const json = await res.json(); + if (!res.ok) { + const detail = typeof json.detail === "string" ? json.detail : JSON.stringify(json.detail); + const error = new Error(`Error ${res.status}: ${res.statusText} +${detail}`); + error.statusCode = res.status; + throw error; + } + if (json.commits.length === 0) { + return void 0; + } + return json.commits[0].commit_hash; + } + async _likeOrUnlikePrompt(promptIdentifier, like) { + const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/likes/${owner}/${promptName}`, { + method: "POST", + body: JSON.stringify({ like }), + headers: { ...this.headers, "Content-Type": "application/json" }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, `${like ? "like" : "unlike"} prompt`); + return await response.json(); + } + async _getPromptUrl(promptIdentifier) { + const [owner, promptName, commitHash] = parsePromptIdentifier(promptIdentifier); + if (!await this._currentTenantIsOwner(owner)) { + if (commitHash !== "latest") { + return `${this.getHostUrl()}/hub/${owner}/${promptName}/${commitHash.substring(0, 8)}`; + } else { + return `${this.getHostUrl()}/hub/${owner}/${promptName}`; + } + } else { + const settings = await this._getSettings(); + if (commitHash !== "latest") { + return `${this.getHostUrl()}/prompts/${promptName}/${commitHash.substring(0, 8)}?organizationId=${settings.id}`; + } else { + return `${this.getHostUrl()}/prompts/${promptName}?organizationId=${settings.id}`; + } + } + } + async promptExists(promptIdentifier) { + const prompt = await this.getPrompt(promptIdentifier); + return !!prompt; + } + async likePrompt(promptIdentifier) { + return this._likeOrUnlikePrompt(promptIdentifier, true); + } + async unlikePrompt(promptIdentifier) { + return this._likeOrUnlikePrompt(promptIdentifier, false); + } + async *listCommits(promptOwnerAndName) { + for await (const commits of this._getPaginated(`/commits/${promptOwnerAndName}/`, new URLSearchParams(), (res) => res.commits)) { + yield* commits; + } + } + async *listPrompts(options) { + const params = new URLSearchParams(); + params.append("sort_field", options?.sortField ?? "updated_at"); + params.append("sort_direction", "desc"); + params.append("is_archived", (!!options?.isArchived).toString()); + if (options?.isPublic !== void 0) { + params.append("is_public", options.isPublic.toString()); + } + if (options?.query) { + params.append("query", options.query); + } + for await (const prompts of this._getPaginated("/repos", params, (res) => res.repos)) { + yield* prompts; + } + } + async getPrompt(promptIdentifier) { + const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/repos/${owner}/${promptName}`, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + if (response.status === 404) { + return null; + } + await raiseForStatus(response, "get prompt"); + const result = await response.json(); + if (result.repo) { + return result.repo; + } else { + return null; + } + } + async createPrompt(promptIdentifier, options) { + const settings = await this._getSettings(); + if (options?.isPublic && !settings.tenant_handle) { + throw new Error(`Cannot create a public prompt without first + + creating a LangChain Hub handle. + You can add a handle by creating a public prompt at: + + https://smith.langchain.com/prompts`); + } + const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier); + if (!await this._currentTenantIsOwner(owner)) { + throw await this._ownerConflictError("create a prompt", owner); + } + const data = { + repo_handle: promptName, + ...options?.description && { description: options.description }, + ...options?.readme && { readme: options.readme }, + ...options?.tags && { tags: options.tags }, + is_public: !!options?.isPublic + }; + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/repos/`, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(data), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, "create prompt"); + const { repo } = await response.json(); + return repo; + } + async createCommit(promptIdentifier, object, options) { + if (!await this.promptExists(promptIdentifier)) { + throw new Error("Prompt does not exist, you must create it first."); + } + const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier); + const resolvedParentCommitHash = options?.parentCommitHash === "latest" || !options?.parentCommitHash ? await this._getLatestCommitHash(`${owner}/${promptName}`) : options?.parentCommitHash; + const payload = { + manifest: JSON.parse(JSON.stringify(object)), + parent_commit: resolvedParentCommitHash + }; + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/commits/${owner}/${promptName}`, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(payload), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, "create commit"); + const result = await response.json(); + return this._getPromptUrl(`${owner}/${promptName}${result.commit_hash ? `:${result.commit_hash}` : ""}`); + } + /** + * Update examples with attachments using multipart form data. + * @param updates List of ExampleUpdateWithAttachments objects to upsert + * @returns Promise with the update response + */ + async updateExamplesMultipart(datasetId, updates = []) { + return this._updateExamplesMultipart(datasetId, updates); + } + async _updateExamplesMultipart(datasetId, updates = []) { + if (!await this._getDatasetExamplesMultiPartSupport()) { + throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version."); + } + const formData = new FormData(); + for (const example of updates) { + const exampleId = example.id; + const exampleBody = { + ...example.metadata && { metadata: example.metadata }, + ...example.split && { split: example.split } + }; + const stringifiedExample = serialize(exampleBody, `Serializing body for example with id: ${exampleId}`); + const exampleBlob = new Blob([stringifiedExample], { + type: "application/json" + }); + formData.append(exampleId, exampleBlob); + if (example.inputs) { + const stringifiedInputs = serialize(example.inputs, `Serializing inputs for example with id: ${exampleId}`); + const inputsBlob = new Blob([stringifiedInputs], { + type: "application/json" + }); + formData.append(`${exampleId}.inputs`, inputsBlob); + } + if (example.outputs) { + const stringifiedOutputs = serialize(example.outputs, `Serializing outputs whle updating example with id: ${exampleId}`); + const outputsBlob = new Blob([stringifiedOutputs], { + type: "application/json" + }); + formData.append(`${exampleId}.outputs`, outputsBlob); + } + if (example.attachments) { + for (const [name, attachment] of Object.entries(example.attachments)) { + let mimeType; + let data; + if (Array.isArray(attachment)) { + [mimeType, data] = attachment; + } else { + mimeType = attachment.mimeType; + data = attachment.data; + } + const attachmentBlob = new Blob([data], { + type: `${mimeType}; length=${data.byteLength}` + }); + formData.append(`${exampleId}.attachment.${name}`, attachmentBlob); + } + } + if (example.attachments_operations) { + const stringifiedAttachmentsOperations = serialize(example.attachments_operations, `Serializing attachments while updating example with id: ${exampleId}`); + const attachmentsOperationsBlob = new Blob([stringifiedAttachmentsOperations], { + type: "application/json" + }); + formData.append(`${exampleId}.attachments_operations`, attachmentsOperationsBlob); + } + } + const datasetIdToUse = datasetId ?? updates[0]?.dataset_id; + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${datasetIdToUse}/examples`)}`, { + method: "PATCH", + headers: this.headers, + body: formData + }); + const result = await response.json(); + return result; + } + /** + * Upload examples with attachments using multipart form data. + * @param uploads List of ExampleUploadWithAttachments objects to upload + * @returns Promise with the upload response + * @deprecated This method is deprecated and will be removed in future LangSmith versions, please use `createExamples` instead + */ + async uploadExamplesMultipart(datasetId, uploads = []) { + return this._uploadExamplesMultipart(datasetId, uploads); + } + async _uploadExamplesMultipart(datasetId, uploads = []) { + if (!await this._getDatasetExamplesMultiPartSupport()) { + throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version."); + } + const formData = new FormData(); + for (const example of uploads) { + const exampleId = (example.id ?? v4_default()).toString(); + const exampleBody = { + created_at: example.created_at, + ...example.metadata && { metadata: example.metadata }, + ...example.split && { split: example.split }, + ...example.source_run_id && { source_run_id: example.source_run_id }, + ...example.use_source_run_io && { + use_source_run_io: example.use_source_run_io + }, + ...example.use_source_run_attachments && { + use_source_run_attachments: example.use_source_run_attachments + } + }; + const stringifiedExample = serialize(exampleBody, `Serializing body for uploaded example with id: ${exampleId}`); + const exampleBlob = new Blob([stringifiedExample], { + type: "application/json" + }); + formData.append(exampleId, exampleBlob); + if (example.inputs) { + const stringifiedInputs = serialize(example.inputs, `Serializing inputs for uploaded example with id: ${exampleId}`); + const inputsBlob = new Blob([stringifiedInputs], { + type: "application/json" + }); + formData.append(`${exampleId}.inputs`, inputsBlob); + } + if (example.outputs) { + const stringifiedOutputs = serialize(example.outputs, `Serializing outputs for uploaded example with id: ${exampleId}`); + const outputsBlob = new Blob([stringifiedOutputs], { + type: "application/json" + }); + formData.append(`${exampleId}.outputs`, outputsBlob); + } + if (example.attachments) { + for (const [name, attachment] of Object.entries(example.attachments)) { + let mimeType; + let data; + if (Array.isArray(attachment)) { + [mimeType, data] = attachment; + } else { + mimeType = attachment.mimeType; + data = attachment.data; + } + const attachmentBlob = new Blob([data], { + type: `${mimeType}; length=${data.byteLength}` + }); + formData.append(`${exampleId}.attachment.${name}`, attachmentBlob); + } + } + } + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${datasetId}/examples`)}`, { + method: "POST", + headers: this.headers, + body: formData + }); + await raiseForStatus(response, "upload examples"); + const result = await response.json(); + return result; + } + async updatePrompt(promptIdentifier, options) { + if (!await this.promptExists(promptIdentifier)) { + throw new Error("Prompt does not exist, you must create it first."); + } + const [owner, promptName] = parsePromptIdentifier(promptIdentifier); + if (!await this._currentTenantIsOwner(owner)) { + throw await this._ownerConflictError("update a prompt", owner); + } + const payload = {}; + if (options?.description !== void 0) + payload.description = options.description; + if (options?.readme !== void 0) + payload.readme = options.readme; + if (options?.tags !== void 0) + payload.tags = options.tags; + if (options?.isPublic !== void 0) + payload.is_public = options.isPublic; + if (options?.isArchived !== void 0) + payload.is_archived = options.isArchived; + if (Object.keys(payload).length === 0) { + throw new Error("No valid update options provided"); + } + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/repos/${owner}/${promptName}`, { + method: "PATCH", + body: JSON.stringify(payload), + headers: { + ...this.headers, + "Content-Type": "application/json" + }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, "update prompt"); + return response.json(); + } + async deletePrompt(promptIdentifier) { + if (!await this.promptExists(promptIdentifier)) { + throw new Error("Prompt does not exist, you must create it first."); + } + const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier); + if (!await this._currentTenantIsOwner(owner)) { + throw await this._ownerConflictError("delete a prompt", owner); + } + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/repos/${owner}/${promptName}`, { + method: "DELETE", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + return await response.json(); + } + async pullPromptCommit(promptIdentifier, options) { + const [owner, promptName, commitHash] = parsePromptIdentifier(promptIdentifier); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/commits/${owner}/${promptName}/${commitHash}${options?.includeModel ? "?include_model=true" : ""}`, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, "pull prompt commit"); + const result = await response.json(); + return { + owner, + repo: promptName, + commit_hash: result.commit_hash, + manifest: result.manifest, + examples: result.examples + }; + } + /** + * This method should not be used directly, use `import { pull } from "langchain/hub"` instead. + * Using this method directly returns the JSON string of the prompt rather than a LangChain object. + * @private + */ + async _pullPrompt(promptIdentifier, options) { + const promptObject = await this.pullPromptCommit(promptIdentifier, { + includeModel: options?.includeModel + }); + const prompt = JSON.stringify(promptObject.manifest); + return prompt; + } + async pushPrompt(promptIdentifier, options) { + if (await this.promptExists(promptIdentifier)) { + if (options && Object.keys(options).some((key) => key !== "object")) { + await this.updatePrompt(promptIdentifier, { + description: options?.description, + readme: options?.readme, + tags: options?.tags, + isPublic: options?.isPublic + }); + } + } else { + await this.createPrompt(promptIdentifier, { + description: options?.description, + readme: options?.readme, + tags: options?.tags, + isPublic: options?.isPublic + }); + } + if (!options?.object) { + return await this._getPromptUrl(promptIdentifier); + } + const url = await this.createCommit(promptIdentifier, options?.object, { + parentCommitHash: options?.parentCommitHash + }); + return url; + } + /** + * Clone a public dataset to your own langsmith tenant. + * This operation is idempotent. If you already have a dataset with the given name, + * this function will do nothing. + + * @param {string} tokenOrUrl The token of the public dataset to clone. + * @param {Object} [options] Additional options for cloning the dataset. + * @param {string} [options.sourceApiUrl] The URL of the langsmith server where the data is hosted. Defaults to the API URL of your current client. + * @param {string} [options.datasetName] The name of the dataset to create in your tenant. Defaults to the name of the public dataset. + * @returns {Promise} + */ + async clonePublicDataset(tokenOrUrl, options = {}) { + const { sourceApiUrl = this.apiUrl, datasetName } = options; + const [parsedApiUrl, tokenUuid] = this.parseTokenOrUrl(tokenOrUrl, sourceApiUrl); + const sourceClient = new _Client({ + apiUrl: parsedApiUrl, + // Placeholder API key not needed anymore in most cases, but + // some private deployments may have API key-based rate limiting + // that would cause this to fail if we provide no value. + apiKey: "placeholder" + }); + const ds = await sourceClient.readSharedDataset(tokenUuid); + const finalDatasetName = datasetName || ds.name; + try { + if (await this.hasDataset({ datasetId: finalDatasetName })) { + console.log(`Dataset ${finalDatasetName} already exists in your tenant. Skipping.`); + return; + } + } catch (_) { + } + const examples = await sourceClient.listSharedExamples(tokenUuid); + const dataset = await this.createDataset(finalDatasetName, { + description: ds.description, + dataType: ds.data_type || "kv", + inputsSchema: ds.inputs_schema_definition ?? void 0, + outputsSchema: ds.outputs_schema_definition ?? void 0 + }); + try { + await this.createExamples({ + inputs: examples.map((e) => e.inputs), + outputs: examples.flatMap((e) => e.outputs ? [e.outputs] : []), + datasetId: dataset.id + }); + } catch (e) { + console.error(`An error occurred while creating dataset ${finalDatasetName}. You should delete it manually.`); + throw e; + } + } + parseTokenOrUrl(urlOrToken, apiUrl, numParts = 2, kind = "dataset") { + try { + assertUuid(urlOrToken); + return [apiUrl, urlOrToken]; + } catch (_) { + } + try { + const parsedUrl = new URL(urlOrToken); + const pathParts = parsedUrl.pathname.split("/").filter((part) => part !== ""); + if (pathParts.length >= numParts) { + const tokenUuid = pathParts[pathParts.length - numParts]; + return [apiUrl, tokenUuid]; + } else { + throw new Error(`Invalid public ${kind} URL: ${urlOrToken}`); + } + } catch (error) { + throw new Error(`Invalid public ${kind} URL or token: ${urlOrToken}`); + } + } + /** + * Awaits all pending trace batches. Useful for environments where + * you need to be sure that all tracing requests finish before execution ends, + * such as serverless environments. + * + * @example + * ``` + * import { Client } from "langsmith"; + * + * const client = new Client(); + * + * try { + * // Tracing happens here + * ... + * } finally { + * await client.awaitPendingTraceBatches(); + * } + * ``` + * + * @returns A promise that resolves once all currently pending traces have sent. + */ + async awaitPendingTraceBatches() { + if (this.manualFlushMode) { + console.warn("[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches."); + return Promise.resolve(); + } + await Promise.all([ + ...this.autoBatchQueue.items.map(({ itemPromise }) => itemPromise), + this.batchIngestCaller.queue.onIdle() + ]); + if (this.langSmithToOTELTranslator !== void 0) { + await getDefaultOTLPTracerComponents()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush(); + } + } + }; + } +}); + +// node_modules/langsmith/dist/env.js +var isTracingEnabled; +var init_env3 = __esm({ + "node_modules/langsmith/dist/env.js"() { + init_env2(); + isTracingEnabled = (tracingEnabled) => { + if (tracingEnabled !== void 0) { + return tracingEnabled; + } + const envVars = ["TRACING_V2", "TRACING"]; + return !!envVars.find((envVar) => getLangSmithEnvironmentVariable(envVar) === "true"); + }; + } +}); + +// node_modules/langsmith/dist/singletons/constants.js +var _LC_CONTEXT_VARIABLES_KEY; +var init_constants2 = __esm({ + "node_modules/langsmith/dist/singletons/constants.js"() { + _LC_CONTEXT_VARIABLES_KEY = Symbol.for("lc:context_variables"); + } +}); + +// node_modules/langsmith/dist/run_trees.js +function stripNonAlphanumeric(input) { + return input.replace(/[-:.]/g, ""); +} +function convertToDottedOrderFormat(epoch, runId, executionOrder = 1) { + const paddedOrder = executionOrder.toFixed(0).slice(0, 3).padStart(3, "0"); + const microsecondPrecisionDatestring = `${new Date(epoch).toISOString().slice(0, -1)}${paddedOrder}Z`; + return { + dottedOrder: stripNonAlphanumeric(microsecondPrecisionDatestring) + runId, + microsecondPrecisionDatestring + }; +} +function isRunTree(x) { + return x !== void 0 && typeof x.createChild === "function" && typeof x.postRun === "function"; +} +function isLangChainTracerLike(x) { + return typeof x === "object" && x != null && typeof x.name === "string" && x.name === "langchain_tracer"; +} +function containsLangChainTracerLike(x) { + return Array.isArray(x) && x.some((callback) => isLangChainTracerLike(callback)); +} +function isCallbackManagerLike(x) { + return typeof x === "object" && x != null && Array.isArray(x.handlers); +} +function isRunnableConfigLike(x) { + return x !== void 0 && typeof x.callbacks === "object" && // Callback manager with a langchain tracer + (containsLangChainTracerLike(x.callbacks?.handlers) || // Or it's an array with a LangChainTracerLike object within it + containsLangChainTracerLike(x.callbacks)); +} +function _parseDottedOrder(dottedOrder) { + const parts = dottedOrder.split("."); + return parts.map((part) => { + const timestampStr = part.slice(0, -36); + const uuidStr = part.slice(-36); + const year = parseInt(timestampStr.slice(0, 4)); + const month = parseInt(timestampStr.slice(4, 6)) - 1; + const day = parseInt(timestampStr.slice(6, 8)); + const hour = parseInt(timestampStr.slice(9, 11)); + const minute = parseInt(timestampStr.slice(11, 13)); + const second = parseInt(timestampStr.slice(13, 15)); + const microsecond = parseInt(timestampStr.slice(15, 21)); + const timestamp = new Date(year, month, day, hour, minute, second, microsecond / 1e3); + return [timestamp, uuidStr]; + }); +} +function _getWriteReplicasFromEnv() { + const envVar = getEnvironmentVariable2("LANGSMITH_RUNS_ENDPOINTS"); + if (!envVar) + return []; + try { + const parsed = JSON.parse(envVar); + if (Array.isArray(parsed)) { + const replicas = []; + for (const item of parsed) { + if (typeof item !== "object" || item === null) { + console.warn(`Invalid item type in LANGSMITH_RUNS_ENDPOINTS: expected object, got ${typeof item}`); + continue; + } + if (typeof item.api_url !== "string") { + console.warn(`Invalid api_url type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof item.api_url}`); + continue; + } + if (typeof item.api_key !== "string") { + console.warn(`Invalid api_key type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof item.api_key}`); + continue; + } + replicas.push({ + apiUrl: item.api_url.replace(/\/$/, ""), + apiKey: item.api_key + }); + } + return replicas; + } else if (typeof parsed === "object" && parsed !== null) { + _checkEndpointEnvUnset(parsed); + const replicas = []; + for (const [url, key] of Object.entries(parsed)) { + const cleanUrl = url.replace(/\/$/, ""); + if (typeof key === "string") { + replicas.push({ + apiUrl: cleanUrl, + apiKey: key + }); + } else { + console.warn(`Invalid value type in LANGSMITH_RUNS_ENDPOINTS for URL ${url}: expected string, got ${typeof key}`); + continue; + } + } + return replicas; + } else { + console.warn(`Invalid LANGSMITH_RUNS_ENDPOINTS \u2013 must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey, got ${typeof parsed}`); + return []; + } + } catch (e) { + if (isConflictingEndpointsError(e)) { + throw e; + } + console.warn("Invalid LANGSMITH_RUNS_ENDPOINTS \u2013 must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey"); + return []; + } +} +function _ensureWriteReplicas(replicas) { + if (replicas) { + return replicas.map((replica) => { + if (Array.isArray(replica)) { + return { + projectName: replica[0], + updates: replica[1] + }; + } + return replica; + }); + } + return _getWriteReplicasFromEnv(); +} +function _checkEndpointEnvUnset(parsed) { + if (Object.keys(parsed).length > 0 && getLangSmithEnvironmentVariable("ENDPOINT")) { + throw new ConflictingEndpointsError(); + } +} +var Baggage, RunTree; +var init_run_trees = __esm({ + "node_modules/langsmith/dist/run_trees.js"() { + init_esm_browser(); + init_client(); + init_env3(); + init_error(); + init_constants2(); + init_env2(); + init_project(); + init_env2(); + init_warn(); + Baggage = class _Baggage { + constructor(metadata, tags, project_name, replicas) { + Object.defineProperty(this, "metadata", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "tags", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "project_name", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "replicas", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.metadata = metadata; + this.tags = tags; + this.project_name = project_name; + this.replicas = replicas; + } + static fromHeader(value) { + const items = value.split(","); + let metadata = {}; + let tags = []; + let project_name; + let replicas; + for (const item of items) { + const [key, uriValue] = item.split("="); + const value2 = decodeURIComponent(uriValue); + if (key === "langsmith-metadata") { + metadata = JSON.parse(value2); + } else if (key === "langsmith-tags") { + tags = value2.split(","); + } else if (key === "langsmith-project") { + project_name = value2; + } else if (key === "langsmith-replicas") { + replicas = JSON.parse(value2); + } + } + return new _Baggage(metadata, tags, project_name, replicas); + } + toHeader() { + const items = []; + if (this.metadata && Object.keys(this.metadata).length > 0) { + items.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`); + } + if (this.tags && this.tags.length > 0) { + items.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`); + } + if (this.project_name) { + items.push(`langsmith-project=${encodeURIComponent(this.project_name)}`); + } + return items.join(","); + } + }; + RunTree = class _RunTree { + constructor(originalConfig) { + Object.defineProperty(this, "id", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "run_type", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "project_name", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "parent_run", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "parent_run_id", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "child_runs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "start_time", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "end_time", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "extra", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "tags", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "error", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "serialized", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "inputs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "outputs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "reference_example_id", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "client", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "events", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "trace_id", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "dotted_order", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "tracingEnabled", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "execution_order", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "child_execution_order", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "attachments", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "replicas", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "_serialized_start_time", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + if (isRunTree(originalConfig)) { + Object.assign(this, { ...originalConfig }); + return; + } + const defaultConfig = _RunTree.getDefaultConfig(); + const { metadata, ...config2 } = originalConfig; + const client2 = config2.client ?? _RunTree.getSharedClient(); + const dedupedMetadata = { + ...metadata, + ...config2?.extra?.metadata + }; + config2.extra = { ...config2.extra, metadata: dedupedMetadata }; + Object.assign(this, { ...defaultConfig, ...config2, client: client2 }); + if (!this.trace_id) { + if (this.parent_run) { + this.trace_id = this.parent_run.trace_id ?? this.id; + } else { + this.trace_id = this.id; + } + } + this.replicas = _ensureWriteReplicas(this.replicas); + this.execution_order ??= 1; + this.child_execution_order ??= 1; + if (!this.dotted_order) { + const { dottedOrder, microsecondPrecisionDatestring } = convertToDottedOrderFormat(this.start_time, this.id, this.execution_order); + if (this.parent_run) { + this.dotted_order = this.parent_run.dotted_order + "." + dottedOrder; + } else { + this.dotted_order = dottedOrder; + } + this._serialized_start_time = microsecondPrecisionDatestring; + } + } + set metadata(metadata) { + this.extra = { + ...this.extra, + metadata: { + ...this.extra?.metadata, + ...metadata + } + }; + } + get metadata() { + return this.extra?.metadata; + } + static getDefaultConfig() { + return { + id: v4_default(), + run_type: "chain", + project_name: getDefaultProjectName(), + child_runs: [], + api_url: getEnvironmentVariable2("LANGCHAIN_ENDPOINT") ?? "http://localhost:1984", + api_key: getEnvironmentVariable2("LANGCHAIN_API_KEY"), + caller_options: {}, + start_time: Date.now(), + serialized: {}, + inputs: {}, + extra: {} + }; + } + static getSharedClient() { + if (!_RunTree.sharedClient) { + _RunTree.sharedClient = new Client(); + } + return _RunTree.sharedClient; + } + createChild(config2) { + const child_execution_order = this.child_execution_order + 1; + const child = new _RunTree({ + ...config2, + parent_run: this, + project_name: this.project_name, + replicas: this.replicas, + client: this.client, + tracingEnabled: this.tracingEnabled, + execution_order: child_execution_order, + child_execution_order + }); + if (_LC_CONTEXT_VARIABLES_KEY in this) { + child[_LC_CONTEXT_VARIABLES_KEY] = this[_LC_CONTEXT_VARIABLES_KEY]; + } + const LC_CHILD = Symbol.for("lc:child_config"); + const presentConfig = config2.extra?.[LC_CHILD] ?? this.extra[LC_CHILD]; + if (isRunnableConfigLike(presentConfig)) { + const newConfig = { ...presentConfig }; + const callbacks = isCallbackManagerLike(newConfig.callbacks) ? newConfig.callbacks.copy?.() : void 0; + if (callbacks) { + Object.assign(callbacks, { _parentRunId: child.id }); + callbacks.handlers?.find(isLangChainTracerLike)?.updateFromRunTree?.(child); + newConfig.callbacks = callbacks; + } + child.extra[LC_CHILD] = newConfig; + } + const visited = /* @__PURE__ */ new Set(); + let current = this; + while (current != null && !visited.has(current.id)) { + visited.add(current.id); + current.child_execution_order = Math.max(current.child_execution_order, child_execution_order); + current = current.parent_run; + } + this.child_runs.push(child); + return child; + } + async end(outputs, error, endTime = Date.now(), metadata) { + this.outputs = this.outputs ?? outputs; + this.error = this.error ?? error; + this.end_time = this.end_time ?? endTime; + if (metadata && Object.keys(metadata).length > 0) { + this.extra = this.extra ? { ...this.extra, metadata: { ...this.extra.metadata, ...metadata } } : { metadata }; + } + } + _convertToCreate(run, runtimeEnv, excludeChildRuns = true) { + const runExtra = run.extra ?? {}; + if (runExtra?.runtime?.library === void 0) { + if (!runExtra.runtime) { + runExtra.runtime = {}; + } + if (runtimeEnv) { + for (const [k, v] of Object.entries(runtimeEnv)) { + if (!runExtra.runtime[k]) { + runExtra.runtime[k] = v; + } + } + } + } + let child_runs; + let parent_run_id; + if (!excludeChildRuns) { + child_runs = run.child_runs.map((child_run) => this._convertToCreate(child_run, runtimeEnv, excludeChildRuns)); + parent_run_id = void 0; + } else { + parent_run_id = run.parent_run?.id ?? run.parent_run_id; + child_runs = []; + } + return { + id: run.id, + name: run.name, + start_time: run._serialized_start_time ?? run.start_time, + end_time: run.end_time, + run_type: run.run_type, + reference_example_id: run.reference_example_id, + extra: runExtra, + serialized: run.serialized, + error: run.error, + inputs: run.inputs, + outputs: run.outputs, + session_name: run.project_name, + child_runs, + parent_run_id, + trace_id: run.trace_id, + dotted_order: run.dotted_order, + tags: run.tags, + attachments: run.attachments, + events: run.events + }; + } + _remapForProject(projectName, runtimeEnv, excludeChildRuns = true) { + const baseRun = this._convertToCreate(this, runtimeEnv, excludeChildRuns); + if (projectName === this.project_name) { + return baseRun; + } + const createRemappedId = (originalId) => { + return v5_default(`${originalId}:${projectName}`, v5_default.DNS); + }; + const newId = createRemappedId(baseRun.id); + const newTraceId = baseRun.trace_id ? createRemappedId(baseRun.trace_id) : void 0; + const newParentRunId = baseRun.parent_run_id ? createRemappedId(baseRun.parent_run_id) : void 0; + let newDottedOrder; + if (baseRun.dotted_order) { + const segments = _parseDottedOrder(baseRun.dotted_order); + const rebuilt = []; + for (let i = 0; i < segments.length - 1; i++) { + const [timestamp, segmentId] = segments[i]; + const remappedId = createRemappedId(segmentId); + rebuilt.push(timestamp.toISOString().replace(/[-:]/g, "").replace(".", "") + remappedId); + } + const [lastTimestamp] = segments[segments.length - 1]; + rebuilt.push(lastTimestamp.toISOString().replace(/[-:]/g, "").replace(".", "") + newId); + newDottedOrder = rebuilt.join("."); + } else { + newDottedOrder = void 0; + } + const remappedRun = { + ...baseRun, + id: newId, + trace_id: newTraceId, + parent_run_id: newParentRunId, + dotted_order: newDottedOrder, + session_name: projectName + }; + return remappedRun; + } + async postRun(excludeChildRuns = true) { + try { + const runtimeEnv = getRuntimeEnvironment2(); + if (this.replicas && this.replicas.length > 0) { + for (const { projectName, apiKey, apiUrl } of this.replicas) { + const runCreate = this._remapForProject(projectName ?? this.project_name, runtimeEnv, true); + await this.client.createRun(runCreate, { + apiKey, + apiUrl + }); + } + } else { + const runCreate = this._convertToCreate(this, runtimeEnv, excludeChildRuns); + await this.client.createRun(runCreate); + } + if (!excludeChildRuns) { + warnOnce("Posting with excludeChildRuns=false is deprecated and will be removed in a future version."); + for (const childRun of this.child_runs) { + await childRun.postRun(false); + } + } + } catch (error) { + console.error(`Error in postRun for run ${this.id}:`, error); + } + } + async patchRun(options) { + if (this.replicas && this.replicas.length > 0) { + for (const { projectName, apiKey, apiUrl, updates } of this.replicas) { + const runData = this._remapForProject(projectName ?? this.project_name); + const updatePayload = { + id: runData.id, + outputs: runData.outputs, + error: runData.error, + parent_run_id: runData.parent_run_id, + session_name: runData.session_name, + reference_example_id: runData.reference_example_id, + end_time: runData.end_time, + dotted_order: runData.dotted_order, + trace_id: runData.trace_id, + events: runData.events, + tags: runData.tags, + extra: runData.extra, + attachments: this.attachments, + ...updates + }; + if (!options?.excludeInputs) { + updatePayload.inputs = runData.inputs; + } + await this.client.updateRun(runData.id, updatePayload, { + apiKey, + apiUrl + }); + } + } else { + try { + const runUpdate = { + end_time: this.end_time, + error: this.error, + outputs: this.outputs, + parent_run_id: this.parent_run?.id ?? this.parent_run_id, + reference_example_id: this.reference_example_id, + extra: this.extra, + events: this.events, + dotted_order: this.dotted_order, + trace_id: this.trace_id, + tags: this.tags, + attachments: this.attachments, + session_name: this.project_name + }; + if (!options?.excludeInputs) { + runUpdate.inputs = this.inputs; + } + await this.client.updateRun(this.id, runUpdate); + } catch (error) { + console.error(`Error in patchRun for run ${this.id}`, error); + } + } + } + toJSON() { + return this._convertToCreate(this, void 0, false); + } + /** + * Add an event to the run tree. + * @param event - A single event or string to add + */ + addEvent(event) { + if (!this.events) { + this.events = []; + } + if (typeof event === "string") { + this.events.push({ + name: "event", + time: (/* @__PURE__ */ new Date()).toISOString(), + message: event + }); + } else { + this.events.push({ + ...event, + time: event.time ?? (/* @__PURE__ */ new Date()).toISOString() + }); + } + } + static fromRunnableConfig(parentConfig, props) { + const callbackManager = parentConfig?.callbacks; + let parentRun; + let projectName; + let client2; + let tracingEnabled = isTracingEnabled(); + if (callbackManager) { + const parentRunId = callbackManager?.getParentRunId?.() ?? ""; + const langChainTracer = callbackManager?.handlers?.find((handler) => handler?.name == "langchain_tracer"); + parentRun = langChainTracer?.getRun?.(parentRunId); + projectName = langChainTracer?.projectName; + client2 = langChainTracer?.client; + tracingEnabled = tracingEnabled || !!langChainTracer; + } + if (!parentRun) { + return new _RunTree({ + ...props, + client: client2, + tracingEnabled, + project_name: projectName + }); + } + const parentRunTree = new _RunTree({ + name: parentRun.name, + id: parentRun.id, + trace_id: parentRun.trace_id, + dotted_order: parentRun.dotted_order, + client: client2, + tracingEnabled, + project_name: projectName, + tags: [ + ...new Set((parentRun?.tags ?? []).concat(parentConfig?.tags ?? [])) + ], + extra: { + metadata: { + ...parentRun?.extra?.metadata, + ...parentConfig?.metadata + } + } + }); + return parentRunTree.createChild(props); + } + static fromDottedOrder(dottedOrder) { + return this.fromHeaders({ "langsmith-trace": dottedOrder }); + } + static fromHeaders(headers, inheritArgs) { + const rawHeaders = "get" in headers && typeof headers.get === "function" ? { + "langsmith-trace": headers.get("langsmith-trace"), + baggage: headers.get("baggage") + } : headers; + const headerTrace = rawHeaders["langsmith-trace"]; + if (!headerTrace || typeof headerTrace !== "string") + return void 0; + const parentDottedOrder = headerTrace.trim(); + const parsedDottedOrder = parentDottedOrder.split(".").map((part) => { + const [strTime, uuid] = part.split("Z"); + return { strTime, time: Date.parse(strTime + "Z"), uuid }; + }); + const traceId = parsedDottedOrder[0].uuid; + const config2 = { + ...inheritArgs, + name: inheritArgs?.["name"] ?? "parent", + run_type: inheritArgs?.["run_type"] ?? "chain", + start_time: inheritArgs?.["start_time"] ?? Date.now(), + id: parsedDottedOrder.at(-1)?.uuid, + trace_id: traceId, + dotted_order: parentDottedOrder + }; + if (rawHeaders["baggage"] && typeof rawHeaders["baggage"] === "string") { + const baggage = Baggage.fromHeader(rawHeaders["baggage"]); + config2.metadata = baggage.metadata; + config2.tags = baggage.tags; + config2.project_name = baggage.project_name; + config2.replicas = baggage.replicas; + } + return new _RunTree(config2); + } + toHeaders(headers) { + const result = { + "langsmith-trace": this.dotted_order, + baggage: new Baggage(this.extra?.metadata, this.tags, this.project_name, this.replicas).toHeader() + }; + if (headers) { + for (const [key, value] of Object.entries(result)) { + headers.set(key, value); + } + } + return result; + } + }; + Object.defineProperty(RunTree, "sharedClient", { + enumerable: true, + configurable: true, + writable: true, + value: null + }); + } +}); + +// node_modules/langsmith/run_trees.js +var init_run_trees2 = __esm({ + "node_modules/langsmith/run_trees.js"() { + init_run_trees(); + } +}); + +// node_modules/@langchain/core/dist/tracers/base.js +var base_exports3 = {}; +__export(base_exports3, { + BaseTracer: () => BaseTracer, + isBaseTracer: () => isBaseTracer +}); +function convertRunToRunTree(run, parentRun) { + if (!run) { + return void 0; + } + return new RunTree({ + ...run, + start_time: run._serialized_start_time ?? run.start_time, + parent_run: convertRunToRunTree(parentRun), + child_runs: run.child_runs.map((r) => convertRunToRunTree(r)).filter((r) => r !== void 0), + extra: { + ...run.extra, + runtime: getRuntimeEnvironmentSync() + }, + tracingEnabled: false + }); +} +function _coerceToDict(value, defaultKey) { + return value && !Array.isArray(value) && typeof value === "object" ? value : { [defaultKey]: value }; +} +function isBaseTracer(x) { + return typeof x._addRunToRunMap === "function"; +} +var convertRunTreeToRun, BaseTracer; +var init_base3 = __esm({ + "node_modules/@langchain/core/dist/tracers/base.js"() { + init_run_trees2(); + init_base2(); + init_env(); + convertRunTreeToRun = (runTree) => { + if (!runTree) { + return void 0; + } + runTree.events = runTree.events ?? []; + runTree.child_runs = runTree.child_runs ?? []; + return runTree; + }; + BaseTracer = class extends BaseCallbackHandler { + constructor(_fields) { + super(...arguments); + Object.defineProperty(this, "runMap", { + enumerable: true, + configurable: true, + writable: true, + value: /* @__PURE__ */ new Map() + }); + Object.defineProperty(this, "runTreeMap", { + enumerable: true, + configurable: true, + writable: true, + value: /* @__PURE__ */ new Map() + }); + Object.defineProperty(this, "usesRunTreeMap", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + } + copy() { + return this; + } + getRunById(runId) { + if (runId === void 0) { + return void 0; + } + return this.usesRunTreeMap ? convertRunTreeToRun(this.runTreeMap.get(runId)) : this.runMap.get(runId); + } + stringifyError(error) { + if (error instanceof Error) { + return error.message + (error?.stack ? ` + +${error.stack}` : ""); + } + if (typeof error === "string") { + return error; + } + return `${error}`; + } + _addChildRun(parentRun, childRun) { + parentRun.child_runs.push(childRun); + } + _addRunToRunMap(run) { + const { dottedOrder: currentDottedOrder, microsecondPrecisionDatestring } = convertToDottedOrderFormat(new Date(run.start_time).getTime(), run.id, run.execution_order); + const storedRun = { ...run }; + const parentRun = this.getRunById(storedRun.parent_run_id); + if (storedRun.parent_run_id !== void 0) { + if (parentRun) { + this._addChildRun(parentRun, storedRun); + parentRun.child_execution_order = Math.max(parentRun.child_execution_order, storedRun.child_execution_order); + storedRun.trace_id = parentRun.trace_id; + if (parentRun.dotted_order !== void 0) { + storedRun.dotted_order = [ + parentRun.dotted_order, + currentDottedOrder + ].join("."); + storedRun._serialized_start_time = microsecondPrecisionDatestring; + } else { + } + } else { + } + } else { + storedRun.trace_id = storedRun.id; + storedRun.dotted_order = currentDottedOrder; + storedRun._serialized_start_time = microsecondPrecisionDatestring; + } + if (this.usesRunTreeMap) { + const runTree = convertRunToRunTree(storedRun, parentRun); + if (runTree !== void 0) { + this.runTreeMap.set(storedRun.id, runTree); + } + } else { + this.runMap.set(storedRun.id, storedRun); + } + return storedRun; + } + async _endTrace(run) { + const parentRun = run.parent_run_id !== void 0 && this.getRunById(run.parent_run_id); + if (parentRun) { + parentRun.child_execution_order = Math.max(parentRun.child_execution_order, run.child_execution_order); + } else { + await this.persistRun(run); + } + await this.onRunUpdate?.(run); + if (this.usesRunTreeMap) { + this.runTreeMap.delete(run.id); + } else { + this.runMap.delete(run.id); + } + } + _getExecutionOrder(parentRunId) { + const parentRun = parentRunId !== void 0 && this.getRunById(parentRunId); + if (!parentRun) { + return 1; + } + return parentRun.child_execution_order + 1; + } + /** + * Create and add a run to the run map for LLM start events. + * This must sometimes be done synchronously to avoid race conditions + * when callbacks are backgrounded, so we expose it as a separate method here. + */ + _createRunForLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, name) { + const execution_order = this._getExecutionOrder(parentRunId); + const start_time = Date.now(); + const finalExtraParams = metadata ? { ...extraParams, metadata } : extraParams; + const run = { + id: runId, + name: name ?? llm.id[llm.id.length - 1], + parent_run_id: parentRunId, + start_time, + serialized: llm, + events: [ + { + name: "start", + time: new Date(start_time).toISOString() + } + ], + inputs: { prompts }, + execution_order, + child_runs: [], + child_execution_order: execution_order, + run_type: "llm", + extra: finalExtraParams ?? {}, + tags: tags || [] + }; + return this._addRunToRunMap(run); + } + async handleLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, name) { + const run = this.getRunById(runId) ?? this._createRunForLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, name); + await this.onRunCreate?.(run); + await this.onLLMStart?.(run); + return run; + } + /** + * Create and add a run to the run map for chat model start events. + * This must sometimes be done synchronously to avoid race conditions + * when callbacks are backgrounded, so we expose it as a separate method here. + */ + _createRunForChatModelStart(llm, messages, runId, parentRunId, extraParams, tags, metadata, name) { + const execution_order = this._getExecutionOrder(parentRunId); + const start_time = Date.now(); + const finalExtraParams = metadata ? { ...extraParams, metadata } : extraParams; + const run = { + id: runId, + name: name ?? llm.id[llm.id.length - 1], + parent_run_id: parentRunId, + start_time, + serialized: llm, + events: [ + { + name: "start", + time: new Date(start_time).toISOString() + } + ], + inputs: { messages }, + execution_order, + child_runs: [], + child_execution_order: execution_order, + run_type: "llm", + extra: finalExtraParams ?? {}, + tags: tags || [] + }; + return this._addRunToRunMap(run); + } + async handleChatModelStart(llm, messages, runId, parentRunId, extraParams, tags, metadata, name) { + const run = this.getRunById(runId) ?? this._createRunForChatModelStart(llm, messages, runId, parentRunId, extraParams, tags, metadata, name); + await this.onRunCreate?.(run); + await this.onLLMStart?.(run); + return run; + } + async handleLLMEnd(output, runId, _parentRunId, _tags, extraParams) { + const run = this.getRunById(runId); + if (!run || run?.run_type !== "llm") { + throw new Error("No LLM run to end."); + } + run.end_time = Date.now(); + run.outputs = output; + run.events.push({ + name: "end", + time: new Date(run.end_time).toISOString() + }); + run.extra = { ...run.extra, ...extraParams }; + await this.onLLMEnd?.(run); + await this._endTrace(run); + return run; + } + async handleLLMError(error, runId, _parentRunId, _tags, extraParams) { + const run = this.getRunById(runId); + if (!run || run?.run_type !== "llm") { + throw new Error("No LLM run to end."); + } + run.end_time = Date.now(); + run.error = this.stringifyError(error); + run.events.push({ + name: "error", + time: new Date(run.end_time).toISOString() + }); + run.extra = { ...run.extra, ...extraParams }; + await this.onLLMError?.(run); + await this._endTrace(run); + return run; + } + /** + * Create and add a run to the run map for chain start events. + * This must sometimes be done synchronously to avoid race conditions + * when callbacks are backgrounded, so we expose it as a separate method here. + */ + _createRunForChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, name) { + const execution_order = this._getExecutionOrder(parentRunId); + const start_time = Date.now(); + const run = { + id: runId, + name: name ?? chain.id[chain.id.length - 1], + parent_run_id: parentRunId, + start_time, + serialized: chain, + events: [ + { + name: "start", + time: new Date(start_time).toISOString() + } + ], + inputs, + execution_order, + child_execution_order: execution_order, + run_type: runType ?? "chain", + child_runs: [], + extra: metadata ? { metadata } : {}, + tags: tags || [] + }; + return this._addRunToRunMap(run); + } + async handleChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, name) { + const run = this.getRunById(runId) ?? this._createRunForChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, name); + await this.onRunCreate?.(run); + await this.onChainStart?.(run); + return run; + } + async handleChainEnd(outputs, runId, _parentRunId, _tags, kwargs) { + const run = this.getRunById(runId); + if (!run) { + throw new Error("No chain run to end."); + } + run.end_time = Date.now(); + run.outputs = _coerceToDict(outputs, "output"); + run.events.push({ + name: "end", + time: new Date(run.end_time).toISOString() + }); + if (kwargs?.inputs !== void 0) { + run.inputs = _coerceToDict(kwargs.inputs, "input"); + } + await this.onChainEnd?.(run); + await this._endTrace(run); + return run; + } + async handleChainError(error, runId, _parentRunId, _tags, kwargs) { + const run = this.getRunById(runId); + if (!run) { + throw new Error("No chain run to end."); + } + run.end_time = Date.now(); + run.error = this.stringifyError(error); + run.events.push({ + name: "error", + time: new Date(run.end_time).toISOString() + }); + if (kwargs?.inputs !== void 0) { + run.inputs = _coerceToDict(kwargs.inputs, "input"); + } + await this.onChainError?.(run); + await this._endTrace(run); + return run; + } + /** + * Create and add a run to the run map for tool start events. + * This must sometimes be done synchronously to avoid race conditions + * when callbacks are backgrounded, so we expose it as a separate method here. + */ + _createRunForToolStart(tool2, input, runId, parentRunId, tags, metadata, name) { + const execution_order = this._getExecutionOrder(parentRunId); + const start_time = Date.now(); + const run = { + id: runId, + name: name ?? tool2.id[tool2.id.length - 1], + parent_run_id: parentRunId, + start_time, + serialized: tool2, + events: [ + { + name: "start", + time: new Date(start_time).toISOString() + } + ], + inputs: { input }, + execution_order, + child_execution_order: execution_order, + run_type: "tool", + child_runs: [], + extra: metadata ? { metadata } : {}, + tags: tags || [] + }; + return this._addRunToRunMap(run); + } + async handleToolStart(tool2, input, runId, parentRunId, tags, metadata, name) { + const run = this.getRunById(runId) ?? this._createRunForToolStart(tool2, input, runId, parentRunId, tags, metadata, name); + await this.onRunCreate?.(run); + await this.onToolStart?.(run); + return run; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + async handleToolEnd(output, runId) { + const run = this.getRunById(runId); + if (!run || run?.run_type !== "tool") { + throw new Error("No tool run to end"); + } + run.end_time = Date.now(); + run.outputs = { output }; + run.events.push({ + name: "end", + time: new Date(run.end_time).toISOString() + }); + await this.onToolEnd?.(run); + await this._endTrace(run); + return run; + } + async handleToolError(error, runId) { + const run = this.getRunById(runId); + if (!run || run?.run_type !== "tool") { + throw new Error("No tool run to end"); + } + run.end_time = Date.now(); + run.error = this.stringifyError(error); + run.events.push({ + name: "error", + time: new Date(run.end_time).toISOString() + }); + await this.onToolError?.(run); + await this._endTrace(run); + return run; + } + async handleAgentAction(action, runId) { + const run = this.getRunById(runId); + if (!run || run?.run_type !== "chain") { + return; + } + const agentRun = run; + agentRun.actions = agentRun.actions || []; + agentRun.actions.push(action); + agentRun.events.push({ + name: "agent_action", + time: (/* @__PURE__ */ new Date()).toISOString(), + kwargs: { action } + }); + await this.onAgentAction?.(run); + } + async handleAgentEnd(action, runId) { + const run = this.getRunById(runId); + if (!run || run?.run_type !== "chain") { + return; + } + run.events.push({ + name: "agent_end", + time: (/* @__PURE__ */ new Date()).toISOString(), + kwargs: { action } + }); + await this.onAgentEnd?.(run); + } + /** + * Create and add a run to the run map for retriever start events. + * This must sometimes be done synchronously to avoid race conditions + * when callbacks are backgrounded, so we expose it as a separate method here. + */ + _createRunForRetrieverStart(retriever, query, runId, parentRunId, tags, metadata, name) { + const execution_order = this._getExecutionOrder(parentRunId); + const start_time = Date.now(); + const run = { + id: runId, + name: name ?? retriever.id[retriever.id.length - 1], + parent_run_id: parentRunId, + start_time, + serialized: retriever, + events: [ + { + name: "start", + time: new Date(start_time).toISOString() + } + ], + inputs: { query }, + execution_order, + child_execution_order: execution_order, + run_type: "retriever", + child_runs: [], + extra: metadata ? { metadata } : {}, + tags: tags || [] + }; + return this._addRunToRunMap(run); + } + async handleRetrieverStart(retriever, query, runId, parentRunId, tags, metadata, name) { + const run = this.getRunById(runId) ?? this._createRunForRetrieverStart(retriever, query, runId, parentRunId, tags, metadata, name); + await this.onRunCreate?.(run); + await this.onRetrieverStart?.(run); + return run; + } + async handleRetrieverEnd(documents, runId) { + const run = this.getRunById(runId); + if (!run || run?.run_type !== "retriever") { + throw new Error("No retriever run to end"); + } + run.end_time = Date.now(); + run.outputs = { documents }; + run.events.push({ + name: "end", + time: new Date(run.end_time).toISOString() + }); + await this.onRetrieverEnd?.(run); + await this._endTrace(run); + return run; + } + async handleRetrieverError(error, runId) { + const run = this.getRunById(runId); + if (!run || run?.run_type !== "retriever") { + throw new Error("No retriever run to end"); + } + run.end_time = Date.now(); + run.error = this.stringifyError(error); + run.events.push({ + name: "error", + time: new Date(run.end_time).toISOString() + }); + await this.onRetrieverError?.(run); + await this._endTrace(run); + return run; + } + async handleText(text, runId) { + const run = this.getRunById(runId); + if (!run || run?.run_type !== "chain") { + return; + } + run.events.push({ + name: "text", + time: (/* @__PURE__ */ new Date()).toISOString(), + kwargs: { text } + }); + await this.onText?.(run); + } + async handleLLMNewToken(token, idx, runId, _parentRunId, _tags, fields) { + const run = this.getRunById(runId); + if (!run || run?.run_type !== "llm") { + throw new Error(`Invalid "runId" provided to "handleLLMNewToken" callback.`); + } + run.events.push({ + name: "new_token", + time: (/* @__PURE__ */ new Date()).toISOString(), + kwargs: { token, idx, chunk: fields?.chunk } + }); + await this.onLLMNewToken?.(run, token, { chunk: fields?.chunk }); + return run; + } + }; + } +}); + +// node_modules/@langchain/core/dist/tracers/console.js +var console_exports = {}; +__export(console_exports, { + ConsoleCallbackHandler: () => ConsoleCallbackHandler +}); +function wrap(style, text) { + return `${style.open}${text}${style.close}`; +} +function tryJsonStringify(obj, fallback) { + try { + return JSON.stringify(obj, null, 2); + } catch (err) { + return fallback; + } +} +function formatKVMapItem(value) { + if (typeof value === "string") { + return value.trim(); + } + if (value === null || value === void 0) { + return value; + } + return tryJsonStringify(value, value.toString()); +} +function elapsed(run) { + if (!run.end_time) + return ""; + const elapsed2 = run.end_time - run.start_time; + if (elapsed2 < 1e3) { + return `${elapsed2}ms`; + } + return `${(elapsed2 / 1e3).toFixed(2)}s`; +} +var import_ansi_styles, color, ConsoleCallbackHandler; +var init_console = __esm({ + "node_modules/@langchain/core/dist/tracers/console.js"() { + import_ansi_styles = __toESM(require_ansi_styles(), 1); + init_base3(); + ({ color } = import_ansi_styles.default); + ConsoleCallbackHandler = class extends BaseTracer { + constructor() { + super(...arguments); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "console_callback_handler" + }); + } + /** + * Method used to persist the run. In this case, it simply returns a + * resolved promise as there's no persistence logic. + * @param _run The run to persist. + * @returns A resolved promise. + */ + persistRun(_run) { + return Promise.resolve(); + } + // utility methods + /** + * Method used to get all the parent runs of a given run. + * @param run The run whose parents are to be retrieved. + * @returns An array of parent runs. + */ + getParents(run) { + const parents = []; + let currentRun = run; + while (currentRun.parent_run_id) { + const parent = this.runMap.get(currentRun.parent_run_id); + if (parent) { + parents.push(parent); + currentRun = parent; + } else { + break; + } + } + return parents; + } + /** + * Method used to get a string representation of the run's lineage, which + * is used in logging. + * @param run The run whose lineage is to be retrieved. + * @returns A string representation of the run's lineage. + */ + getBreadcrumbs(run) { + const parents = this.getParents(run).reverse(); + const string = [...parents, run].map((parent, i, arr3) => { + const name = `${parent.execution_order}:${parent.run_type}:${parent.name}`; + return i === arr3.length - 1 ? wrap(import_ansi_styles.default.bold, name) : name; + }).join(" > "); + return wrap(color.grey, string); + } + // logging methods + /** + * Method used to log the start of a chain run. + * @param run The chain run that has started. + * @returns void + */ + onChainStart(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.green, "[chain/start]")} [${crumbs}] Entering Chain run with input: ${tryJsonStringify(run.inputs, "[inputs]")}`); + } + /** + * Method used to log the end of a chain run. + * @param run The chain run that has ended. + * @returns void + */ + onChainEnd(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.cyan, "[chain/end]")} [${crumbs}] [${elapsed(run)}] Exiting Chain run with output: ${tryJsonStringify(run.outputs, "[outputs]")}`); + } + /** + * Method used to log any errors of a chain run. + * @param run The chain run that has errored. + * @returns void + */ + onChainError(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.red, "[chain/error]")} [${crumbs}] [${elapsed(run)}] Chain run errored with error: ${tryJsonStringify(run.error, "[error]")}`); + } + /** + * Method used to log the start of an LLM run. + * @param run The LLM run that has started. + * @returns void + */ + onLLMStart(run) { + const crumbs = this.getBreadcrumbs(run); + const inputs = "prompts" in run.inputs ? { prompts: run.inputs.prompts.map((p) => p.trim()) } : run.inputs; + console.log(`${wrap(color.green, "[llm/start]")} [${crumbs}] Entering LLM run with input: ${tryJsonStringify(inputs, "[inputs]")}`); + } + /** + * Method used to log the end of an LLM run. + * @param run The LLM run that has ended. + * @returns void + */ + onLLMEnd(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.cyan, "[llm/end]")} [${crumbs}] [${elapsed(run)}] Exiting LLM run with output: ${tryJsonStringify(run.outputs, "[response]")}`); + } + /** + * Method used to log any errors of an LLM run. + * @param run The LLM run that has errored. + * @returns void + */ + onLLMError(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.red, "[llm/error]")} [${crumbs}] [${elapsed(run)}] LLM run errored with error: ${tryJsonStringify(run.error, "[error]")}`); + } + /** + * Method used to log the start of a tool run. + * @param run The tool run that has started. + * @returns void + */ + onToolStart(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.green, "[tool/start]")} [${crumbs}] Entering Tool run with input: "${formatKVMapItem(run.inputs.input)}"`); + } + /** + * Method used to log the end of a tool run. + * @param run The tool run that has ended. + * @returns void + */ + onToolEnd(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.cyan, "[tool/end]")} [${crumbs}] [${elapsed(run)}] Exiting Tool run with output: "${formatKVMapItem(run.outputs?.output)}"`); + } + /** + * Method used to log any errors of a tool run. + * @param run The tool run that has errored. + * @returns void + */ + onToolError(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.red, "[tool/error]")} [${crumbs}] [${elapsed(run)}] Tool run errored with error: ${tryJsonStringify(run.error, "[error]")}`); + } + /** + * Method used to log the start of a retriever run. + * @param run The retriever run that has started. + * @returns void + */ + onRetrieverStart(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.green, "[retriever/start]")} [${crumbs}] Entering Retriever run with input: ${tryJsonStringify(run.inputs, "[inputs]")}`); + } + /** + * Method used to log the end of a retriever run. + * @param run The retriever run that has ended. + * @returns void + */ + onRetrieverEnd(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.cyan, "[retriever/end]")} [${crumbs}] [${elapsed(run)}] Exiting Retriever run with output: ${tryJsonStringify(run.outputs, "[outputs]")}`); + } + /** + * Method used to log any errors of a retriever run. + * @param run The retriever run that has errored. + * @returns void + */ + onRetrieverError(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.red, "[retriever/error]")} [${crumbs}] [${elapsed(run)}] Retriever run errored with error: ${tryJsonStringify(run.error, "[error]")}`); + } + /** + * Method used to log the action selected by the agent. + * @param run The run in which the agent action occurred. + * @returns void + */ + onAgentAction(run) { + const agentRun = run; + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.blue, "[agent/action]")} [${crumbs}] Agent selected action: ${tryJsonStringify(agentRun.actions[agentRun.actions.length - 1], "[action]")}`); + } + }; + } +}); + +// node_modules/langsmith/index.js +var init_langsmith = __esm({ + "node_modules/langsmith/index.js"() { + init_dist(); + } +}); + +// node_modules/langsmith/dist/singletons/traceable.js +function getCurrentRunTree(permitAbsentRunTree = false) { + const runTree = AsyncLocalStorageProviderSingleton.getInstance().getStore(); + if (!permitAbsentRunTree && runTree === void 0) { + throw new Error("Could not get the current run tree.\n\nPlease make sure you are calling this method within a traceable function and that tracing is enabled."); + } + return runTree; +} +function isTraceableFunction(x) { + return typeof x === "function" && "langsmith:traceable" in x; +} +var MockAsyncLocalStorage, TRACING_ALS_KEY, mockAsyncLocalStorage, AsyncLocalStorageProvider, AsyncLocalStorageProviderSingleton, ROOT; +var init_traceable = __esm({ + "node_modules/langsmith/dist/singletons/traceable.js"() { + MockAsyncLocalStorage = class { + getStore() { + return void 0; + } + run(_, callback) { + return callback(); + } + }; + TRACING_ALS_KEY = Symbol.for("ls:tracing_async_local_storage"); + mockAsyncLocalStorage = new MockAsyncLocalStorage(); + AsyncLocalStorageProvider = class { + getInstance() { + return globalThis[TRACING_ALS_KEY] ?? mockAsyncLocalStorage; + } + initializeGlobalInstance(instance) { + if (globalThis[TRACING_ALS_KEY] === void 0) { + globalThis[TRACING_ALS_KEY] = instance; + } + } + }; + AsyncLocalStorageProviderSingleton = new AsyncLocalStorageProvider(); + ROOT = Symbol.for("langsmith:traceable:root"); + } +}); + +// node_modules/langsmith/singletons/traceable.js +var init_traceable2 = __esm({ + "node_modules/langsmith/singletons/traceable.js"() { + init_traceable(); + } +}); + +// node_modules/@langchain/core/dist/singletons/tracer.js +var client, getDefaultLangChainClientSingleton; +var init_tracer = __esm({ + "node_modules/@langchain/core/dist/singletons/tracer.js"() { + init_langsmith(); + init_env(); + getDefaultLangChainClientSingleton = () => { + if (client === void 0) { + const clientParams = getEnvironmentVariable("LANGCHAIN_CALLBACKS_BACKGROUND") === "false" ? { + // LangSmith has its own backgrounding system + blockOnRootRunFinalization: true + } : {}; + client = new Client(clientParams); + } + return client; + }; + } +}); + +// node_modules/@langchain/core/dist/tracers/tracer_langchain.js +var tracer_langchain_exports = {}; +__export(tracer_langchain_exports, { + LangChainTracer: () => LangChainTracer +}); +var LangChainTracer; +var init_tracer_langchain = __esm({ + "node_modules/@langchain/core/dist/tracers/tracer_langchain.js"() { + init_langsmith(); + init_run_trees2(); + init_traceable2(); + init_base3(); + init_tracer(); + LangChainTracer = class _LangChainTracer extends BaseTracer { + constructor(fields = {}) { + super(fields); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "langchain_tracer" + }); + Object.defineProperty(this, "projectName", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "exampleId", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "client", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "replicas", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "usesRunTreeMap", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + const { exampleId, projectName, client: client2, replicas } = fields; + this.projectName = projectName ?? getDefaultProjectName(); + this.replicas = replicas; + this.exampleId = exampleId; + this.client = client2 ?? getDefaultLangChainClientSingleton(); + const traceableTree = _LangChainTracer.getTraceableRunTree(); + if (traceableTree) { + this.updateFromRunTree(traceableTree); + } + } + async persistRun(_run) { + } + async onRunCreate(run) { + const runTree = this.getRunTreeWithTracingConfig(run.id); + await runTree?.postRun(); + } + async onRunUpdate(run) { + const runTree = this.getRunTreeWithTracingConfig(run.id); + await runTree?.patchRun(); + } + getRun(id) { + return this.runTreeMap.get(id); + } + updateFromRunTree(runTree) { + this.runTreeMap.set(runTree.id, runTree); + let rootRun = runTree; + const visited = /* @__PURE__ */ new Set(); + while (rootRun.parent_run) { + if (visited.has(rootRun.id)) + break; + visited.add(rootRun.id); + if (!rootRun.parent_run) + break; + rootRun = rootRun.parent_run; + } + visited.clear(); + const queue2 = [rootRun]; + while (queue2.length > 0) { + const current = queue2.shift(); + if (!current || visited.has(current.id)) + continue; + visited.add(current.id); + this.runTreeMap.set(current.id, current); + if (current.child_runs) { + queue2.push(...current.child_runs); + } + } + this.client = runTree.client ?? this.client; + this.replicas = runTree.replicas ?? this.replicas; + this.projectName = runTree.project_name ?? this.projectName; + this.exampleId = runTree.reference_example_id ?? this.exampleId; + } + getRunTreeWithTracingConfig(id) { + const runTree = this.runTreeMap.get(id); + if (!runTree) + return void 0; + return new RunTree({ + ...runTree, + client: this.client, + project_name: this.projectName, + replicas: this.replicas, + reference_example_id: this.exampleId, + tracingEnabled: true + }); + } + static getTraceableRunTree() { + try { + return ( + // The type cast here provides forward compatibility. Old versions of LangSmith will just + // ignore the permitAbsentRunTree arg. + getCurrentRunTree(true) + ); + } catch { + return void 0; + } + } + }; + } +}); + +// node_modules/@langchain/core/dist/singletons/async_local_storage/globals.js +var TRACING_ALS_KEY2, _CONTEXT_VARIABLES_KEY, setGlobalAsyncLocalStorageInstance, getGlobalAsyncLocalStorageInstance; +var init_globals = __esm({ + "node_modules/@langchain/core/dist/singletons/async_local_storage/globals.js"() { + TRACING_ALS_KEY2 = Symbol.for("ls:tracing_async_local_storage"); + _CONTEXT_VARIABLES_KEY = Symbol.for("lc:context_variables"); + setGlobalAsyncLocalStorageInstance = (instance) => { + globalThis[TRACING_ALS_KEY2] = instance; + }; + getGlobalAsyncLocalStorageInstance = () => { + return globalThis[TRACING_ALS_KEY2]; + }; + } +}); + +// node_modules/@langchain/core/dist/singletons/callbacks.js +function createQueue() { + const PQueue = "default" in import_p_queue2.default ? import_p_queue2.default.default : import_p_queue2.default; + return new PQueue({ + autoStart: true, + concurrency: 1 + }); +} +function getQueue() { + if (typeof queue === "undefined") { + queue = createQueue(); + } + return queue; +} +async function consumeCallback(promiseFn, wait2) { + if (wait2 === true) { + const asyncLocalStorageInstance = getGlobalAsyncLocalStorageInstance(); + if (asyncLocalStorageInstance !== void 0) { + await asyncLocalStorageInstance.run(void 0, async () => promiseFn()); + } else { + await promiseFn(); + } + } else { + queue = getQueue(); + void queue.add(async () => { + const asyncLocalStorageInstance = getGlobalAsyncLocalStorageInstance(); + if (asyncLocalStorageInstance !== void 0) { + await asyncLocalStorageInstance.run(void 0, async () => promiseFn()); + } else { + await promiseFn(); + } + }); + } +} +async function awaitAllCallbacks() { + const defaultClient = getDefaultLangChainClientSingleton(); + await Promise.allSettled([ + typeof queue !== "undefined" ? queue.onIdle() : Promise.resolve(), + defaultClient.awaitPendingTraceBatches() + ]); +} +var import_p_queue2, queue; +var init_callbacks = __esm({ + "node_modules/@langchain/core/dist/singletons/callbacks.js"() { + import_p_queue2 = __toESM(require_dist(), 1); + init_globals(); + init_tracer(); + } +}); + +// node_modules/@langchain/core/dist/callbacks/promises.js +var promises_exports = {}; +__export(promises_exports, { + awaitAllCallbacks: () => awaitAllCallbacks, + consumeCallback: () => consumeCallback +}); +var init_promises = __esm({ + "node_modules/@langchain/core/dist/callbacks/promises.js"() { + init_callbacks(); + } +}); + +// node_modules/@langchain/core/dist/utils/callbacks.js +var isTracingEnabled2; +var init_callbacks2 = __esm({ + "node_modules/@langchain/core/dist/utils/callbacks.js"() { + init_env(); + isTracingEnabled2 = (tracingEnabled) => { + if (tracingEnabled !== void 0) { + return tracingEnabled; + } + const envVars = [ + "LANGSMITH_TRACING_V2", + "LANGCHAIN_TRACING_V2", + "LANGSMITH_TRACING", + "LANGCHAIN_TRACING" + ]; + return !!envVars.find((envVar) => getEnvironmentVariable(envVar) === "true"); + }; + } +}); + +// node_modules/@langchain/core/dist/singletons/async_local_storage/context.js +function getContextVariable(name) { + const asyncLocalStorageInstance = getGlobalAsyncLocalStorageInstance(); + if (asyncLocalStorageInstance === void 0) { + return void 0; + } + const runTree = asyncLocalStorageInstance.getStore(); + return runTree?.[_CONTEXT_VARIABLES_KEY]?.[name]; +} +var LC_CONFIGURE_HOOKS_KEY, _getConfigureHooks; +var init_context = __esm({ + "node_modules/@langchain/core/dist/singletons/async_local_storage/context.js"() { + init_run_trees2(); + init_globals(); + LC_CONFIGURE_HOOKS_KEY = Symbol("lc:configure_hooks"); + _getConfigureHooks = () => getContextVariable(LC_CONFIGURE_HOOKS_KEY) || []; + } +}); + +// node_modules/@langchain/core/dist/callbacks/manager.js +var manager_exports = {}; +__export(manager_exports, { + BaseCallbackManager: () => BaseCallbackManager, + BaseRunManager: () => BaseRunManager, + CallbackManager: () => CallbackManager, + CallbackManagerForChainRun: () => CallbackManagerForChainRun, + CallbackManagerForLLMRun: () => CallbackManagerForLLMRun, + CallbackManagerForRetrieverRun: () => CallbackManagerForRetrieverRun, + CallbackManagerForToolRun: () => CallbackManagerForToolRun, + TraceGroup: () => TraceGroup, + ensureHandler: () => ensureHandler, + parseCallbackConfigArg: () => parseCallbackConfigArg, + traceAsGroup: () => traceAsGroup +}); +function parseCallbackConfigArg(arg) { + if (!arg) { + return {}; + } else if (Array.isArray(arg) || "name" in arg) { + return { callbacks: arg }; + } else { + return arg; + } +} +function ensureHandler(handler) { + if ("name" in handler) { + return handler; + } + return BaseCallbackHandler.fromMethods(handler); +} +function _coerceToDict2(value, defaultKey) { + return value && !Array.isArray(value) && typeof value === "object" ? value : { [defaultKey]: value }; +} +async function traceAsGroup(groupOptions, enclosedCode, ...args) { + const traceGroup = new TraceGroup(groupOptions.name, groupOptions); + const callbackManager = await traceGroup.start({ ...args }); + try { + const result = await enclosedCode(callbackManager, ...args); + await traceGroup.end(_coerceToDict2(result, "output")); + return result; + } catch (err) { + await traceGroup.error(err); + throw err; + } +} +var BaseCallbackManager, BaseRunManager, CallbackManagerForRetrieverRun, CallbackManagerForLLMRun, CallbackManagerForChainRun, CallbackManagerForToolRun, CallbackManager, TraceGroup; +var init_manager = __esm({ + "node_modules/@langchain/core/dist/callbacks/manager.js"() { + init_esm_browser(); + init_base2(); + init_console(); + init_utils2(); + init_env(); + init_tracer_langchain(); + init_promises(); + init_callbacks2(); + init_base3(); + init_context(); + BaseCallbackManager = class { + setHandler(handler) { + return this.setHandlers([handler]); + } + }; + BaseRunManager = class { + constructor(runId, handlers, inheritableHandlers, tags, inheritableTags, metadata, inheritableMetadata, _parentRunId) { + Object.defineProperty(this, "runId", { + enumerable: true, + configurable: true, + writable: true, + value: runId + }); + Object.defineProperty(this, "handlers", { + enumerable: true, + configurable: true, + writable: true, + value: handlers + }); + Object.defineProperty(this, "inheritableHandlers", { + enumerable: true, + configurable: true, + writable: true, + value: inheritableHandlers + }); + Object.defineProperty(this, "tags", { + enumerable: true, + configurable: true, + writable: true, + value: tags + }); + Object.defineProperty(this, "inheritableTags", { + enumerable: true, + configurable: true, + writable: true, + value: inheritableTags + }); + Object.defineProperty(this, "metadata", { + enumerable: true, + configurable: true, + writable: true, + value: metadata + }); + Object.defineProperty(this, "inheritableMetadata", { + enumerable: true, + configurable: true, + writable: true, + value: inheritableMetadata + }); + Object.defineProperty(this, "_parentRunId", { + enumerable: true, + configurable: true, + writable: true, + value: _parentRunId + }); + } + get parentRunId() { + return this._parentRunId; + } + async handleText(text) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + try { + await handler.handleText?.(text, this.runId, this._parentRunId, this.tags); + } catch (err) { + const logFunction = handler.raiseError ? console.error : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleText: ${err}`); + if (handler.raiseError) { + throw err; + } + } + }, handler.awaitHandlers))); + } + async handleCustomEvent(eventName, data, _runId, _tags, _metadata) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + try { + await handler.handleCustomEvent?.(eventName, data, this.runId, this.tags, this.metadata); + } catch (err) { + const logFunction = handler.raiseError ? console.error : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleCustomEvent: ${err}`); + if (handler.raiseError) { + throw err; + } + } + }, handler.awaitHandlers))); + } + }; + CallbackManagerForRetrieverRun = class extends BaseRunManager { + getChild(tag) { + const manager = new CallbackManager(this.runId); + manager.setHandlers(this.inheritableHandlers); + manager.addTags(this.inheritableTags); + manager.addMetadata(this.inheritableMetadata); + if (tag) { + manager.addTags([tag], false); + } + return manager; + } + async handleRetrieverEnd(documents) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreRetriever) { + try { + await handler.handleRetrieverEnd?.(documents, this.runId, this._parentRunId, this.tags); + } catch (err) { + const logFunction = handler.raiseError ? console.error : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleRetriever`); + if (handler.raiseError) { + throw err; + } + } + } + }, handler.awaitHandlers))); + } + async handleRetrieverError(err) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreRetriever) { + try { + await handler.handleRetrieverError?.(err, this.runId, this._parentRunId, this.tags); + } catch (error) { + const logFunction = handler.raiseError ? console.error : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleRetrieverError: ${error}`); + if (handler.raiseError) { + throw err; + } + } + } + }, handler.awaitHandlers))); + } + }; + CallbackManagerForLLMRun = class extends BaseRunManager { + async handleLLMNewToken(token, idx, _runId, _parentRunId, _tags, fields) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreLLM) { + try { + await handler.handleLLMNewToken?.(token, idx ?? { prompt: 0, completion: 0 }, this.runId, this._parentRunId, this.tags, fields); + } catch (err) { + const logFunction = handler.raiseError ? console.error : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleLLMNewToken: ${err}`); + if (handler.raiseError) { + throw err; + } + } + } + }, handler.awaitHandlers))); + } + async handleLLMError(err, _runId, _parentRunId, _tags, extraParams) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreLLM) { + try { + await handler.handleLLMError?.(err, this.runId, this._parentRunId, this.tags, extraParams); + } catch (err2) { + const logFunction = handler.raiseError ? console.error : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleLLMError: ${err2}`); + if (handler.raiseError) { + throw err2; + } + } + } + }, handler.awaitHandlers))); + } + async handleLLMEnd(output, _runId, _parentRunId, _tags, extraParams) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreLLM) { + try { + await handler.handleLLMEnd?.(output, this.runId, this._parentRunId, this.tags, extraParams); + } catch (err) { + const logFunction = handler.raiseError ? console.error : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleLLMEnd: ${err}`); + if (handler.raiseError) { + throw err; + } + } + } + }, handler.awaitHandlers))); + } + }; + CallbackManagerForChainRun = class extends BaseRunManager { + getChild(tag) { + const manager = new CallbackManager(this.runId); + manager.setHandlers(this.inheritableHandlers); + manager.addTags(this.inheritableTags); + manager.addMetadata(this.inheritableMetadata); + if (tag) { + manager.addTags([tag], false); + } + return manager; + } + async handleChainError(err, _runId, _parentRunId, _tags, kwargs) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreChain) { + try { + await handler.handleChainError?.(err, this.runId, this._parentRunId, this.tags, kwargs); + } catch (err2) { + const logFunction = handler.raiseError ? console.error : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleChainError: ${err2}`); + if (handler.raiseError) { + throw err2; + } + } + } + }, handler.awaitHandlers))); + } + async handleChainEnd(output, _runId, _parentRunId, _tags, kwargs) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreChain) { + try { + await handler.handleChainEnd?.(output, this.runId, this._parentRunId, this.tags, kwargs); + } catch (err) { + const logFunction = handler.raiseError ? console.error : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleChainEnd: ${err}`); + if (handler.raiseError) { + throw err; + } + } + } + }, handler.awaitHandlers))); + } + async handleAgentAction(action) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreAgent) { + try { + await handler.handleAgentAction?.(action, this.runId, this._parentRunId, this.tags); + } catch (err) { + const logFunction = handler.raiseError ? console.error : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleAgentAction: ${err}`); + if (handler.raiseError) { + throw err; + } + } + } + }, handler.awaitHandlers))); + } + async handleAgentEnd(action) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreAgent) { + try { + await handler.handleAgentEnd?.(action, this.runId, this._parentRunId, this.tags); + } catch (err) { + const logFunction = handler.raiseError ? console.error : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleAgentEnd: ${err}`); + if (handler.raiseError) { + throw err; + } + } + } + }, handler.awaitHandlers))); + } + }; + CallbackManagerForToolRun = class extends BaseRunManager { + getChild(tag) { + const manager = new CallbackManager(this.runId); + manager.setHandlers(this.inheritableHandlers); + manager.addTags(this.inheritableTags); + manager.addMetadata(this.inheritableMetadata); + if (tag) { + manager.addTags([tag], false); + } + return manager; + } + async handleToolError(err) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreAgent) { + try { + await handler.handleToolError?.(err, this.runId, this._parentRunId, this.tags); + } catch (err2) { + const logFunction = handler.raiseError ? console.error : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleToolError: ${err2}`); + if (handler.raiseError) { + throw err2; + } + } + } + }, handler.awaitHandlers))); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + async handleToolEnd(output) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreAgent) { + try { + await handler.handleToolEnd?.(output, this.runId, this._parentRunId, this.tags); + } catch (err) { + const logFunction = handler.raiseError ? console.error : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleToolEnd: ${err}`); + if (handler.raiseError) { + throw err; + } + } + } + }, handler.awaitHandlers))); + } + }; + CallbackManager = class _CallbackManager extends BaseCallbackManager { + constructor(parentRunId, options) { + super(); + Object.defineProperty(this, "handlers", { + enumerable: true, + configurable: true, + writable: true, + value: [] + }); + Object.defineProperty(this, "inheritableHandlers", { + enumerable: true, + configurable: true, + writable: true, + value: [] + }); + Object.defineProperty(this, "tags", { + enumerable: true, + configurable: true, + writable: true, + value: [] + }); + Object.defineProperty(this, "inheritableTags", { + enumerable: true, + configurable: true, + writable: true, + value: [] + }); + Object.defineProperty(this, "metadata", { + enumerable: true, + configurable: true, + writable: true, + value: {} + }); + Object.defineProperty(this, "inheritableMetadata", { + enumerable: true, + configurable: true, + writable: true, + value: {} + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "callback_manager" + }); + Object.defineProperty(this, "_parentRunId", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.handlers = options?.handlers ?? this.handlers; + this.inheritableHandlers = options?.inheritableHandlers ?? this.inheritableHandlers; + this.tags = options?.tags ?? this.tags; + this.inheritableTags = options?.inheritableTags ?? this.inheritableTags; + this.metadata = options?.metadata ?? this.metadata; + this.inheritableMetadata = options?.inheritableMetadata ?? this.inheritableMetadata; + this._parentRunId = parentRunId; + } + /** + * Gets the parent run ID, if any. + * + * @returns The parent run ID. + */ + getParentRunId() { + return this._parentRunId; + } + async handleLLMStart(llm, prompts, runId = void 0, _parentRunId = void 0, extraParams = void 0, _tags = void 0, _metadata = void 0, runName = void 0) { + return Promise.all(prompts.map(async (prompt, idx) => { + const runId_ = idx === 0 && runId ? runId : v4_default(); + await Promise.all(this.handlers.map((handler) => { + if (handler.ignoreLLM) { + return; + } + if (isBaseTracer(handler)) { + handler._createRunForLLMStart(llm, [prompt], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName); + } + return consumeCallback(async () => { + try { + await handler.handleLLMStart?.(llm, [prompt], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName); + } catch (err) { + const logFunction = handler.raiseError ? console.error : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleLLMStart: ${err}`); + if (handler.raiseError) { + throw err; + } + } + }, handler.awaitHandlers); + })); + return new CallbackManagerForLLMRun(runId_, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); + })); + } + async handleChatModelStart(llm, messages, runId = void 0, _parentRunId = void 0, extraParams = void 0, _tags = void 0, _metadata = void 0, runName = void 0) { + return Promise.all(messages.map(async (messageGroup, idx) => { + const runId_ = idx === 0 && runId ? runId : v4_default(); + await Promise.all(this.handlers.map((handler) => { + if (handler.ignoreLLM) { + return; + } + if (isBaseTracer(handler)) { + handler._createRunForChatModelStart(llm, [messageGroup], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName); + } + return consumeCallback(async () => { + try { + if (handler.handleChatModelStart) { + await handler.handleChatModelStart?.(llm, [messageGroup], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName); + } else if (handler.handleLLMStart) { + const messageString = getBufferString(messageGroup); + await handler.handleLLMStart?.(llm, [messageString], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName); + } + } catch (err) { + const logFunction = handler.raiseError ? console.error : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleLLMStart: ${err}`); + if (handler.raiseError) { + throw err; + } + } + }, handler.awaitHandlers); + })); + return new CallbackManagerForLLMRun(runId_, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); + })); + } + async handleChainStart(chain, inputs, runId = v4_default(), runType = void 0, _tags = void 0, _metadata = void 0, runName = void 0) { + await Promise.all(this.handlers.map((handler) => { + if (handler.ignoreChain) { + return; + } + if (isBaseTracer(handler)) { + handler._createRunForChainStart(chain, inputs, runId, this._parentRunId, this.tags, this.metadata, runType, runName); + } + return consumeCallback(async () => { + try { + await handler.handleChainStart?.(chain, inputs, runId, this._parentRunId, this.tags, this.metadata, runType, runName); + } catch (err) { + const logFunction = handler.raiseError ? console.error : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleChainStart: ${err}`); + if (handler.raiseError) { + throw err; + } + } + }, handler.awaitHandlers); + })); + return new CallbackManagerForChainRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); + } + async handleToolStart(tool2, input, runId = v4_default(), _parentRunId = void 0, _tags = void 0, _metadata = void 0, runName = void 0) { + await Promise.all(this.handlers.map((handler) => { + if (handler.ignoreAgent) { + return; + } + if (isBaseTracer(handler)) { + handler._createRunForToolStart(tool2, input, runId, this._parentRunId, this.tags, this.metadata, runName); + } + return consumeCallback(async () => { + try { + await handler.handleToolStart?.(tool2, input, runId, this._parentRunId, this.tags, this.metadata, runName); + } catch (err) { + const logFunction = handler.raiseError ? console.error : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleToolStart: ${err}`); + if (handler.raiseError) { + throw err; + } + } + }, handler.awaitHandlers); + })); + return new CallbackManagerForToolRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); + } + async handleRetrieverStart(retriever, query, runId = v4_default(), _parentRunId = void 0, _tags = void 0, _metadata = void 0, runName = void 0) { + await Promise.all(this.handlers.map((handler) => { + if (handler.ignoreRetriever) { + return; + } + if (isBaseTracer(handler)) { + handler._createRunForRetrieverStart(retriever, query, runId, this._parentRunId, this.tags, this.metadata, runName); + } + return consumeCallback(async () => { + try { + await handler.handleRetrieverStart?.(retriever, query, runId, this._parentRunId, this.tags, this.metadata, runName); + } catch (err) { + const logFunction = handler.raiseError ? console.error : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleRetrieverStart: ${err}`); + if (handler.raiseError) { + throw err; + } + } + }, handler.awaitHandlers); + })); + return new CallbackManagerForRetrieverRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); + } + async handleCustomEvent(eventName, data, runId, _tags, _metadata) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreCustomEvent) { + try { + await handler.handleCustomEvent?.(eventName, data, runId, this.tags, this.metadata); + } catch (err) { + const logFunction = handler.raiseError ? console.error : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleCustomEvent: ${err}`); + if (handler.raiseError) { + throw err; + } + } + } + }, handler.awaitHandlers))); + } + addHandler(handler, inherit = true) { + this.handlers.push(handler); + if (inherit) { + this.inheritableHandlers.push(handler); + } + } + removeHandler(handler) { + this.handlers = this.handlers.filter((_handler) => _handler !== handler); + this.inheritableHandlers = this.inheritableHandlers.filter((_handler) => _handler !== handler); + } + setHandlers(handlers, inherit = true) { + this.handlers = []; + this.inheritableHandlers = []; + for (const handler of handlers) { + this.addHandler(handler, inherit); + } + } + addTags(tags, inherit = true) { + this.removeTags(tags); + this.tags.push(...tags); + if (inherit) { + this.inheritableTags.push(...tags); + } + } + removeTags(tags) { + this.tags = this.tags.filter((tag) => !tags.includes(tag)); + this.inheritableTags = this.inheritableTags.filter((tag) => !tags.includes(tag)); + } + addMetadata(metadata, inherit = true) { + this.metadata = { ...this.metadata, ...metadata }; + if (inherit) { + this.inheritableMetadata = { ...this.inheritableMetadata, ...metadata }; + } + } + removeMetadata(metadata) { + for (const key of Object.keys(metadata)) { + delete this.metadata[key]; + delete this.inheritableMetadata[key]; + } + } + copy(additionalHandlers = [], inherit = true) { + const manager = new _CallbackManager(this._parentRunId); + for (const handler of this.handlers) { + const inheritable = this.inheritableHandlers.includes(handler); + manager.addHandler(handler, inheritable); + } + for (const tag of this.tags) { + const inheritable = this.inheritableTags.includes(tag); + manager.addTags([tag], inheritable); + } + for (const key of Object.keys(this.metadata)) { + const inheritable = Object.keys(this.inheritableMetadata).includes(key); + manager.addMetadata({ [key]: this.metadata[key] }, inheritable); + } + for (const handler of additionalHandlers) { + if ( + // Prevent multiple copies of console_callback_handler + manager.handlers.filter((h) => h.name === "console_callback_handler").some((h) => h.name === handler.name) + ) { + continue; + } + manager.addHandler(handler, inherit); + } + return manager; + } + static fromHandlers(handlers) { + class Handler extends BaseCallbackHandler { + constructor() { + super(); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: v4_default() + }); + Object.assign(this, handlers); + } + } + const manager = new this(); + manager.addHandler(new Handler()); + return manager; + } + static configure(inheritableHandlers, localHandlers, inheritableTags, localTags, inheritableMetadata, localMetadata, options) { + return this._configureSync(inheritableHandlers, localHandlers, inheritableTags, localTags, inheritableMetadata, localMetadata, options); + } + // TODO: Deprecate async method in favor of this one. + static _configureSync(inheritableHandlers, localHandlers, inheritableTags, localTags, inheritableMetadata, localMetadata, options) { + let callbackManager; + if (inheritableHandlers || localHandlers) { + if (Array.isArray(inheritableHandlers) || !inheritableHandlers) { + callbackManager = new _CallbackManager(); + callbackManager.setHandlers(inheritableHandlers?.map(ensureHandler) ?? [], true); + } else { + callbackManager = inheritableHandlers; + } + callbackManager = callbackManager.copy(Array.isArray(localHandlers) ? localHandlers.map(ensureHandler) : localHandlers?.handlers, false); + } + const verboseEnabled = getEnvironmentVariable("LANGCHAIN_VERBOSE") === "true" || options?.verbose; + const tracingV2Enabled = LangChainTracer.getTraceableRunTree()?.tracingEnabled || isTracingEnabled2(); + const tracingEnabled = tracingV2Enabled || (getEnvironmentVariable("LANGCHAIN_TRACING") ?? false); + if (verboseEnabled || tracingEnabled) { + if (!callbackManager) { + callbackManager = new _CallbackManager(); + } + if (verboseEnabled && !callbackManager.handlers.some((handler) => handler.name === ConsoleCallbackHandler.prototype.name)) { + const consoleHandler = new ConsoleCallbackHandler(); + callbackManager.addHandler(consoleHandler, true); + } + if (tracingEnabled && !callbackManager.handlers.some((handler) => handler.name === "langchain_tracer")) { + if (tracingV2Enabled) { + const tracerV2 = new LangChainTracer(); + callbackManager.addHandler(tracerV2, true); + callbackManager._parentRunId = LangChainTracer.getTraceableRunTree()?.id ?? callbackManager._parentRunId; + } + } + } + for (const { contextVar, inheritable = true, handlerClass, envVar } of _getConfigureHooks()) { + const createIfNotInContext = envVar && getEnvironmentVariable(envVar) === "true" && handlerClass; + let handler; + const contextVarValue = contextVar !== void 0 ? getContextVariable(contextVar) : void 0; + if (contextVarValue && isBaseCallbackHandler(contextVarValue)) { + handler = contextVarValue; + } else if (createIfNotInContext) { + handler = new handlerClass({}); + } + if (handler !== void 0) { + if (!callbackManager) { + callbackManager = new _CallbackManager(); + } + if (!callbackManager.handlers.some((h) => h.name === handler.name)) { + callbackManager.addHandler(handler, inheritable); + } + } + } + if (inheritableTags || localTags) { + if (callbackManager) { + callbackManager.addTags(inheritableTags ?? []); + callbackManager.addTags(localTags ?? [], false); + } + } + if (inheritableMetadata || localMetadata) { + if (callbackManager) { + callbackManager.addMetadata(inheritableMetadata ?? {}); + callbackManager.addMetadata(localMetadata ?? {}, false); + } + } + return callbackManager; + } + }; + TraceGroup = class { + constructor(groupName, options) { + Object.defineProperty(this, "groupName", { + enumerable: true, + configurable: true, + writable: true, + value: groupName + }); + Object.defineProperty(this, "options", { + enumerable: true, + configurable: true, + writable: true, + value: options + }); + Object.defineProperty(this, "runManager", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + } + async getTraceGroupCallbackManager(group_name, inputs, options) { + const cb = new LangChainTracer(options); + const cm = await CallbackManager.configure([cb]); + const runManager = await cm?.handleChainStart({ + lc: 1, + type: "not_implemented", + id: ["langchain", "callbacks", "groups", group_name] + }, inputs ?? {}); + if (!runManager) { + throw new Error("Failed to create run group callback manager."); + } + return runManager; + } + async start(inputs) { + if (!this.runManager) { + this.runManager = await this.getTraceGroupCallbackManager(this.groupName, inputs, this.options); + } + return this.runManager.getChild(); + } + async error(err) { + if (this.runManager) { + await this.runManager.handleChainError(err); + this.runManager = void 0; + } + } + async end(output) { + if (this.runManager) { + await this.runManager.handleChainEnd(output ?? {}); + this.runManager = void 0; + } + } + }; + } +}); + +// node_modules/zod/v3/helpers/util.js +var util, objectUtil, ZodParsedType, getParsedType; +var init_util = __esm({ + "node_modules/zod/v3/helpers/util.js"() { + (function(util2) { + util2.assertEqual = (_) => { + }; + function assertIs2(_arg) { + } + util2.assertIs = assertIs2; + function assertNever2(_x) { + throw new Error(); + } + util2.assertNever = assertNever2; + util2.arrayToEnum = (items) => { + const obj = {}; + for (const item of items) { + obj[item] = item; + } + return obj; + }; + util2.getValidEnumValues = (obj) => { + const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); + const filtered = {}; + for (const k of validKeys) { + filtered[k] = obj[k]; + } + return util2.objectValues(filtered); + }; + util2.objectValues = (obj) => { + return util2.objectKeys(obj).map(function(e) { + return obj[e]; + }); + }; + util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => { + const keys = []; + for (const key in object) { + if (Object.prototype.hasOwnProperty.call(object, key)) { + keys.push(key); + } + } + return keys; + }; + util2.find = (arr3, checker) => { + for (const item of arr3) { + if (checker(item)) + return item; + } + return void 0; + }; + util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val; + function joinValues2(array, separator = " | ") { + return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator); + } + util2.joinValues = joinValues2; + util2.jsonStringifyReplacer = (_, value) => { + if (typeof value === "bigint") { + return value.toString(); + } + return value; + }; + })(util || (util = {})); + (function(objectUtil2) { + objectUtil2.mergeShapes = (first, second) => { + return { + ...first, + ...second + // second overwrites first + }; + }; + })(objectUtil || (objectUtil = {})); + ZodParsedType = util.arrayToEnum([ + "string", + "nan", + "number", + "integer", + "float", + "boolean", + "date", + "bigint", + "symbol", + "function", + "undefined", + "null", + "array", + "object", + "unknown", + "promise", + "void", + "never", + "map", + "set" + ]); + getParsedType = (data) => { + const t = typeof data; + switch (t) { + case "undefined": + return ZodParsedType.undefined; + case "string": + return ZodParsedType.string; + case "number": + return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number; + case "boolean": + return ZodParsedType.boolean; + case "function": + return ZodParsedType.function; + case "bigint": + return ZodParsedType.bigint; + case "symbol": + return ZodParsedType.symbol; + case "object": + if (Array.isArray(data)) { + return ZodParsedType.array; + } + if (data === null) { + return ZodParsedType.null; + } + if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { + return ZodParsedType.promise; + } + if (typeof Map !== "undefined" && data instanceof Map) { + return ZodParsedType.map; + } + if (typeof Set !== "undefined" && data instanceof Set) { + return ZodParsedType.set; + } + if (typeof Date !== "undefined" && data instanceof Date) { + return ZodParsedType.date; + } + return ZodParsedType.object; + default: + return ZodParsedType.unknown; + } + }; + } +}); + +// node_modules/zod/v3/ZodError.js +var ZodIssueCode, quotelessJson, ZodError; +var init_ZodError = __esm({ + "node_modules/zod/v3/ZodError.js"() { + init_util(); + ZodIssueCode = util.arrayToEnum([ + "invalid_type", + "invalid_literal", + "custom", + "invalid_union", + "invalid_union_discriminator", + "invalid_enum_value", + "unrecognized_keys", + "invalid_arguments", + "invalid_return_type", + "invalid_date", + "invalid_string", + "too_small", + "too_big", + "invalid_intersection_types", + "not_multiple_of", + "not_finite" + ]); + quotelessJson = (obj) => { + const json = JSON.stringify(obj, null, 2); + return json.replace(/"([^"]+)":/g, "$1:"); + }; + ZodError = class _ZodError extends Error { + get errors() { + return this.issues; + } + constructor(issues) { + super(); + this.issues = []; + this.addIssue = (sub) => { + this.issues = [...this.issues, sub]; + }; + this.addIssues = (subs = []) => { + this.issues = [...this.issues, ...subs]; + }; + const actualProto = new.target.prototype; + if (Object.setPrototypeOf) { + Object.setPrototypeOf(this, actualProto); + } else { + this.__proto__ = actualProto; + } + this.name = "ZodError"; + this.issues = issues; + } + format(_mapper) { + const mapper = _mapper || function(issue2) { + return issue2.message; + }; + const fieldErrors = { _errors: [] }; + const processError = (error) => { + for (const issue2 of error.issues) { + if (issue2.code === "invalid_union") { + issue2.unionErrors.map(processError); + } else if (issue2.code === "invalid_return_type") { + processError(issue2.returnTypeError); + } else if (issue2.code === "invalid_arguments") { + processError(issue2.argumentsError); + } else if (issue2.path.length === 0) { + fieldErrors._errors.push(mapper(issue2)); + } else { + let curr = fieldErrors; + let i = 0; + while (i < issue2.path.length) { + const el = issue2.path[i]; + const terminal = i === issue2.path.length - 1; + if (!terminal) { + curr[el] = curr[el] || { _errors: [] }; + } else { + curr[el] = curr[el] || { _errors: [] }; + curr[el]._errors.push(mapper(issue2)); + } + curr = curr[el]; + i++; + } + } + } + }; + processError(this); + return fieldErrors; + } + static assert(value) { + if (!(value instanceof _ZodError)) { + throw new Error(`Not a ZodError: ${value}`); + } + } + toString() { + return this.message; + } + get message() { + return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2); + } + get isEmpty() { + return this.issues.length === 0; + } + flatten(mapper = (issue2) => issue2.message) { + const fieldErrors = {}; + const formErrors = []; + for (const sub of this.issues) { + if (sub.path.length > 0) { + const firstEl = sub.path[0]; + fieldErrors[firstEl] = fieldErrors[firstEl] || []; + fieldErrors[firstEl].push(mapper(sub)); + } else { + formErrors.push(mapper(sub)); + } + } + return { formErrors, fieldErrors }; + } + get formErrors() { + return this.flatten(); + } + }; + ZodError.create = (issues) => { + const error = new ZodError(issues); + return error; + }; + } +}); + +// node_modules/zod/v3/locales/en.js +var errorMap, en_default; +var init_en = __esm({ + "node_modules/zod/v3/locales/en.js"() { + init_ZodError(); + init_util(); + errorMap = (issue2, _ctx) => { + let message; + switch (issue2.code) { + case ZodIssueCode.invalid_type: + if (issue2.received === ZodParsedType.undefined) { + message = "Required"; + } else { + message = `Expected ${issue2.expected}, received ${issue2.received}`; + } + break; + case ZodIssueCode.invalid_literal: + message = `Invalid literal value, expected ${JSON.stringify(issue2.expected, util.jsonStringifyReplacer)}`; + break; + case ZodIssueCode.unrecognized_keys: + message = `Unrecognized key(s) in object: ${util.joinValues(issue2.keys, ", ")}`; + break; + case ZodIssueCode.invalid_union: + message = `Invalid input`; + break; + case ZodIssueCode.invalid_union_discriminator: + message = `Invalid discriminator value. Expected ${util.joinValues(issue2.options)}`; + break; + case ZodIssueCode.invalid_enum_value: + message = `Invalid enum value. Expected ${util.joinValues(issue2.options)}, received '${issue2.received}'`; + break; + case ZodIssueCode.invalid_arguments: + message = `Invalid function arguments`; + break; + case ZodIssueCode.invalid_return_type: + message = `Invalid function return type`; + break; + case ZodIssueCode.invalid_date: + message = `Invalid date`; + break; + case ZodIssueCode.invalid_string: + if (typeof issue2.validation === "object") { + if ("includes" in issue2.validation) { + message = `Invalid input: must include "${issue2.validation.includes}"`; + if (typeof issue2.validation.position === "number") { + message = `${message} at one or more positions greater than or equal to ${issue2.validation.position}`; + } + } else if ("startsWith" in issue2.validation) { + message = `Invalid input: must start with "${issue2.validation.startsWith}"`; + } else if ("endsWith" in issue2.validation) { + message = `Invalid input: must end with "${issue2.validation.endsWith}"`; + } else { + util.assertNever(issue2.validation); + } + } else if (issue2.validation !== "regex") { + message = `Invalid ${issue2.validation}`; + } else { + message = "Invalid"; + } + break; + case ZodIssueCode.too_small: + if (issue2.type === "array") + message = `Array must contain ${issue2.exact ? "exactly" : issue2.inclusive ? `at least` : `more than`} ${issue2.minimum} element(s)`; + else if (issue2.type === "string") + message = `String must contain ${issue2.exact ? "exactly" : issue2.inclusive ? `at least` : `over`} ${issue2.minimum} character(s)`; + else if (issue2.type === "number") + message = `Number must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${issue2.minimum}`; + else if (issue2.type === "bigint") + message = `Number must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${issue2.minimum}`; + else if (issue2.type === "date") + message = `Date must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue2.minimum))}`; + else + message = "Invalid input"; + break; + case ZodIssueCode.too_big: + if (issue2.type === "array") + message = `Array must contain ${issue2.exact ? `exactly` : issue2.inclusive ? `at most` : `less than`} ${issue2.maximum} element(s)`; + else if (issue2.type === "string") + message = `String must contain ${issue2.exact ? `exactly` : issue2.inclusive ? `at most` : `under`} ${issue2.maximum} character(s)`; + else if (issue2.type === "number") + message = `Number must be ${issue2.exact ? `exactly` : issue2.inclusive ? `less than or equal to` : `less than`} ${issue2.maximum}`; + else if (issue2.type === "bigint") + message = `BigInt must be ${issue2.exact ? `exactly` : issue2.inclusive ? `less than or equal to` : `less than`} ${issue2.maximum}`; + else if (issue2.type === "date") + message = `Date must be ${issue2.exact ? `exactly` : issue2.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue2.maximum))}`; + else + message = "Invalid input"; + break; + case ZodIssueCode.custom: + message = `Invalid input`; + break; + case ZodIssueCode.invalid_intersection_types: + message = `Intersection results could not be merged`; + break; + case ZodIssueCode.not_multiple_of: + message = `Number must be a multiple of ${issue2.multipleOf}`; + break; + case ZodIssueCode.not_finite: + message = "Number must be finite"; + break; + default: + message = _ctx.defaultError; + util.assertNever(issue2); + } + return { message }; + }; + en_default = errorMap; + } +}); + +// node_modules/zod/v3/errors.js +function setErrorMap(map) { + overrideErrorMap = map; +} +function getErrorMap() { + return overrideErrorMap; +} +var overrideErrorMap; +var init_errors2 = __esm({ + "node_modules/zod/v3/errors.js"() { + init_en(); + overrideErrorMap = en_default; + } +}); + +// node_modules/zod/v3/helpers/parseUtil.js +function addIssueToContext(ctx, issueData) { + const overrideMap = getErrorMap(); + const issue2 = makeIssue({ + issueData, + data: ctx.data, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, + // contextual error map is first priority + ctx.schemaErrorMap, + // then schema-bound map if available + overrideMap, + // then global override map + overrideMap === en_default ? void 0 : en_default + // then global default map + ].filter((x) => !!x) + }); + ctx.common.issues.push(issue2); +} +var makeIssue, EMPTY_PATH, ParseStatus, INVALID, DIRTY, OK, isAborted, isDirty, isValid, isAsync; +var init_parseUtil = __esm({ + "node_modules/zod/v3/helpers/parseUtil.js"() { + init_errors2(); + init_en(); + makeIssue = (params) => { + const { data, path, errorMaps, issueData } = params; + const fullPath = [...path, ...issueData.path || []]; + const fullIssue = { + ...issueData, + path: fullPath + }; + if (issueData.message !== void 0) { + return { + ...issueData, + path: fullPath, + message: issueData.message + }; + } + let errorMessage = ""; + const maps = errorMaps.filter((m) => !!m).slice().reverse(); + for (const map of maps) { + errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message; + } + return { + ...issueData, + path: fullPath, + message: errorMessage + }; + }; + EMPTY_PATH = []; + ParseStatus = class _ParseStatus { + constructor() { + this.value = "valid"; + } + dirty() { + if (this.value === "valid") + this.value = "dirty"; + } + abort() { + if (this.value !== "aborted") + this.value = "aborted"; + } + static mergeArray(status, results) { + const arrayValue = []; + for (const s of results) { + if (s.status === "aborted") + return INVALID; + if (s.status === "dirty") + status.dirty(); + arrayValue.push(s.value); + } + return { status: status.value, value: arrayValue }; + } + static async mergeObjectAsync(status, pairs) { + const syncPairs = []; + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + syncPairs.push({ + key, + value + }); + } + return _ParseStatus.mergeObjectSync(status, syncPairs); + } + static mergeObjectSync(status, pairs) { + const finalObject = {}; + for (const pair of pairs) { + const { key, value } = pair; + if (key.status === "aborted") + return INVALID; + if (value.status === "aborted") + return INVALID; + if (key.status === "dirty") + status.dirty(); + if (value.status === "dirty") + status.dirty(); + if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) { + finalObject[key.value] = value.value; + } + } + return { status: status.value, value: finalObject }; + } + }; + INVALID = Object.freeze({ + status: "aborted" + }); + DIRTY = (value) => ({ status: "dirty", value }); + OK = (value) => ({ status: "valid", value }); + isAborted = (x) => x.status === "aborted"; + isDirty = (x) => x.status === "dirty"; + isValid = (x) => x.status === "valid"; + isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise; + } +}); + +// node_modules/zod/v3/helpers/typeAliases.js +var init_typeAliases = __esm({ + "node_modules/zod/v3/helpers/typeAliases.js"() { + } +}); + +// node_modules/zod/v3/helpers/errorUtil.js +var errorUtil; +var init_errorUtil = __esm({ + "node_modules/zod/v3/helpers/errorUtil.js"() { + (function(errorUtil2) { + errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {}; + errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message; + })(errorUtil || (errorUtil = {})); + } +}); + +// node_modules/zod/v3/types.js +function processCreateParams(params) { + if (!params) + return {}; + const { errorMap: errorMap2, invalid_type_error, required_error, description } = params; + if (errorMap2 && (invalid_type_error || required_error)) { + throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); + } + if (errorMap2) + return { errorMap: errorMap2, description }; + const customMap = (iss, ctx) => { + const { message } = params; + if (iss.code === "invalid_enum_value") { + return { message: message ?? ctx.defaultError }; + } + if (typeof ctx.data === "undefined") { + return { message: message ?? required_error ?? ctx.defaultError }; + } + if (iss.code !== "invalid_type") + return { message: ctx.defaultError }; + return { message: message ?? invalid_type_error ?? ctx.defaultError }; + }; + return { errorMap: customMap, description }; +} +function timeRegexSource(args) { + let secondsRegexSource = `[0-5]\\d`; + if (args.precision) { + secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`; + } else if (args.precision == null) { + secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`; + } + const secondsQuantifier = args.precision ? "+" : "?"; + return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`; +} +function timeRegex(args) { + return new RegExp(`^${timeRegexSource(args)}$`); +} +function datetimeRegex(args) { + let regex2 = `${dateRegexSource}T${timeRegexSource(args)}`; + const opts = []; + opts.push(args.local ? `Z?` : `Z`); + if (args.offset) + opts.push(`([+-]\\d{2}:?\\d{2})`); + regex2 = `${regex2}(${opts.join("|")})`; + return new RegExp(`^${regex2}$`); +} +function isValidIP(ip, version2) { + if ((version2 === "v4" || !version2) && ipv4Regex.test(ip)) { + return true; + } + if ((version2 === "v6" || !version2) && ipv6Regex.test(ip)) { + return true; + } + return false; +} +function isValidJWT(jwt, alg) { + if (!jwtRegex.test(jwt)) + return false; + try { + const [header] = jwt.split("."); + if (!header) + return false; + const base642 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "="); + const decoded = JSON.parse(atob(base642)); + if (typeof decoded !== "object" || decoded === null) + return false; + if ("typ" in decoded && decoded?.typ !== "JWT") + return false; + if (!decoded.alg) + return false; + if (alg && decoded.alg !== alg) + return false; + return true; + } catch { + return false; + } +} +function isValidCidr(ip, version2) { + if ((version2 === "v4" || !version2) && ipv4CidrRegex.test(ip)) { + return true; + } + if ((version2 === "v6" || !version2) && ipv6CidrRegex.test(ip)) { + return true; + } + return false; +} +function floatSafeRemainder(val, step) { + const valDecCount = (val.toString().split(".")[1] || "").length; + const stepDecCount = (step.toString().split(".")[1] || "").length; + const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; + const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); + const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); + return valInt % stepInt / 10 ** decCount; +} +function deepPartialify(schema) { + if (schema instanceof ZodObject) { + const newShape = {}; + for (const key in schema.shape) { + const fieldSchema = schema.shape[key]; + newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); + } + return new ZodObject({ + ...schema._def, + shape: () => newShape + }); + } else if (schema instanceof ZodArray) { + return new ZodArray({ + ...schema._def, + type: deepPartialify(schema.element) + }); + } else if (schema instanceof ZodOptional) { + return ZodOptional.create(deepPartialify(schema.unwrap())); + } else if (schema instanceof ZodNullable) { + return ZodNullable.create(deepPartialify(schema.unwrap())); + } else if (schema instanceof ZodTuple) { + return ZodTuple.create(schema.items.map((item) => deepPartialify(item))); + } else { + return schema; + } +} +function mergeValues(a, b) { + const aType = getParsedType(a); + const bType = getParsedType(b); + if (a === b) { + return { valid: true, data: a }; + } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { + const bKeys = util.objectKeys(b); + const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1); + const newObj = { ...a, ...b }; + for (const key of sharedKeys) { + const sharedValue = mergeValues(a[key], b[key]); + if (!sharedValue.valid) { + return { valid: false }; + } + newObj[key] = sharedValue.data; + } + return { valid: true, data: newObj }; + } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) { + if (a.length !== b.length) { + return { valid: false }; + } + const newArray = []; + for (let index2 = 0; index2 < a.length; index2++) { + const itemA = a[index2]; + const itemB = b[index2]; + const sharedValue = mergeValues(itemA, itemB); + if (!sharedValue.valid) { + return { valid: false }; + } + newArray.push(sharedValue.data); + } + return { valid: true, data: newArray }; + } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) { + return { valid: true, data: a }; + } else { + return { valid: false }; + } +} +function createZodEnum(values, params) { + return new ZodEnum({ + values, + typeName: ZodFirstPartyTypeKind.ZodEnum, + ...processCreateParams(params) + }); +} +function cleanParams(params, data) { + const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params; + const p2 = typeof p === "string" ? { message: p } : p; + return p2; +} +function custom(check, _params = {}, fatal) { + if (check) + return ZodAny.create().superRefine((data, ctx) => { + const r = check(data); + if (r instanceof Promise) { + return r.then((r2) => { + if (!r2) { + const params = cleanParams(_params, data); + const _fatal = params.fatal ?? fatal ?? true; + ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); + } + }); + } + if (!r) { + const params = cleanParams(_params, data); + const _fatal = params.fatal ?? fatal ?? true; + ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); + } + return; + }); + return ZodAny.create(); +} +var ParseInputLazyPath, handleResult, ZodType, cuidRegex, cuid2Regex, ulidRegex, uuidRegex, nanoidRegex, jwtRegex, durationRegex, emailRegex, _emojiRegex, emojiRegex, ipv4Regex, ipv4CidrRegex, ipv6Regex, ipv6CidrRegex, base64Regex, base64urlRegex, dateRegexSource, dateRegex, ZodString, ZodNumber, ZodBigInt, ZodBoolean, ZodDate, ZodSymbol, ZodUndefined, ZodNull, ZodAny, ZodUnknown, ZodNever, ZodVoid, ZodArray, ZodObject, ZodUnion, getDiscriminator, ZodDiscriminatedUnion, ZodIntersection, ZodTuple, ZodRecord, ZodMap, ZodSet, ZodFunction, ZodLazy, ZodLiteral, ZodEnum, ZodNativeEnum, ZodPromise, ZodEffects, ZodOptional, ZodNullable, ZodDefault, ZodCatch, ZodNaN, BRAND, ZodBranded, ZodPipeline, ZodReadonly, late, ZodFirstPartyTypeKind, instanceOfType, stringType, numberType, nanType, bigIntType, booleanType, dateType, symbolType, undefinedType, nullType, anyType, unknownType, neverType, voidType, arrayType, objectType, strictObjectType, unionType, discriminatedUnionType, intersectionType, tupleType, recordType, mapType, setType, functionType, lazyType, literalType, enumType, nativeEnumType, promiseType, effectsType, optionalType, nullableType, preprocessType, pipelineType, ostring, onumber, oboolean, coerce, NEVER; +var init_types = __esm({ + "node_modules/zod/v3/types.js"() { + init_ZodError(); + init_errors2(); + init_errorUtil(); + init_parseUtil(); + init_util(); + ParseInputLazyPath = class { + constructor(parent, value, path, key) { + this._cachedPath = []; + this.parent = parent; + this.data = value; + this._path = path; + this._key = key; + } + get path() { + if (!this._cachedPath.length) { + if (Array.isArray(this._key)) { + this._cachedPath.push(...this._path, ...this._key); + } else { + this._cachedPath.push(...this._path, this._key); + } + } + return this._cachedPath; + } + }; + handleResult = (ctx, result) => { + if (isValid(result)) { + return { success: true, data: result.value }; + } else { + if (!ctx.common.issues.length) { + throw new Error("Validation failed but no issues detected."); + } + return { + success: false, + get error() { + if (this._error) + return this._error; + const error = new ZodError(ctx.common.issues); + this._error = error; + return this._error; + } + }; + } + }; + ZodType = class { + get description() { + return this._def.description; + } + _getType(input) { + return getParsedType(input.data); + } + _getOrReturnCtx(input, ctx) { + return ctx || { + common: input.parent.common, + data: input.data, + parsedType: getParsedType(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent + }; + } + _processInputParams(input) { + return { + status: new ParseStatus(), + ctx: { + common: input.parent.common, + data: input.data, + parsedType: getParsedType(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent + } + }; + } + _parseSync(input) { + const result = this._parse(input); + if (isAsync(result)) { + throw new Error("Synchronous parse encountered promise."); + } + return result; + } + _parseAsync(input) { + const result = this._parse(input); + return Promise.resolve(result); + } + parse(data, params) { + const result = this.safeParse(data, params); + if (result.success) + return result.data; + throw result.error; + } + safeParse(data, params) { + const ctx = { + common: { + issues: [], + async: params?.async ?? false, + contextualErrorMap: params?.errorMap + }, + path: params?.path || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType(data) + }; + const result = this._parseSync({ data, path: ctx.path, parent: ctx }); + return handleResult(ctx, result); + } + "~validate"(data) { + const ctx = { + common: { + issues: [], + async: !!this["~standard"].async + }, + path: [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType(data) + }; + if (!this["~standard"].async) { + try { + const result = this._parseSync({ data, path: [], parent: ctx }); + return isValid(result) ? { + value: result.value + } : { + issues: ctx.common.issues + }; + } catch (err) { + if (err?.message?.toLowerCase()?.includes("encountered")) { + this["~standard"].async = true; + } + ctx.common = { + issues: [], + async: true + }; + } + } + return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? { + value: result.value + } : { + issues: ctx.common.issues + }); + } + async parseAsync(data, params) { + const result = await this.safeParseAsync(data, params); + if (result.success) + return result.data; + throw result.error; + } + async safeParseAsync(data, params) { + const ctx = { + common: { + issues: [], + contextualErrorMap: params?.errorMap, + async: true + }, + path: params?.path || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType(data) + }; + const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); + const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); + return handleResult(ctx, result); + } + refine(check, message) { + const getIssueProperties = (val) => { + if (typeof message === "string" || typeof message === "undefined") { + return { message }; + } else if (typeof message === "function") { + return message(val); + } else { + return message; + } + }; + return this._refinement((val, ctx) => { + const result = check(val); + const setError = () => ctx.addIssue({ + code: ZodIssueCode.custom, + ...getIssueProperties(val) + }); + if (typeof Promise !== "undefined" && result instanceof Promise) { + return result.then((data) => { + if (!data) { + setError(); + return false; + } else { + return true; + } + }); + } + if (!result) { + setError(); + return false; + } else { + return true; + } + }); + } + refinement(check, refinementData) { + return this._refinement((val, ctx) => { + if (!check(val)) { + ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData); + return false; + } else { + return true; + } + }); + } + _refinement(refinement) { + return new ZodEffects({ + schema: this, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect: { type: "refinement", refinement } + }); + } + superRefine(refinement) { + return this._refinement(refinement); + } + constructor(def) { + this.spa = this.safeParseAsync; + this._def = def; + this.parse = this.parse.bind(this); + this.safeParse = this.safeParse.bind(this); + this.parseAsync = this.parseAsync.bind(this); + this.safeParseAsync = this.safeParseAsync.bind(this); + this.spa = this.spa.bind(this); + this.refine = this.refine.bind(this); + this.refinement = this.refinement.bind(this); + this.superRefine = this.superRefine.bind(this); + this.optional = this.optional.bind(this); + this.nullable = this.nullable.bind(this); + this.nullish = this.nullish.bind(this); + this.array = this.array.bind(this); + this.promise = this.promise.bind(this); + this.or = this.or.bind(this); + this.and = this.and.bind(this); + this.transform = this.transform.bind(this); + this.brand = this.brand.bind(this); + this.default = this.default.bind(this); + this.catch = this.catch.bind(this); + this.describe = this.describe.bind(this); + this.pipe = this.pipe.bind(this); + this.readonly = this.readonly.bind(this); + this.isNullable = this.isNullable.bind(this); + this.isOptional = this.isOptional.bind(this); + this["~standard"] = { + version: 1, + vendor: "zod", + validate: (data) => this["~validate"](data) + }; + } + optional() { + return ZodOptional.create(this, this._def); + } + nullable() { + return ZodNullable.create(this, this._def); + } + nullish() { + return this.nullable().optional(); + } + array() { + return ZodArray.create(this); + } + promise() { + return ZodPromise.create(this, this._def); + } + or(option) { + return ZodUnion.create([this, option], this._def); + } + and(incoming) { + return ZodIntersection.create(this, incoming, this._def); + } + transform(transform) { + return new ZodEffects({ + ...processCreateParams(this._def), + schema: this, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect: { type: "transform", transform } + }); + } + default(def) { + const defaultValueFunc = typeof def === "function" ? def : () => def; + return new ZodDefault({ + ...processCreateParams(this._def), + innerType: this, + defaultValue: defaultValueFunc, + typeName: ZodFirstPartyTypeKind.ZodDefault + }); + } + brand() { + return new ZodBranded({ + typeName: ZodFirstPartyTypeKind.ZodBranded, + type: this, + ...processCreateParams(this._def) + }); + } + catch(def) { + const catchValueFunc = typeof def === "function" ? def : () => def; + return new ZodCatch({ + ...processCreateParams(this._def), + innerType: this, + catchValue: catchValueFunc, + typeName: ZodFirstPartyTypeKind.ZodCatch + }); + } + describe(description) { + const This = this.constructor; + return new This({ + ...this._def, + description + }); + } + pipe(target) { + return ZodPipeline.create(this, target); + } + readonly() { + return ZodReadonly.create(this); + } + isOptional() { + return this.safeParse(void 0).success; + } + isNullable() { + return this.safeParse(null).success; + } + }; + cuidRegex = /^c[^\s-]{8,}$/i; + cuid2Regex = /^[0-9a-z]+$/; + ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i; + uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; + nanoidRegex = /^[a-z0-9_-]{21}$/i; + jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; + durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; + emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; + _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; + ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; + ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/; + ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/; + ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; + base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; + base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; + dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`; + dateRegex = new RegExp(`^${dateRegexSource}$`); + ZodString = class _ZodString extends ZodType { + _parse(input) { + if (this._def.coerce) { + input.data = String(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.string) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext(ctx2, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.string, + received: ctx2.parsedType + }); + return INVALID; + } + const status = new ParseStatus(); + let ctx = void 0; + for (const check of this._def.checks) { + if (check.kind === "min") { + if (input.data.length < check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check.value, + type: "string", + inclusive: true, + exact: false, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "max") { + if (input.data.length > check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check.value, + type: "string", + inclusive: true, + exact: false, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "length") { + const tooBig = input.data.length > check.value; + const tooSmall = input.data.length < check.value; + if (tooBig || tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + if (tooBig) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check.value, + type: "string", + inclusive: true, + exact: true, + message: check.message + }); + } else if (tooSmall) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check.value, + type: "string", + inclusive: true, + exact: true, + message: check.message + }); + } + status.dirty(); + } + } else if (check.kind === "email") { + if (!emailRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "email", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "emoji") { + if (!emojiRegex) { + emojiRegex = new RegExp(_emojiRegex, "u"); + } + if (!emojiRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "emoji", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "uuid") { + if (!uuidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "uuid", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "nanoid") { + if (!nanoidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "nanoid", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "cuid") { + if (!cuidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cuid", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "cuid2") { + if (!cuid2Regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cuid2", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "ulid") { + if (!ulidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "ulid", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "url") { + try { + new URL(input.data); + } catch { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "url", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "regex") { + check.regex.lastIndex = 0; + const testResult = check.regex.test(input.data); + if (!testResult) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "regex", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "trim") { + input.data = input.data.trim(); + } else if (check.kind === "includes") { + if (!input.data.includes(check.value, check.position)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { includes: check.value, position: check.position }, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "toLowerCase") { + input.data = input.data.toLowerCase(); + } else if (check.kind === "toUpperCase") { + input.data = input.data.toUpperCase(); + } else if (check.kind === "startsWith") { + if (!input.data.startsWith(check.value)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { startsWith: check.value }, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "endsWith") { + if (!input.data.endsWith(check.value)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { endsWith: check.value }, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "datetime") { + const regex2 = datetimeRegex(check); + if (!regex2.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: "datetime", + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "date") { + const regex2 = dateRegex; + if (!regex2.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: "date", + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "time") { + const regex2 = timeRegex(check); + if (!regex2.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: "time", + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "duration") { + if (!durationRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "duration", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "ip") { + if (!isValidIP(input.data, check.version)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "ip", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "jwt") { + if (!isValidJWT(input.data, check.alg)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "jwt", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "cidr") { + if (!isValidCidr(input.data, check.version)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cidr", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "base64") { + if (!base64Regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "base64", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "base64url") { + if (!base64urlRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "base64url", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else { + util.assertNever(check); + } + } + return { status: status.value, value: input.data }; + } + _regex(regex2, validation, message) { + return this.refinement((data) => regex2.test(data), { + validation, + code: ZodIssueCode.invalid_string, + ...errorUtil.errToObj(message) + }); + } + _addCheck(check) { + return new _ZodString({ + ...this._def, + checks: [...this._def.checks, check] + }); + } + email(message) { + return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) }); + } + url(message) { + return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) }); + } + emoji(message) { + return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) }); + } + uuid(message) { + return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) }); + } + nanoid(message) { + return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) }); + } + cuid(message) { + return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) }); + } + cuid2(message) { + return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) }); + } + ulid(message) { + return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) }); + } + base64(message) { + return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) }); + } + base64url(message) { + return this._addCheck({ + kind: "base64url", + ...errorUtil.errToObj(message) + }); + } + jwt(options) { + return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) }); + } + ip(options) { + return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) }); + } + cidr(options) { + return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) }); + } + datetime(options) { + if (typeof options === "string") { + return this._addCheck({ + kind: "datetime", + precision: null, + offset: false, + local: false, + message: options + }); + } + return this._addCheck({ + kind: "datetime", + precision: typeof options?.precision === "undefined" ? null : options?.precision, + offset: options?.offset ?? false, + local: options?.local ?? false, + ...errorUtil.errToObj(options?.message) + }); + } + date(message) { + return this._addCheck({ kind: "date", message }); + } + time(options) { + if (typeof options === "string") { + return this._addCheck({ + kind: "time", + precision: null, + message: options + }); + } + return this._addCheck({ + kind: "time", + precision: typeof options?.precision === "undefined" ? null : options?.precision, + ...errorUtil.errToObj(options?.message) + }); + } + duration(message) { + return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) }); + } + regex(regex2, message) { + return this._addCheck({ + kind: "regex", + regex: regex2, + ...errorUtil.errToObj(message) + }); + } + includes(value, options) { + return this._addCheck({ + kind: "includes", + value, + position: options?.position, + ...errorUtil.errToObj(options?.message) + }); + } + startsWith(value, message) { + return this._addCheck({ + kind: "startsWith", + value, + ...errorUtil.errToObj(message) + }); + } + endsWith(value, message) { + return this._addCheck({ + kind: "endsWith", + value, + ...errorUtil.errToObj(message) + }); + } + min(minLength, message) { + return this._addCheck({ + kind: "min", + value: minLength, + ...errorUtil.errToObj(message) + }); + } + max(maxLength, message) { + return this._addCheck({ + kind: "max", + value: maxLength, + ...errorUtil.errToObj(message) + }); + } + length(len, message) { + return this._addCheck({ + kind: "length", + value: len, + ...errorUtil.errToObj(message) + }); + } + /** + * Equivalent to `.min(1)` + */ + nonempty(message) { + return this.min(1, errorUtil.errToObj(message)); + } + trim() { + return new _ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "trim" }] + }); + } + toLowerCase() { + return new _ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "toLowerCase" }] + }); + } + toUpperCase() { + return new _ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "toUpperCase" }] + }); + } + get isDatetime() { + return !!this._def.checks.find((ch) => ch.kind === "datetime"); + } + get isDate() { + return !!this._def.checks.find((ch) => ch.kind === "date"); + } + get isTime() { + return !!this._def.checks.find((ch) => ch.kind === "time"); + } + get isDuration() { + return !!this._def.checks.find((ch) => ch.kind === "duration"); + } + get isEmail() { + return !!this._def.checks.find((ch) => ch.kind === "email"); + } + get isURL() { + return !!this._def.checks.find((ch) => ch.kind === "url"); + } + get isEmoji() { + return !!this._def.checks.find((ch) => ch.kind === "emoji"); + } + get isUUID() { + return !!this._def.checks.find((ch) => ch.kind === "uuid"); + } + get isNANOID() { + return !!this._def.checks.find((ch) => ch.kind === "nanoid"); + } + get isCUID() { + return !!this._def.checks.find((ch) => ch.kind === "cuid"); + } + get isCUID2() { + return !!this._def.checks.find((ch) => ch.kind === "cuid2"); + } + get isULID() { + return !!this._def.checks.find((ch) => ch.kind === "ulid"); + } + get isIP() { + return !!this._def.checks.find((ch) => ch.kind === "ip"); + } + get isCIDR() { + return !!this._def.checks.find((ch) => ch.kind === "cidr"); + } + get isBase64() { + return !!this._def.checks.find((ch) => ch.kind === "base64"); + } + get isBase64url() { + return !!this._def.checks.find((ch) => ch.kind === "base64url"); + } + get minLength() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxLength() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } + }; + ZodString.create = (params) => { + return new ZodString({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodString, + coerce: params?.coerce ?? false, + ...processCreateParams(params) + }); + }; + ZodNumber = class _ZodNumber extends ZodType { + constructor() { + super(...arguments); + this.min = this.gte; + this.max = this.lte; + this.step = this.multipleOf; + } + _parse(input) { + if (this._def.coerce) { + input.data = Number(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.number) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext(ctx2, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.number, + received: ctx2.parsedType + }); + return INVALID; + } + let ctx = void 0; + const status = new ParseStatus(); + for (const check of this._def.checks) { + if (check.kind === "int") { + if (!util.isInteger(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: "integer", + received: "float", + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "min") { + const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check.value, + type: "number", + inclusive: check.inclusive, + exact: false, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "max") { + const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check.value, + type: "number", + inclusive: check.inclusive, + exact: false, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "multipleOf") { + if (floatSafeRemainder(input.data, check.value) !== 0) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_multiple_of, + multipleOf: check.value, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "finite") { + if (!Number.isFinite(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_finite, + message: check.message + }); + status.dirty(); + } + } else { + util.assertNever(check); + } + } + return { status: status.value, value: input.data }; + } + gte(value, message) { + return this.setLimit("min", value, true, errorUtil.toString(message)); + } + gt(value, message) { + return this.setLimit("min", value, false, errorUtil.toString(message)); + } + lte(value, message) { + return this.setLimit("max", value, true, errorUtil.toString(message)); + } + lt(value, message) { + return this.setLimit("max", value, false, errorUtil.toString(message)); + } + setLimit(kind, value, inclusive, message) { + return new _ZodNumber({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil.toString(message) + } + ] + }); + } + _addCheck(check) { + return new _ZodNumber({ + ...this._def, + checks: [...this._def.checks, check] + }); + } + int(message) { + return this._addCheck({ + kind: "int", + message: errorUtil.toString(message) + }); + } + positive(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: false, + message: errorUtil.toString(message) + }); + } + negative(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: false, + message: errorUtil.toString(message) + }); + } + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: true, + message: errorUtil.toString(message) + }); + } + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: true, + message: errorUtil.toString(message) + }); + } + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value, + message: errorUtil.toString(message) + }); + } + finite(message) { + return this._addCheck({ + kind: "finite", + message: errorUtil.toString(message) + }); + } + safe(message) { + return this._addCheck({ + kind: "min", + inclusive: true, + value: Number.MIN_SAFE_INTEGER, + message: errorUtil.toString(message) + })._addCheck({ + kind: "max", + inclusive: true, + value: Number.MAX_SAFE_INTEGER, + message: errorUtil.toString(message) + }); + } + get minValue() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxValue() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } + get isInt() { + return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value)); + } + get isFinite() { + let max = null; + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { + return true; + } else if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } else if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return Number.isFinite(min) && Number.isFinite(max); + } + }; + ZodNumber.create = (params) => { + return new ZodNumber({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodNumber, + coerce: params?.coerce || false, + ...processCreateParams(params) + }); + }; + ZodBigInt = class _ZodBigInt extends ZodType { + constructor() { + super(...arguments); + this.min = this.gte; + this.max = this.lte; + } + _parse(input) { + if (this._def.coerce) { + try { + input.data = BigInt(input.data); + } catch { + return this._getInvalidInput(input); + } + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.bigint) { + return this._getInvalidInput(input); + } + let ctx = void 0; + const status = new ParseStatus(); + for (const check of this._def.checks) { + if (check.kind === "min") { + const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + type: "bigint", + minimum: check.value, + inclusive: check.inclusive, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "max") { + const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + type: "bigint", + maximum: check.value, + inclusive: check.inclusive, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "multipleOf") { + if (input.data % check.value !== BigInt(0)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_multiple_of, + multipleOf: check.value, + message: check.message + }); + status.dirty(); + } + } else { + util.assertNever(check); + } + } + return { status: status.value, value: input.data }; + } + _getInvalidInput(input) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.bigint, + received: ctx.parsedType + }); + return INVALID; + } + gte(value, message) { + return this.setLimit("min", value, true, errorUtil.toString(message)); + } + gt(value, message) { + return this.setLimit("min", value, false, errorUtil.toString(message)); + } + lte(value, message) { + return this.setLimit("max", value, true, errorUtil.toString(message)); + } + lt(value, message) { + return this.setLimit("max", value, false, errorUtil.toString(message)); + } + setLimit(kind, value, inclusive, message) { + return new _ZodBigInt({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil.toString(message) + } + ] + }); + } + _addCheck(check) { + return new _ZodBigInt({ + ...this._def, + checks: [...this._def.checks, check] + }); + } + positive(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: false, + message: errorUtil.toString(message) + }); + } + negative(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: false, + message: errorUtil.toString(message) + }); + } + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: true, + message: errorUtil.toString(message) + }); + } + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: true, + message: errorUtil.toString(message) + }); + } + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value, + message: errorUtil.toString(message) + }); + } + get minValue() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxValue() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } + }; + ZodBigInt.create = (params) => { + return new ZodBigInt({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodBigInt, + coerce: params?.coerce ?? false, + ...processCreateParams(params) + }); + }; + ZodBoolean = class extends ZodType { + _parse(input) { + if (this._def.coerce) { + input.data = Boolean(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.boolean) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.boolean, + received: ctx.parsedType + }); + return INVALID; + } + return OK(input.data); + } + }; + ZodBoolean.create = (params) => { + return new ZodBoolean({ + typeName: ZodFirstPartyTypeKind.ZodBoolean, + coerce: params?.coerce || false, + ...processCreateParams(params) + }); + }; + ZodDate = class _ZodDate extends ZodType { + _parse(input) { + if (this._def.coerce) { + input.data = new Date(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.date) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext(ctx2, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.date, + received: ctx2.parsedType + }); + return INVALID; + } + if (Number.isNaN(input.data.getTime())) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext(ctx2, { + code: ZodIssueCode.invalid_date + }); + return INVALID; + } + const status = new ParseStatus(); + let ctx = void 0; + for (const check of this._def.checks) { + if (check.kind === "min") { + if (input.data.getTime() < check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + message: check.message, + inclusive: true, + exact: false, + minimum: check.value, + type: "date" + }); + status.dirty(); + } + } else if (check.kind === "max") { + if (input.data.getTime() > check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + message: check.message, + inclusive: true, + exact: false, + maximum: check.value, + type: "date" + }); + status.dirty(); + } + } else { + util.assertNever(check); + } + } + return { + status: status.value, + value: new Date(input.data.getTime()) + }; + } + _addCheck(check) { + return new _ZodDate({ + ...this._def, + checks: [...this._def.checks, check] + }); + } + min(minDate, message) { + return this._addCheck({ + kind: "min", + value: minDate.getTime(), + message: errorUtil.toString(message) + }); + } + max(maxDate, message) { + return this._addCheck({ + kind: "max", + value: maxDate.getTime(), + message: errorUtil.toString(message) + }); + } + get minDate() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min != null ? new Date(min) : null; + } + get maxDate() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max != null ? new Date(max) : null; + } + }; + ZodDate.create = (params) => { + return new ZodDate({ + checks: [], + coerce: params?.coerce || false, + typeName: ZodFirstPartyTypeKind.ZodDate, + ...processCreateParams(params) + }); + }; + ZodSymbol = class extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.symbol) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.symbol, + received: ctx.parsedType + }); + return INVALID; + } + return OK(input.data); + } + }; + ZodSymbol.create = (params) => { + return new ZodSymbol({ + typeName: ZodFirstPartyTypeKind.ZodSymbol, + ...processCreateParams(params) + }); + }; + ZodUndefined = class extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.undefined, + received: ctx.parsedType + }); + return INVALID; + } + return OK(input.data); + } + }; + ZodUndefined.create = (params) => { + return new ZodUndefined({ + typeName: ZodFirstPartyTypeKind.ZodUndefined, + ...processCreateParams(params) + }); + }; + ZodNull = class extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.null) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.null, + received: ctx.parsedType + }); + return INVALID; + } + return OK(input.data); + } + }; + ZodNull.create = (params) => { + return new ZodNull({ + typeName: ZodFirstPartyTypeKind.ZodNull, + ...processCreateParams(params) + }); + }; + ZodAny = class extends ZodType { + constructor() { + super(...arguments); + this._any = true; + } + _parse(input) { + return OK(input.data); + } + }; + ZodAny.create = (params) => { + return new ZodAny({ + typeName: ZodFirstPartyTypeKind.ZodAny, + ...processCreateParams(params) + }); + }; + ZodUnknown = class extends ZodType { + constructor() { + super(...arguments); + this._unknown = true; + } + _parse(input) { + return OK(input.data); + } + }; + ZodUnknown.create = (params) => { + return new ZodUnknown({ + typeName: ZodFirstPartyTypeKind.ZodUnknown, + ...processCreateParams(params) + }); + }; + ZodNever = class extends ZodType { + _parse(input) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.never, + received: ctx.parsedType + }); + return INVALID; + } + }; + ZodNever.create = (params) => { + return new ZodNever({ + typeName: ZodFirstPartyTypeKind.ZodNever, + ...processCreateParams(params) + }); + }; + ZodVoid = class extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.void, + received: ctx.parsedType + }); + return INVALID; + } + return OK(input.data); + } + }; + ZodVoid.create = (params) => { + return new ZodVoid({ + typeName: ZodFirstPartyTypeKind.ZodVoid, + ...processCreateParams(params) + }); + }; + ZodArray = class _ZodArray extends ZodType { + _parse(input) { + const { ctx, status } = this._processInputParams(input); + const def = this._def; + if (ctx.parsedType !== ZodParsedType.array) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.array, + received: ctx.parsedType + }); + return INVALID; + } + if (def.exactLength !== null) { + const tooBig = ctx.data.length > def.exactLength.value; + const tooSmall = ctx.data.length < def.exactLength.value; + if (tooBig || tooSmall) { + addIssueToContext(ctx, { + code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small, + minimum: tooSmall ? def.exactLength.value : void 0, + maximum: tooBig ? def.exactLength.value : void 0, + type: "array", + inclusive: true, + exact: true, + message: def.exactLength.message + }); + status.dirty(); + } + } + if (def.minLength !== null) { + if (ctx.data.length < def.minLength.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: def.minLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.minLength.message + }); + status.dirty(); + } + } + if (def.maxLength !== null) { + if (ctx.data.length > def.maxLength.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: def.maxLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.maxLength.message + }); + status.dirty(); + } + } + if (ctx.common.async) { + return Promise.all([...ctx.data].map((item, i) => { + return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)); + })).then((result2) => { + return ParseStatus.mergeArray(status, result2); + }); + } + const result = [...ctx.data].map((item, i) => { + return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i)); + }); + return ParseStatus.mergeArray(status, result); + } + get element() { + return this._def.type; + } + min(minLength, message) { + return new _ZodArray({ + ...this._def, + minLength: { value: minLength, message: errorUtil.toString(message) } + }); + } + max(maxLength, message) { + return new _ZodArray({ + ...this._def, + maxLength: { value: maxLength, message: errorUtil.toString(message) } + }); + } + length(len, message) { + return new _ZodArray({ + ...this._def, + exactLength: { value: len, message: errorUtil.toString(message) } + }); + } + nonempty(message) { + return this.min(1, message); + } + }; + ZodArray.create = (schema, params) => { + return new ZodArray({ + type: schema, + minLength: null, + maxLength: null, + exactLength: null, + typeName: ZodFirstPartyTypeKind.ZodArray, + ...processCreateParams(params) + }); + }; + ZodObject = class _ZodObject extends ZodType { + constructor() { + super(...arguments); + this._cached = null; + this.nonstrict = this.passthrough; + this.augment = this.extend; + } + _getCached() { + if (this._cached !== null) + return this._cached; + const shape = this._def.shape(); + const keys = util.objectKeys(shape); + this._cached = { shape, keys }; + return this._cached; + } + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.object) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext(ctx2, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx2.parsedType + }); + return INVALID; + } + const { status, ctx } = this._processInputParams(input); + const { shape, keys: shapeKeys } = this._getCached(); + const extraKeys = []; + if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) { + for (const key in ctx.data) { + if (!shapeKeys.includes(key)) { + extraKeys.push(key); + } + } + } + const pairs = []; + for (const key of shapeKeys) { + const keyValidator = shape[key]; + const value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), + alwaysSet: key in ctx.data + }); + } + if (this._def.catchall instanceof ZodNever) { + const unknownKeys = this._def.unknownKeys; + if (unknownKeys === "passthrough") { + for (const key of extraKeys) { + pairs.push({ + key: { status: "valid", value: key }, + value: { status: "valid", value: ctx.data[key] } + }); + } + } else if (unknownKeys === "strict") { + if (extraKeys.length > 0) { + addIssueToContext(ctx, { + code: ZodIssueCode.unrecognized_keys, + keys: extraKeys + }); + status.dirty(); + } + } else if (unknownKeys === "strip") { + } else { + throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); + } + } else { + const catchall = this._def.catchall; + for (const key of extraKeys) { + const value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: catchall._parse( + new ParseInputLazyPath(ctx, value, ctx.path, key) + //, ctx.child(key), value, getParsedType(value) + ), + alwaysSet: key in ctx.data + }); + } + } + if (ctx.common.async) { + return Promise.resolve().then(async () => { + const syncPairs = []; + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + syncPairs.push({ + key, + value, + alwaysSet: pair.alwaysSet + }); + } + return syncPairs; + }).then((syncPairs) => { + return ParseStatus.mergeObjectSync(status, syncPairs); + }); + } else { + return ParseStatus.mergeObjectSync(status, pairs); + } + } + get shape() { + return this._def.shape(); + } + strict(message) { + errorUtil.errToObj; + return new _ZodObject({ + ...this._def, + unknownKeys: "strict", + ...message !== void 0 ? { + errorMap: (issue2, ctx) => { + const defaultError = this._def.errorMap?.(issue2, ctx).message ?? ctx.defaultError; + if (issue2.code === "unrecognized_keys") + return { + message: errorUtil.errToObj(message).message ?? defaultError + }; + return { + message: defaultError + }; + } + } : {} + }); + } + strip() { + return new _ZodObject({ + ...this._def, + unknownKeys: "strip" + }); + } + passthrough() { + return new _ZodObject({ + ...this._def, + unknownKeys: "passthrough" + }); + } + // const AugmentFactory = + // (def: Def) => + // ( + // augmentation: Augmentation + // ): ZodObject< + // extendShape, Augmentation>, + // Def["unknownKeys"], + // Def["catchall"] + // > => { + // return new ZodObject({ + // ...def, + // shape: () => ({ + // ...def.shape(), + // ...augmentation, + // }), + // }) as any; + // }; + extend(augmentation) { + return new _ZodObject({ + ...this._def, + shape: () => ({ + ...this._def.shape(), + ...augmentation + }) + }); + } + /** + * Prior to zod@1.0.12 there was a bug in the + * inferred type of merged objects. Please + * upgrade if you are experiencing issues. + */ + merge(merging) { + const merged = new _ZodObject({ + unknownKeys: merging._def.unknownKeys, + catchall: merging._def.catchall, + shape: () => ({ + ...this._def.shape(), + ...merging._def.shape() + }), + typeName: ZodFirstPartyTypeKind.ZodObject + }); + return merged; + } + // merge< + // Incoming extends AnyZodObject, + // Augmentation extends Incoming["shape"], + // NewOutput extends { + // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation + // ? Augmentation[k]["_output"] + // : k extends keyof Output + // ? Output[k] + // : never; + // }, + // NewInput extends { + // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation + // ? Augmentation[k]["_input"] + // : k extends keyof Input + // ? Input[k] + // : never; + // } + // >( + // merging: Incoming + // ): ZodObject< + // extendShape>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"], + // NewOutput, + // NewInput + // > { + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } + setKey(key, schema) { + return this.augment({ [key]: schema }); + } + // merge( + // merging: Incoming + // ): //ZodObject = (merging) => { + // ZodObject< + // extendShape>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"] + // > { + // // const mergedShape = objectUtil.mergeShapes( + // // this._def.shape(), + // // merging._def.shape() + // // ); + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } + catchall(index2) { + return new _ZodObject({ + ...this._def, + catchall: index2 + }); + } + pick(mask) { + const shape = {}; + for (const key of util.objectKeys(mask)) { + if (mask[key] && this.shape[key]) { + shape[key] = this.shape[key]; + } + } + return new _ZodObject({ + ...this._def, + shape: () => shape + }); + } + omit(mask) { + const shape = {}; + for (const key of util.objectKeys(this.shape)) { + if (!mask[key]) { + shape[key] = this.shape[key]; + } + } + return new _ZodObject({ + ...this._def, + shape: () => shape + }); + } + /** + * @deprecated + */ + deepPartial() { + return deepPartialify(this); + } + partial(mask) { + const newShape = {}; + for (const key of util.objectKeys(this.shape)) { + const fieldSchema = this.shape[key]; + if (mask && !mask[key]) { + newShape[key] = fieldSchema; + } else { + newShape[key] = fieldSchema.optional(); + } + } + return new _ZodObject({ + ...this._def, + shape: () => newShape + }); + } + required(mask) { + const newShape = {}; + for (const key of util.objectKeys(this.shape)) { + if (mask && !mask[key]) { + newShape[key] = this.shape[key]; + } else { + const fieldSchema = this.shape[key]; + let newField = fieldSchema; + while (newField instanceof ZodOptional) { + newField = newField._def.innerType; + } + newShape[key] = newField; + } + } + return new _ZodObject({ + ...this._def, + shape: () => newShape + }); + } + keyof() { + return createZodEnum(util.objectKeys(this.shape)); + } + }; + ZodObject.create = (shape, params) => { + return new ZodObject({ + shape: () => shape, + unknownKeys: "strip", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params) + }); + }; + ZodObject.strictCreate = (shape, params) => { + return new ZodObject({ + shape: () => shape, + unknownKeys: "strict", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params) + }); + }; + ZodObject.lazycreate = (shape, params) => { + return new ZodObject({ + shape, + unknownKeys: "strip", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params) + }); + }; + ZodUnion = class extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + const options = this._def.options; + function handleResults(results) { + for (const result of results) { + if (result.result.status === "valid") { + return result.result; + } + } + for (const result of results) { + if (result.result.status === "dirty") { + ctx.common.issues.push(...result.ctx.common.issues); + return result.result; + } + } + const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues)); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union, + unionErrors + }); + return INVALID; + } + if (ctx.common.async) { + return Promise.all(options.map(async (option) => { + const childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [] + }, + parent: null + }; + return { + result: await option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: childCtx + }), + ctx: childCtx + }; + })).then(handleResults); + } else { + let dirty = void 0; + const issues = []; + for (const option of options) { + const childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [] + }, + parent: null + }; + const result = option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: childCtx + }); + if (result.status === "valid") { + return result; + } else if (result.status === "dirty" && !dirty) { + dirty = { result, ctx: childCtx }; + } + if (childCtx.common.issues.length) { + issues.push(childCtx.common.issues); + } + } + if (dirty) { + ctx.common.issues.push(...dirty.ctx.common.issues); + return dirty.result; + } + const unionErrors = issues.map((issues2) => new ZodError(issues2)); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union, + unionErrors + }); + return INVALID; + } + } + get options() { + return this._def.options; + } + }; + ZodUnion.create = (types, params) => { + return new ZodUnion({ + options: types, + typeName: ZodFirstPartyTypeKind.ZodUnion, + ...processCreateParams(params) + }); + }; + getDiscriminator = (type) => { + if (type instanceof ZodLazy) { + return getDiscriminator(type.schema); + } else if (type instanceof ZodEffects) { + return getDiscriminator(type.innerType()); + } else if (type instanceof ZodLiteral) { + return [type.value]; + } else if (type instanceof ZodEnum) { + return type.options; + } else if (type instanceof ZodNativeEnum) { + return util.objectValues(type.enum); + } else if (type instanceof ZodDefault) { + return getDiscriminator(type._def.innerType); + } else if (type instanceof ZodUndefined) { + return [void 0]; + } else if (type instanceof ZodNull) { + return [null]; + } else if (type instanceof ZodOptional) { + return [void 0, ...getDiscriminator(type.unwrap())]; + } else if (type instanceof ZodNullable) { + return [null, ...getDiscriminator(type.unwrap())]; + } else if (type instanceof ZodBranded) { + return getDiscriminator(type.unwrap()); + } else if (type instanceof ZodReadonly) { + return getDiscriminator(type.unwrap()); + } else if (type instanceof ZodCatch) { + return getDiscriminator(type._def.innerType); + } else { + return []; + } + }; + ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.object) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType + }); + return INVALID; + } + const discriminator = this.discriminator; + const discriminatorValue = ctx.data[discriminator]; + const option = this.optionsMap.get(discriminatorValue); + if (!option) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union_discriminator, + options: Array.from(this.optionsMap.keys()), + path: [discriminator] + }); + return INVALID; + } + if (ctx.common.async) { + return option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + } else { + return option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + } + } + get discriminator() { + return this._def.discriminator; + } + get options() { + return this._def.options; + } + get optionsMap() { + return this._def.optionsMap; + } + /** + * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. + * However, it only allows a union of objects, all of which need to share a discriminator property. This property must + * have a different value for each object in the union. + * @param discriminator the name of the discriminator property + * @param types an array of object schemas + * @param params + */ + static create(discriminator, options, params) { + const optionsMap = /* @__PURE__ */ new Map(); + for (const type of options) { + const discriminatorValues = getDiscriminator(type.shape[discriminator]); + if (!discriminatorValues.length) { + throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); + } + for (const value of discriminatorValues) { + if (optionsMap.has(value)) { + throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); + } + optionsMap.set(value, type); + } + } + return new _ZodDiscriminatedUnion({ + typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, + discriminator, + options, + optionsMap, + ...processCreateParams(params) + }); + } + }; + ZodIntersection = class extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + const handleParsed = (parsedLeft, parsedRight) => { + if (isAborted(parsedLeft) || isAborted(parsedRight)) { + return INVALID; + } + const merged = mergeValues(parsedLeft.value, parsedRight.value); + if (!merged.valid) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_intersection_types + }); + return INVALID; + } + if (isDirty(parsedLeft) || isDirty(parsedRight)) { + status.dirty(); + } + return { status: status.value, value: merged.data }; + }; + if (ctx.common.async) { + return Promise.all([ + this._def.left._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }), + this._def.right._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }) + ]).then(([left, right]) => handleParsed(left, right)); + } else { + return handleParsed(this._def.left._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }), this._def.right._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + })); + } + } + }; + ZodIntersection.create = (left, right, params) => { + return new ZodIntersection({ + left, + right, + typeName: ZodFirstPartyTypeKind.ZodIntersection, + ...processCreateParams(params) + }); + }; + ZodTuple = class _ZodTuple extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.array) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.array, + received: ctx.parsedType + }); + return INVALID; + } + if (ctx.data.length < this._def.items.length) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: this._def.items.length, + inclusive: true, + exact: false, + type: "array" + }); + return INVALID; + } + const rest = this._def.rest; + if (!rest && ctx.data.length > this._def.items.length) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: this._def.items.length, + inclusive: true, + exact: false, + type: "array" + }); + status.dirty(); + } + const items = [...ctx.data].map((item, itemIndex) => { + const schema = this._def.items[itemIndex] || this._def.rest; + if (!schema) + return null; + return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); + }).filter((x) => !!x); + if (ctx.common.async) { + return Promise.all(items).then((results) => { + return ParseStatus.mergeArray(status, results); + }); + } else { + return ParseStatus.mergeArray(status, items); + } + } + get items() { + return this._def.items; + } + rest(rest) { + return new _ZodTuple({ + ...this._def, + rest + }); + } + }; + ZodTuple.create = (schemas, params) => { + if (!Array.isArray(schemas)) { + throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); + } + return new ZodTuple({ + items: schemas, + typeName: ZodFirstPartyTypeKind.ZodTuple, + rest: null, + ...processCreateParams(params) + }); + }; + ZodRecord = class _ZodRecord extends ZodType { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.object) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType + }); + return INVALID; + } + const pairs = []; + const keyType = this._def.keyType; + const valueType = this._def.valueType; + for (const key in ctx.data) { + pairs.push({ + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), + value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), + alwaysSet: key in ctx.data + }); + } + if (ctx.common.async) { + return ParseStatus.mergeObjectAsync(status, pairs); + } else { + return ParseStatus.mergeObjectSync(status, pairs); + } + } + get element() { + return this._def.valueType; + } + static create(first, second, third) { + if (second instanceof ZodType) { + return new _ZodRecord({ + keyType: first, + valueType: second, + typeName: ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(third) + }); + } + return new _ZodRecord({ + keyType: ZodString.create(), + valueType: first, + typeName: ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(second) + }); + } + }; + ZodMap = class extends ZodType { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.map) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.map, + received: ctx.parsedType + }); + return INVALID; + } + const keyType = this._def.keyType; + const valueType = this._def.valueType; + const pairs = [...ctx.data.entries()].map(([key, value], index2) => { + return { + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index2, "key"])), + value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index2, "value"])) + }; + }); + if (ctx.common.async) { + const finalMap = /* @__PURE__ */ new Map(); + return Promise.resolve().then(async () => { + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + if (key.status === "aborted" || value.status === "aborted") { + return INVALID; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; + }); + } else { + const finalMap = /* @__PURE__ */ new Map(); + for (const pair of pairs) { + const key = pair.key; + const value = pair.value; + if (key.status === "aborted" || value.status === "aborted") { + return INVALID; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; + } + } + }; + ZodMap.create = (keyType, valueType, params) => { + return new ZodMap({ + valueType, + keyType, + typeName: ZodFirstPartyTypeKind.ZodMap, + ...processCreateParams(params) + }); + }; + ZodSet = class _ZodSet extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.set) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.set, + received: ctx.parsedType + }); + return INVALID; + } + const def = this._def; + if (def.minSize !== null) { + if (ctx.data.size < def.minSize.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: def.minSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.minSize.message + }); + status.dirty(); + } + } + if (def.maxSize !== null) { + if (ctx.data.size > def.maxSize.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: def.maxSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.maxSize.message + }); + status.dirty(); + } + } + const valueType = this._def.valueType; + function finalizeSet(elements2) { + const parsedSet = /* @__PURE__ */ new Set(); + for (const element of elements2) { + if (element.status === "aborted") + return INVALID; + if (element.status === "dirty") + status.dirty(); + parsedSet.add(element.value); + } + return { status: status.value, value: parsedSet }; + } + const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))); + if (ctx.common.async) { + return Promise.all(elements).then((elements2) => finalizeSet(elements2)); + } else { + return finalizeSet(elements); + } + } + min(minSize, message) { + return new _ZodSet({ + ...this._def, + minSize: { value: minSize, message: errorUtil.toString(message) } + }); + } + max(maxSize, message) { + return new _ZodSet({ + ...this._def, + maxSize: { value: maxSize, message: errorUtil.toString(message) } + }); + } + size(size, message) { + return this.min(size, message).max(size, message); + } + nonempty(message) { + return this.min(1, message); + } + }; + ZodSet.create = (valueType, params) => { + return new ZodSet({ + valueType, + minSize: null, + maxSize: null, + typeName: ZodFirstPartyTypeKind.ZodSet, + ...processCreateParams(params) + }); + }; + ZodFunction = class _ZodFunction extends ZodType { + constructor() { + super(...arguments); + this.validate = this.implement; + } + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.function) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.function, + received: ctx.parsedType + }); + return INVALID; + } + function makeArgsIssue(args, error) { + return makeIssue({ + data: args, + path: ctx.path, + errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x), + issueData: { + code: ZodIssueCode.invalid_arguments, + argumentsError: error + } + }); + } + function makeReturnsIssue(returns, error) { + return makeIssue({ + data: returns, + path: ctx.path, + errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x), + issueData: { + code: ZodIssueCode.invalid_return_type, + returnTypeError: error + } + }); + } + const params = { errorMap: ctx.common.contextualErrorMap }; + const fn = ctx.data; + if (this._def.returns instanceof ZodPromise) { + const me = this; + return OK(async function(...args) { + const error = new ZodError([]); + const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => { + error.addIssue(makeArgsIssue(args, e)); + throw error; + }); + const result = await Reflect.apply(fn, this, parsedArgs); + const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => { + error.addIssue(makeReturnsIssue(result, e)); + throw error; + }); + return parsedReturns; + }); + } else { + const me = this; + return OK(function(...args) { + const parsedArgs = me._def.args.safeParse(args, params); + if (!parsedArgs.success) { + throw new ZodError([makeArgsIssue(args, parsedArgs.error)]); + } + const result = Reflect.apply(fn, this, parsedArgs.data); + const parsedReturns = me._def.returns.safeParse(result, params); + if (!parsedReturns.success) { + throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]); + } + return parsedReturns.data; + }); + } + } + parameters() { + return this._def.args; + } + returnType() { + return this._def.returns; + } + args(...items) { + return new _ZodFunction({ + ...this._def, + args: ZodTuple.create(items).rest(ZodUnknown.create()) + }); + } + returns(returnType) { + return new _ZodFunction({ + ...this._def, + returns: returnType + }); + } + implement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; + } + strictImplement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; + } + static create(args, returns, params) { + return new _ZodFunction({ + args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()), + returns: returns || ZodUnknown.create(), + typeName: ZodFirstPartyTypeKind.ZodFunction, + ...processCreateParams(params) + }); + } + }; + ZodLazy = class extends ZodType { + get schema() { + return this._def.getter(); + } + _parse(input) { + const { ctx } = this._processInputParams(input); + const lazySchema = this._def.getter(); + return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); + } + }; + ZodLazy.create = (getter, params) => { + return new ZodLazy({ + getter, + typeName: ZodFirstPartyTypeKind.ZodLazy, + ...processCreateParams(params) + }); + }; + ZodLiteral = class extends ZodType { + _parse(input) { + if (input.data !== this._def.value) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_literal, + expected: this._def.value + }); + return INVALID; + } + return { status: "valid", value: input.data }; + } + get value() { + return this._def.value; + } + }; + ZodLiteral.create = (value, params) => { + return new ZodLiteral({ + value, + typeName: ZodFirstPartyTypeKind.ZodLiteral, + ...processCreateParams(params) + }); + }; + ZodEnum = class _ZodEnum extends ZodType { + _parse(input) { + if (typeof input.data !== "string") { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + addIssueToContext(ctx, { + expected: util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodIssueCode.invalid_type + }); + return INVALID; + } + if (!this._cache) { + this._cache = new Set(this._def.values); + } + if (!this._cache.has(input.data)) { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_enum_value, + options: expectedValues + }); + return INVALID; + } + return OK(input.data); + } + get options() { + return this._def.values; + } + get enum() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; + } + get Values() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; + } + get Enum() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; + } + extract(values, newDef = this._def) { + return _ZodEnum.create(values, { + ...this._def, + ...newDef + }); + } + exclude(values, newDef = this._def) { + return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), { + ...this._def, + ...newDef + }); + } + }; + ZodEnum.create = createZodEnum; + ZodNativeEnum = class extends ZodType { + _parse(input) { + const nativeEnumValues = util.getValidEnumValues(this._def.values); + const ctx = this._getOrReturnCtx(input); + if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) { + const expectedValues = util.objectValues(nativeEnumValues); + addIssueToContext(ctx, { + expected: util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodIssueCode.invalid_type + }); + return INVALID; + } + if (!this._cache) { + this._cache = new Set(util.getValidEnumValues(this._def.values)); + } + if (!this._cache.has(input.data)) { + const expectedValues = util.objectValues(nativeEnumValues); + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_enum_value, + options: expectedValues + }); + return INVALID; + } + return OK(input.data); + } + get enum() { + return this._def.values; + } + }; + ZodNativeEnum.create = (values, params) => { + return new ZodNativeEnum({ + values, + typeName: ZodFirstPartyTypeKind.ZodNativeEnum, + ...processCreateParams(params) + }); + }; + ZodPromise = class extends ZodType { + unwrap() { + return this._def.type; + } + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.promise, + received: ctx.parsedType + }); + return INVALID; + } + const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data); + return OK(promisified.then((data) => { + return this._def.type.parseAsync(data, { + path: ctx.path, + errorMap: ctx.common.contextualErrorMap + }); + })); + } + }; + ZodPromise.create = (schema, params) => { + return new ZodPromise({ + type: schema, + typeName: ZodFirstPartyTypeKind.ZodPromise, + ...processCreateParams(params) + }); + }; + ZodEffects = class extends ZodType { + innerType() { + return this._def.schema; + } + sourceType() { + return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + const effect = this._def.effect || null; + const checkCtx = { + addIssue: (arg) => { + addIssueToContext(ctx, arg); + if (arg.fatal) { + status.abort(); + } else { + status.dirty(); + } + }, + get path() { + return ctx.path; + } + }; + checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); + if (effect.type === "preprocess") { + const processed = effect.transform(ctx.data, checkCtx); + if (ctx.common.async) { + return Promise.resolve(processed).then(async (processed2) => { + if (status.value === "aborted") + return INVALID; + const result = await this._def.schema._parseAsync({ + data: processed2, + path: ctx.path, + parent: ctx + }); + if (result.status === "aborted") + return INVALID; + if (result.status === "dirty") + return DIRTY(result.value); + if (status.value === "dirty") + return DIRTY(result.value); + return result; + }); + } else { + if (status.value === "aborted") + return INVALID; + const result = this._def.schema._parseSync({ + data: processed, + path: ctx.path, + parent: ctx + }); + if (result.status === "aborted") + return INVALID; + if (result.status === "dirty") + return DIRTY(result.value); + if (status.value === "dirty") + return DIRTY(result.value); + return result; + } + } + if (effect.type === "refinement") { + const executeRefinement = (acc) => { + const result = effect.refinement(acc, checkCtx); + if (ctx.common.async) { + return Promise.resolve(result); + } + if (result instanceof Promise) { + throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); + } + return acc; + }; + if (ctx.common.async === false) { + const inner = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (inner.status === "aborted") + return INVALID; + if (inner.status === "dirty") + status.dirty(); + executeRefinement(inner.value); + return { status: status.value, value: inner.value }; + } else { + return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => { + if (inner.status === "aborted") + return INVALID; + if (inner.status === "dirty") + status.dirty(); + return executeRefinement(inner.value).then(() => { + return { status: status.value, value: inner.value }; + }); + }); + } + } + if (effect.type === "transform") { + if (ctx.common.async === false) { + const base = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (!isValid(base)) + return INVALID; + const result = effect.transform(base.value, checkCtx); + if (result instanceof Promise) { + throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); + } + return { status: status.value, value: result }; + } else { + return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => { + if (!isValid(base)) + return INVALID; + return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ + status: status.value, + value: result + })); + }); + } + } + util.assertNever(effect); + } + }; + ZodEffects.create = (schema, effect, params) => { + return new ZodEffects({ + schema, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect, + ...processCreateParams(params) + }); + }; + ZodEffects.createWithPreprocess = (preprocess, schema, params) => { + return new ZodEffects({ + schema, + effect: { type: "preprocess", transform: preprocess }, + typeName: ZodFirstPartyTypeKind.ZodEffects, + ...processCreateParams(params) + }); + }; + ZodOptional = class extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType === ZodParsedType.undefined) { + return OK(void 0); + } + return this._def.innerType._parse(input); + } + unwrap() { + return this._def.innerType; + } + }; + ZodOptional.create = (type, params) => { + return new ZodOptional({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodOptional, + ...processCreateParams(params) + }); + }; + ZodNullable = class extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType === ZodParsedType.null) { + return OK(null); + } + return this._def.innerType._parse(input); + } + unwrap() { + return this._def.innerType; + } + }; + ZodNullable.create = (type, params) => { + return new ZodNullable({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodNullable, + ...processCreateParams(params) + }); + }; + ZodDefault = class extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + let data = ctx.data; + if (ctx.parsedType === ZodParsedType.undefined) { + data = this._def.defaultValue(); + } + return this._def.innerType._parse({ + data, + path: ctx.path, + parent: ctx + }); + } + removeDefault() { + return this._def.innerType; + } + }; + ZodDefault.create = (type, params) => { + return new ZodDefault({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodDefault, + defaultValue: typeof params.default === "function" ? params.default : () => params.default, + ...processCreateParams(params) + }); + }; + ZodCatch = class extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + const newCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [] + } + }; + const result = this._def.innerType._parse({ + data: newCtx.data, + path: newCtx.path, + parent: { + ...newCtx + } + }); + if (isAsync(result)) { + return result.then((result2) => { + return { + status: "valid", + value: result2.status === "valid" ? result2.value : this._def.catchValue({ + get error() { + return new ZodError(newCtx.common.issues); + }, + input: newCtx.data + }) + }; + }); + } else { + return { + status: "valid", + value: result.status === "valid" ? result.value : this._def.catchValue({ + get error() { + return new ZodError(newCtx.common.issues); + }, + input: newCtx.data + }) + }; + } + } + removeCatch() { + return this._def.innerType; + } + }; + ZodCatch.create = (type, params) => { + return new ZodCatch({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodCatch, + catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, + ...processCreateParams(params) + }); + }; + ZodNaN = class extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.nan) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.nan, + received: ctx.parsedType + }); + return INVALID; + } + return { status: "valid", value: input.data }; + } + }; + ZodNaN.create = (params) => { + return new ZodNaN({ + typeName: ZodFirstPartyTypeKind.ZodNaN, + ...processCreateParams(params) + }); + }; + BRAND = Symbol("zod_brand"); + ZodBranded = class extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + const data = ctx.data; + return this._def.type._parse({ + data, + path: ctx.path, + parent: ctx + }); + } + unwrap() { + return this._def.type; + } + }; + ZodPipeline = class _ZodPipeline extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.common.async) { + const handleAsync = async () => { + const inResult = await this._def.in._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (inResult.status === "aborted") + return INVALID; + if (inResult.status === "dirty") { + status.dirty(); + return DIRTY(inResult.value); + } else { + return this._def.out._parseAsync({ + data: inResult.value, + path: ctx.path, + parent: ctx + }); + } + }; + return handleAsync(); + } else { + const inResult = this._def.in._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (inResult.status === "aborted") + return INVALID; + if (inResult.status === "dirty") { + status.dirty(); + return { + status: "dirty", + value: inResult.value + }; + } else { + return this._def.out._parseSync({ + data: inResult.value, + path: ctx.path, + parent: ctx + }); + } + } + } + static create(a, b) { + return new _ZodPipeline({ + in: a, + out: b, + typeName: ZodFirstPartyTypeKind.ZodPipeline + }); + } + }; + ZodReadonly = class extends ZodType { + _parse(input) { + const result = this._def.innerType._parse(input); + const freeze = (data) => { + if (isValid(data)) { + data.value = Object.freeze(data.value); + } + return data; + }; + return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result); + } + unwrap() { + return this._def.innerType; + } + }; + ZodReadonly.create = (type, params) => { + return new ZodReadonly({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodReadonly, + ...processCreateParams(params) + }); + }; + late = { + object: ZodObject.lazycreate + }; + (function(ZodFirstPartyTypeKind2) { + ZodFirstPartyTypeKind2["ZodString"] = "ZodString"; + ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber"; + ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN"; + ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt"; + ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean"; + ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate"; + ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol"; + ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined"; + ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull"; + ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny"; + ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown"; + ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever"; + ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid"; + ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray"; + ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject"; + ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion"; + ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; + ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection"; + ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple"; + ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord"; + ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap"; + ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet"; + ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction"; + ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy"; + ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral"; + ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum"; + ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects"; + ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum"; + ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional"; + ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable"; + ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault"; + ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch"; + ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise"; + ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded"; + ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline"; + ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly"; + })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); + instanceOfType = (cls, params = { + message: `Input not instance of ${cls.name}` + }) => custom((data) => data instanceof cls, params); + stringType = ZodString.create; + numberType = ZodNumber.create; + nanType = ZodNaN.create; + bigIntType = ZodBigInt.create; + booleanType = ZodBoolean.create; + dateType = ZodDate.create; + symbolType = ZodSymbol.create; + undefinedType = ZodUndefined.create; + nullType = ZodNull.create; + anyType = ZodAny.create; + unknownType = ZodUnknown.create; + neverType = ZodNever.create; + voidType = ZodVoid.create; + arrayType = ZodArray.create; + objectType = ZodObject.create; + strictObjectType = ZodObject.strictCreate; + unionType = ZodUnion.create; + discriminatedUnionType = ZodDiscriminatedUnion.create; + intersectionType = ZodIntersection.create; + tupleType = ZodTuple.create; + recordType = ZodRecord.create; + mapType = ZodMap.create; + setType = ZodSet.create; + functionType = ZodFunction.create; + lazyType = ZodLazy.create; + literalType = ZodLiteral.create; + enumType = ZodEnum.create; + nativeEnumType = ZodNativeEnum.create; + promiseType = ZodPromise.create; + effectsType = ZodEffects.create; + optionalType = ZodOptional.create; + nullableType = ZodNullable.create; + preprocessType = ZodEffects.createWithPreprocess; + pipelineType = ZodPipeline.create; + ostring = () => stringType().optional(); + onumber = () => numberType().optional(); + oboolean = () => booleanType().optional(); + coerce = { + string: ((arg) => ZodString.create({ ...arg, coerce: true })), + number: ((arg) => ZodNumber.create({ ...arg, coerce: true })), + boolean: ((arg) => ZodBoolean.create({ + ...arg, + coerce: true + })), + bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })), + date: ((arg) => ZodDate.create({ ...arg, coerce: true })) + }; + NEVER = INVALID; + } +}); + +// node_modules/zod/v3/external.js +var external_exports = {}; +__export(external_exports, { + BRAND: () => BRAND, + DIRTY: () => DIRTY, + EMPTY_PATH: () => EMPTY_PATH, + INVALID: () => INVALID, + NEVER: () => NEVER, + OK: () => OK, + ParseStatus: () => ParseStatus, + Schema: () => ZodType, + ZodAny: () => ZodAny, + ZodArray: () => ZodArray, + ZodBigInt: () => ZodBigInt, + ZodBoolean: () => ZodBoolean, + ZodBranded: () => ZodBranded, + ZodCatch: () => ZodCatch, + ZodDate: () => ZodDate, + ZodDefault: () => ZodDefault, + ZodDiscriminatedUnion: () => ZodDiscriminatedUnion, + ZodEffects: () => ZodEffects, + ZodEnum: () => ZodEnum, + ZodError: () => ZodError, + ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind, + ZodFunction: () => ZodFunction, + ZodIntersection: () => ZodIntersection, + ZodIssueCode: () => ZodIssueCode, + ZodLazy: () => ZodLazy, + ZodLiteral: () => ZodLiteral, + ZodMap: () => ZodMap, + ZodNaN: () => ZodNaN, + ZodNativeEnum: () => ZodNativeEnum, + ZodNever: () => ZodNever, + ZodNull: () => ZodNull, + ZodNullable: () => ZodNullable, + ZodNumber: () => ZodNumber, + ZodObject: () => ZodObject, + ZodOptional: () => ZodOptional, + ZodParsedType: () => ZodParsedType, + ZodPipeline: () => ZodPipeline, + ZodPromise: () => ZodPromise, + ZodReadonly: () => ZodReadonly, + ZodRecord: () => ZodRecord, + ZodSchema: () => ZodType, + ZodSet: () => ZodSet, + ZodString: () => ZodString, + ZodSymbol: () => ZodSymbol, + ZodTransformer: () => ZodEffects, + ZodTuple: () => ZodTuple, + ZodType: () => ZodType, + ZodUndefined: () => ZodUndefined, + ZodUnion: () => ZodUnion, + ZodUnknown: () => ZodUnknown, + ZodVoid: () => ZodVoid, + addIssueToContext: () => addIssueToContext, + any: () => anyType, + array: () => arrayType, + bigint: () => bigIntType, + boolean: () => booleanType, + coerce: () => coerce, + custom: () => custom, + date: () => dateType, + datetimeRegex: () => datetimeRegex, + defaultErrorMap: () => en_default, + discriminatedUnion: () => discriminatedUnionType, + effect: () => effectsType, + enum: () => enumType, + function: () => functionType, + getErrorMap: () => getErrorMap, + getParsedType: () => getParsedType, + instanceof: () => instanceOfType, + intersection: () => intersectionType, + isAborted: () => isAborted, + isAsync: () => isAsync, + isDirty: () => isDirty, + isValid: () => isValid, + late: () => late, + lazy: () => lazyType, + literal: () => literalType, + makeIssue: () => makeIssue, + map: () => mapType, + nan: () => nanType, + nativeEnum: () => nativeEnumType, + never: () => neverType, + null: () => nullType, + nullable: () => nullableType, + number: () => numberType, + object: () => objectType, + objectUtil: () => objectUtil, + oboolean: () => oboolean, + onumber: () => onumber, + optional: () => optionalType, + ostring: () => ostring, + pipeline: () => pipelineType, + preprocess: () => preprocessType, + promise: () => promiseType, + quotelessJson: () => quotelessJson, + record: () => recordType, + set: () => setType, + setErrorMap: () => setErrorMap, + strictObject: () => strictObjectType, + string: () => stringType, + symbol: () => symbolType, + transformer: () => effectsType, + tuple: () => tupleType, + undefined: () => undefinedType, + union: () => unionType, + unknown: () => unknownType, + util: () => util, + void: () => voidType +}); +var init_external = __esm({ + "node_modules/zod/v3/external.js"() { + init_errors2(); + init_parseUtil(); + init_typeAliases(); + init_util(); + init_types(); + init_ZodError(); + } +}); + +// node_modules/zod/v3/index.js +var init_v3 = __esm({ + "node_modules/zod/v3/index.js"() { + init_external(); + init_external(); + } +}); + +// node_modules/@langchain/core/dist/utils/fast-json-patch/src/helpers.js +function hasOwnProperty(obj, key) { + return _hasOwnProperty.call(obj, key); +} +function _objectKeys(obj) { + if (Array.isArray(obj)) { + const keys2 = new Array(obj.length); + for (let k = 0; k < keys2.length; k++) { + keys2[k] = "" + k; + } + return keys2; + } + if (Object.keys) { + return Object.keys(obj); + } + let keys = []; + for (let i in obj) { + if (hasOwnProperty(obj, i)) { + keys.push(i); + } + } + return keys; +} +function _deepClone(obj) { + switch (typeof obj) { + case "object": + return JSON.parse(JSON.stringify(obj)); + //Faster than ES5 clone - http://jsperf.com/deep-cloning-of-objects/5 + case "undefined": + return null; + //this is how JSON.stringify behaves for array items + default: + return obj; + } +} +function isInteger(str) { + let i = 0; + const len = str.length; + let charCode; + while (i < len) { + charCode = str.charCodeAt(i); + if (charCode >= 48 && charCode <= 57) { + i++; + continue; + } + return false; + } + return true; +} +function escapePathComponent(path) { + if (path.indexOf("/") === -1 && path.indexOf("~") === -1) + return path; + return path.replace(/~/g, "~0").replace(/\//g, "~1"); +} +function unescapePathComponent(path) { + return path.replace(/~1/g, "/").replace(/~0/g, "~"); +} +function hasUndefined(obj) { + if (obj === void 0) { + return true; + } + if (obj) { + if (Array.isArray(obj)) { + for (let i2 = 0, len = obj.length; i2 < len; i2++) { + if (hasUndefined(obj[i2])) { + return true; + } + } + } else if (typeof obj === "object") { + const objKeys = _objectKeys(obj); + const objKeysLength = objKeys.length; + for (var i = 0; i < objKeysLength; i++) { + if (hasUndefined(obj[objKeys[i]])) { + return true; + } + } + } + } + return false; +} +function patchErrorMessageFormatter(message, args) { + const messageParts = [message]; + for (const key in args) { + const value = typeof args[key] === "object" ? JSON.stringify(args[key], null, 2) : args[key]; + if (typeof value !== "undefined") { + messageParts.push(`${key}: ${value}`); + } + } + return messageParts.join("\n"); +} +var _hasOwnProperty, PatchError; +var init_helpers = __esm({ + "node_modules/@langchain/core/dist/utils/fast-json-patch/src/helpers.js"() { + _hasOwnProperty = Object.prototype.hasOwnProperty; + PatchError = class extends Error { + constructor(message, name, index2, operation, tree) { + super(patchErrorMessageFormatter(message, { name, index: index2, operation, tree })); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: name + }); + Object.defineProperty(this, "index", { + enumerable: true, + configurable: true, + writable: true, + value: index2 + }); + Object.defineProperty(this, "operation", { + enumerable: true, + configurable: true, + writable: true, + value: operation + }); + Object.defineProperty(this, "tree", { + enumerable: true, + configurable: true, + writable: true, + value: tree + }); + Object.setPrototypeOf(this, new.target.prototype); + this.message = patchErrorMessageFormatter(message, { + name, + index: index2, + operation, + tree + }); + } + }; + } +}); + +// node_modules/@langchain/core/dist/utils/fast-json-patch/src/core.js +var core_exports = {}; +__export(core_exports, { + JsonPatchError: () => JsonPatchError, + _areEquals: () => _areEquals, + applyOperation: () => applyOperation, + applyPatch: () => applyPatch, + applyReducer: () => applyReducer, + deepClone: () => deepClone, + getValueByPointer: () => getValueByPointer, + validate: () => validate2, + validator: () => validator +}); +function getValueByPointer(document2, pointer) { + if (pointer == "") { + return document2; + } + var getOriginalDestination = { op: "_get", path: pointer }; + applyOperation(document2, getOriginalDestination); + return getOriginalDestination.value; +} +function applyOperation(document2, operation, validateOperation = false, mutateDocument = true, banPrototypeModifications = true, index2 = 0) { + if (validateOperation) { + if (typeof validateOperation == "function") { + validateOperation(operation, 0, document2, operation.path); + } else { + validator(operation, 0); + } + } + if (operation.path === "") { + let returnValue = { newDocument: document2 }; + if (operation.op === "add") { + returnValue.newDocument = operation.value; + return returnValue; + } else if (operation.op === "replace") { + returnValue.newDocument = operation.value; + returnValue.removed = document2; + return returnValue; + } else if (operation.op === "move" || operation.op === "copy") { + returnValue.newDocument = getValueByPointer(document2, operation.from); + if (operation.op === "move") { + returnValue.removed = document2; + } + return returnValue; + } else if (operation.op === "test") { + returnValue.test = _areEquals(document2, operation.value); + if (returnValue.test === false) { + throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index2, operation, document2); + } + returnValue.newDocument = document2; + return returnValue; + } else if (operation.op === "remove") { + returnValue.removed = document2; + returnValue.newDocument = null; + return returnValue; + } else if (operation.op === "_get") { + operation.value = document2; + return returnValue; + } else { + if (validateOperation) { + throw new JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902", "OPERATION_OP_INVALID", index2, operation, document2); + } else { + return returnValue; + } + } + } else { + if (!mutateDocument) { + document2 = _deepClone(document2); + } + const path = operation.path || ""; + const keys = path.split("/"); + let obj = document2; + let t = 1; + let len = keys.length; + let existingPathFragment = void 0; + let key; + let validateFunction; + if (typeof validateOperation == "function") { + validateFunction = validateOperation; + } else { + validateFunction = validator; + } + while (true) { + key = keys[t]; + if (key && key.indexOf("~") != -1) { + key = unescapePathComponent(key); + } + if (banPrototypeModifications && (key == "__proto__" || key == "prototype" && t > 0 && keys[t - 1] == "constructor")) { + throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README"); + } + if (validateOperation) { + if (existingPathFragment === void 0) { + if (obj[key] === void 0) { + existingPathFragment = keys.slice(0, t).join("/"); + } else if (t == len - 1) { + existingPathFragment = operation.path; + } + if (existingPathFragment !== void 0) { + validateFunction(operation, 0, document2, existingPathFragment); + } + } + } + t++; + if (Array.isArray(obj)) { + if (key === "-") { + key = obj.length; + } else { + if (validateOperation && !isInteger(key)) { + throw new JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index", "OPERATION_PATH_ILLEGAL_ARRAY_INDEX", index2, operation, document2); + } else if (isInteger(key)) { + key = ~~key; + } + } + if (t >= len) { + if (validateOperation && operation.op === "add" && key > obj.length) { + throw new JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array", "OPERATION_VALUE_OUT_OF_BOUNDS", index2, operation, document2); + } + const returnValue = arrOps[operation.op].call(operation, obj, key, document2); + if (returnValue.test === false) { + throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index2, operation, document2); + } + return returnValue; + } + } else { + if (t >= len) { + const returnValue = objOps[operation.op].call(operation, obj, key, document2); + if (returnValue.test === false) { + throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index2, operation, document2); + } + return returnValue; + } + } + obj = obj[key]; + if (validateOperation && t < len && (!obj || typeof obj !== "object")) { + throw new JsonPatchError("Cannot perform operation at the desired path", "OPERATION_PATH_UNRESOLVABLE", index2, operation, document2); + } + } + } +} +function applyPatch(document2, patch, validateOperation, mutateDocument = true, banPrototypeModifications = true) { + if (validateOperation) { + if (!Array.isArray(patch)) { + throw new JsonPatchError("Patch sequence must be an array", "SEQUENCE_NOT_AN_ARRAY"); + } + } + if (!mutateDocument) { + document2 = _deepClone(document2); + } + const results = new Array(patch.length); + for (let i = 0, length = patch.length; i < length; i++) { + results[i] = applyOperation(document2, patch[i], validateOperation, true, banPrototypeModifications, i); + document2 = results[i].newDocument; + } + results.newDocument = document2; + return results; +} +function applyReducer(document2, operation, index2) { + const operationResult = applyOperation(document2, operation); + if (operationResult.test === false) { + throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index2, operation, document2); + } + return operationResult.newDocument; +} +function validator(operation, index2, document2, existingPathFragment) { + if (typeof operation !== "object" || operation === null || Array.isArray(operation)) { + throw new JsonPatchError("Operation is not an object", "OPERATION_NOT_AN_OBJECT", index2, operation, document2); + } else if (!objOps[operation.op]) { + throw new JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902", "OPERATION_OP_INVALID", index2, operation, document2); + } else if (typeof operation.path !== "string") { + throw new JsonPatchError("Operation `path` property is not a string", "OPERATION_PATH_INVALID", index2, operation, document2); + } else if (operation.path.indexOf("/") !== 0 && operation.path.length > 0) { + throw new JsonPatchError('Operation `path` property must start with "/"', "OPERATION_PATH_INVALID", index2, operation, document2); + } else if ((operation.op === "move" || operation.op === "copy") && typeof operation.from !== "string") { + throw new JsonPatchError("Operation `from` property is not present (applicable in `move` and `copy` operations)", "OPERATION_FROM_REQUIRED", index2, operation, document2); + } else if ((operation.op === "add" || operation.op === "replace" || operation.op === "test") && operation.value === void 0) { + throw new JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)", "OPERATION_VALUE_REQUIRED", index2, operation, document2); + } else if ((operation.op === "add" || operation.op === "replace" || operation.op === "test") && hasUndefined(operation.value)) { + throw new JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)", "OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED", index2, operation, document2); + } else if (document2) { + if (operation.op == "add") { + var pathLen = operation.path.split("/").length; + var existingPathLen = existingPathFragment.split("/").length; + if (pathLen !== existingPathLen + 1 && pathLen !== existingPathLen) { + throw new JsonPatchError("Cannot perform an `add` operation at the desired path", "OPERATION_PATH_CANNOT_ADD", index2, operation, document2); + } + } else if (operation.op === "replace" || operation.op === "remove" || operation.op === "_get") { + if (operation.path !== existingPathFragment) { + throw new JsonPatchError("Cannot perform the operation at a path that does not exist", "OPERATION_PATH_UNRESOLVABLE", index2, operation, document2); + } + } else if (operation.op === "move" || operation.op === "copy") { + var existingValue = { + op: "_get", + path: operation.from, + value: void 0 + }; + var error = validate2([existingValue], document2); + if (error && error.name === "OPERATION_PATH_UNRESOLVABLE") { + throw new JsonPatchError("Cannot perform the operation from a path that does not exist", "OPERATION_FROM_UNRESOLVABLE", index2, operation, document2); + } + } + } +} +function validate2(sequence, document2, externalValidator) { + try { + if (!Array.isArray(sequence)) { + throw new JsonPatchError("Patch sequence must be an array", "SEQUENCE_NOT_AN_ARRAY"); + } + if (document2) { + applyPatch(_deepClone(document2), _deepClone(sequence), externalValidator || true); + } else { + externalValidator = externalValidator || validator; + for (var i = 0; i < sequence.length; i++) { + externalValidator(sequence[i], i, document2, void 0); + } + } + } catch (e) { + if (e instanceof JsonPatchError) { + return e; + } else { + throw e; + } + } +} +function _areEquals(a, b) { + if (a === b) + return true; + if (a && b && typeof a == "object" && typeof b == "object") { + var arrA = Array.isArray(a), arrB = Array.isArray(b), i, length, key; + if (arrA && arrB) { + length = a.length; + if (length != b.length) + return false; + for (i = length; i-- !== 0; ) + if (!_areEquals(a[i], b[i])) + return false; + return true; + } + if (arrA != arrB) + return false; + var keys = Object.keys(a); + length = keys.length; + if (length !== Object.keys(b).length) + return false; + for (i = length; i-- !== 0; ) + if (!b.hasOwnProperty(keys[i])) + return false; + for (i = length; i-- !== 0; ) { + key = keys[i]; + if (!_areEquals(a[key], b[key])) + return false; + } + return true; + } + return a !== a && b !== b; +} +var JsonPatchError, deepClone, objOps, arrOps; +var init_core = __esm({ + "node_modules/@langchain/core/dist/utils/fast-json-patch/src/core.js"() { + init_helpers(); + JsonPatchError = PatchError; + deepClone = _deepClone; + objOps = { + add: function(obj, key, document2) { + obj[key] = this.value; + return { newDocument: document2 }; + }, + remove: function(obj, key, document2) { + var removed = obj[key]; + delete obj[key]; + return { newDocument: document2, removed }; + }, + replace: function(obj, key, document2) { + var removed = obj[key]; + obj[key] = this.value; + return { newDocument: document2, removed }; + }, + move: function(obj, key, document2) { + let removed = getValueByPointer(document2, this.path); + if (removed) { + removed = _deepClone(removed); + } + const originalValue = applyOperation(document2, { + op: "remove", + path: this.from + }).removed; + applyOperation(document2, { + op: "add", + path: this.path, + value: originalValue + }); + return { newDocument: document2, removed }; + }, + copy: function(obj, key, document2) { + const valueToCopy = getValueByPointer(document2, this.from); + applyOperation(document2, { + op: "add", + path: this.path, + value: _deepClone(valueToCopy) + }); + return { newDocument: document2 }; + }, + test: function(obj, key, document2) { + return { newDocument: document2, test: _areEquals(obj[key], this.value) }; + }, + _get: function(obj, key, document2) { + this.value = obj[key]; + return { newDocument: document2 }; + } + }; + arrOps = { + add: function(arr3, i, document2) { + if (isInteger(i)) { + arr3.splice(i, 0, this.value); + } else { + arr3[i] = this.value; + } + return { newDocument: document2, index: i }; + }, + remove: function(arr3, i, document2) { + var removedList = arr3.splice(i, 1); + return { newDocument: document2, removed: removedList[0] }; + }, + replace: function(arr3, i, document2) { + var removed = arr3[i]; + arr3[i] = this.value; + return { newDocument: document2, removed }; + }, + move: objOps.move, + copy: objOps.copy, + test: objOps.test, + _get: objOps._get + }; + } +}); + +// node_modules/@langchain/core/dist/utils/fast-json-patch/src/duplex.js +function _generate(mirror, obj, patches, path, invertible) { + if (obj === mirror) { + return; + } + if (typeof obj.toJSON === "function") { + obj = obj.toJSON(); + } + var newKeys = _objectKeys(obj); + var oldKeys = _objectKeys(mirror); + var changed = false; + var deleted = false; + for (var t = oldKeys.length - 1; t >= 0; t--) { + var key = oldKeys[t]; + var oldVal = mirror[key]; + if (hasOwnProperty(obj, key) && !(obj[key] === void 0 && oldVal !== void 0 && Array.isArray(obj) === false)) { + var newVal = obj[key]; + if (typeof oldVal == "object" && oldVal != null && typeof newVal == "object" && newVal != null && Array.isArray(oldVal) === Array.isArray(newVal)) { + _generate(oldVal, newVal, patches, path + "/" + escapePathComponent(key), invertible); + } else { + if (oldVal !== newVal) { + changed = true; + if (invertible) { + patches.push({ + op: "test", + path: path + "/" + escapePathComponent(key), + value: _deepClone(oldVal) + }); + } + patches.push({ + op: "replace", + path: path + "/" + escapePathComponent(key), + value: _deepClone(newVal) + }); + } + } + } else if (Array.isArray(mirror) === Array.isArray(obj)) { + if (invertible) { + patches.push({ + op: "test", + path: path + "/" + escapePathComponent(key), + value: _deepClone(oldVal) + }); + } + patches.push({ + op: "remove", + path: path + "/" + escapePathComponent(key) + }); + deleted = true; + } else { + if (invertible) { + patches.push({ op: "test", path, value: mirror }); + } + patches.push({ op: "replace", path, value: obj }); + changed = true; + } + } + if (!deleted && newKeys.length == oldKeys.length) { + return; + } + for (var t = 0; t < newKeys.length; t++) { + var key = newKeys[t]; + if (!hasOwnProperty(mirror, key) && obj[key] !== void 0) { + patches.push({ + op: "add", + path: path + "/" + escapePathComponent(key), + value: _deepClone(obj[key]) + }); + } + } +} +function compare(tree1, tree2, invertible = false) { + var patches = []; + _generate(tree1, tree2, patches, "", invertible); + return patches; +} +var init_duplex = __esm({ + "node_modules/@langchain/core/dist/utils/fast-json-patch/src/duplex.js"() { + init_helpers(); + init_core(); + } +}); + +// node_modules/@langchain/core/dist/utils/fast-json-patch/index.js +var fast_json_patch_default; +var init_fast_json_patch = __esm({ + "node_modules/@langchain/core/dist/utils/fast-json-patch/index.js"() { + init_core(); + init_duplex(); + init_helpers(); + init_core(); + init_helpers(); + fast_json_patch_default = { + ...core_exports, + // ...duplex, + JsonPatchError: PatchError, + deepClone: _deepClone, + escapePathComponent, + unescapePathComponent + }; + } +}); + +// node_modules/@langchain/core/dist/singletons/async_local_storage/index.js +var MockAsyncLocalStorage2, mockAsyncLocalStorage2, LC_CHILD_KEY, AsyncLocalStorageProvider2, AsyncLocalStorageProviderSingleton2; +var init_async_local_storage = __esm({ + "node_modules/@langchain/core/dist/singletons/async_local_storage/index.js"() { + init_langsmith(); + init_globals(); + init_manager(); + MockAsyncLocalStorage2 = class { + getStore() { + return void 0; + } + run(_store, callback) { + return callback(); + } + enterWith(_store) { + return void 0; + } + }; + mockAsyncLocalStorage2 = new MockAsyncLocalStorage2(); + LC_CHILD_KEY = Symbol.for("lc:child_config"); + AsyncLocalStorageProvider2 = class { + getInstance() { + return getGlobalAsyncLocalStorageInstance() ?? mockAsyncLocalStorage2; + } + getRunnableConfig() { + const storage = this.getInstance(); + return storage.getStore()?.extra?.[LC_CHILD_KEY]; + } + runWithConfig(config2, callback, avoidCreatingRootRunTree) { + const callbackManager = CallbackManager._configureSync(config2?.callbacks, void 0, config2?.tags, void 0, config2?.metadata); + const storage = this.getInstance(); + const previousValue = storage.getStore(); + const parentRunId = callbackManager?.getParentRunId(); + const langChainTracer = callbackManager?.handlers?.find((handler) => handler?.name === "langchain_tracer"); + let runTree; + if (langChainTracer && parentRunId) { + runTree = langChainTracer.getRunTreeWithTracingConfig(parentRunId); + } else if (!avoidCreatingRootRunTree) { + runTree = new RunTree({ + name: "", + tracingEnabled: false + }); + } + if (runTree) { + runTree.extra = { ...runTree.extra, [LC_CHILD_KEY]: config2 }; + } + if (previousValue !== void 0 && previousValue[_CONTEXT_VARIABLES_KEY] !== void 0) { + if (runTree === void 0) { + runTree = {}; + } + runTree[_CONTEXT_VARIABLES_KEY] = previousValue[_CONTEXT_VARIABLES_KEY]; + } + return storage.run(runTree, callback); + } + initializeGlobalInstance(instance) { + if (getGlobalAsyncLocalStorageInstance() === void 0) { + setGlobalAsyncLocalStorageInstance(instance); + } + } + }; + AsyncLocalStorageProviderSingleton2 = new AsyncLocalStorageProvider2(); + } +}); + +// node_modules/@langchain/core/dist/singletons/index.js +var init_singletons = __esm({ + "node_modules/@langchain/core/dist/singletons/index.js"() { + init_async_local_storage(); + init_globals(); + } +}); + +// node_modules/@langchain/core/dist/runnables/config.js +async function getCallbackManagerForConfig(config2) { + return CallbackManager._configureSync(config2?.callbacks, void 0, config2?.tags, void 0, config2?.metadata); +} +function mergeConfigs(...configs) { + const copy = {}; + for (const options of configs.filter((c) => !!c)) { + for (const key of Object.keys(options)) { + if (key === "metadata") { + copy[key] = { ...copy[key], ...options[key] }; + } else if (key === "tags") { + const baseKeys = copy[key] ?? []; + copy[key] = [...new Set(baseKeys.concat(options[key] ?? []))]; + } else if (key === "configurable") { + copy[key] = { ...copy[key], ...options[key] }; + } else if (key === "timeout") { + if (copy.timeout === void 0) { + copy.timeout = options.timeout; + } else if (options.timeout !== void 0) { + copy.timeout = Math.min(copy.timeout, options.timeout); + } + } else if (key === "signal") { + if (copy.signal === void 0) { + copy.signal = options.signal; + } else if (options.signal !== void 0) { + if ("any" in AbortSignal) { + copy.signal = AbortSignal.any([ + copy.signal, + options.signal + ]); + } else { + copy.signal = options.signal; + } + } + } else if (key === "callbacks") { + const baseCallbacks = copy.callbacks; + const providedCallbacks = options.callbacks; + if (Array.isArray(providedCallbacks)) { + if (!baseCallbacks) { + copy.callbacks = providedCallbacks; + } else if (Array.isArray(baseCallbacks)) { + copy.callbacks = baseCallbacks.concat(providedCallbacks); + } else { + const manager = baseCallbacks.copy(); + for (const callback of providedCallbacks) { + manager.addHandler(ensureHandler(callback), true); + } + copy.callbacks = manager; + } + } else if (providedCallbacks) { + if (!baseCallbacks) { + copy.callbacks = providedCallbacks; + } else if (Array.isArray(baseCallbacks)) { + const manager = providedCallbacks.copy(); + for (const callback of baseCallbacks) { + manager.addHandler(ensureHandler(callback), true); + } + copy.callbacks = manager; + } else { + copy.callbacks = new CallbackManager(providedCallbacks._parentRunId, { + handlers: baseCallbacks.handlers.concat(providedCallbacks.handlers), + inheritableHandlers: baseCallbacks.inheritableHandlers.concat(providedCallbacks.inheritableHandlers), + tags: Array.from(new Set(baseCallbacks.tags.concat(providedCallbacks.tags))), + inheritableTags: Array.from(new Set(baseCallbacks.inheritableTags.concat(providedCallbacks.inheritableTags))), + metadata: { + ...baseCallbacks.metadata, + ...providedCallbacks.metadata + } + }); + } + } + } else { + const typedKey = key; + copy[typedKey] = options[typedKey] ?? copy[typedKey]; + } + } + } + return copy; +} +function ensureConfig(config2) { + const implicitConfig = AsyncLocalStorageProviderSingleton2.getRunnableConfig(); + let empty = { + tags: [], + metadata: {}, + recursionLimit: 25, + runId: void 0 + }; + if (implicitConfig) { + const { runId, runName, ...rest } = implicitConfig; + empty = Object.entries(rest).reduce( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (currentConfig, [key, value]) => { + if (value !== void 0) { + currentConfig[key] = value; + } + return currentConfig; + }, + empty + ); + } + if (config2) { + empty = Object.entries(config2).reduce( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (currentConfig, [key, value]) => { + if (value !== void 0) { + currentConfig[key] = value; + } + return currentConfig; + }, + empty + ); + } + if (empty?.configurable) { + for (const key of Object.keys(empty.configurable)) { + if (PRIMITIVES.has(typeof empty.configurable[key]) && !empty.metadata?.[key]) { + if (!empty.metadata) { + empty.metadata = {}; + } + empty.metadata[key] = empty.configurable[key]; + } + } + } + if (empty.timeout !== void 0) { + if (empty.timeout <= 0) { + throw new Error("Timeout must be a positive number"); + } + const timeoutSignal = AbortSignal.timeout(empty.timeout); + if (empty.signal !== void 0) { + if ("any" in AbortSignal) { + empty.signal = AbortSignal.any([empty.signal, timeoutSignal]); + } + } else { + empty.signal = timeoutSignal; + } + delete empty.timeout; + } + return empty; +} +function patchConfig(config2 = {}, { callbacks, maxConcurrency, recursionLimit, runName, configurable, runId } = {}) { + const newConfig = ensureConfig(config2); + if (callbacks !== void 0) { + delete newConfig.runName; + newConfig.callbacks = callbacks; + } + if (recursionLimit !== void 0) { + newConfig.recursionLimit = recursionLimit; + } + if (maxConcurrency !== void 0) { + newConfig.maxConcurrency = maxConcurrency; + } + if (runName !== void 0) { + newConfig.runName = runName; + } + if (configurable !== void 0) { + newConfig.configurable = { ...newConfig.configurable, ...configurable }; + } + if (runId !== void 0) { + delete newConfig.runId; + } + return newConfig; +} +function pickRunnableConfigKeys(config2) { + return config2 ? { + configurable: config2.configurable, + recursionLimit: config2.recursionLimit, + callbacks: config2.callbacks, + tags: config2.tags, + metadata: config2.metadata, + maxConcurrency: config2.maxConcurrency, + timeout: config2.timeout, + signal: config2.signal + } : void 0; +} +var DEFAULT_RECURSION_LIMIT, PRIMITIVES; +var init_config = __esm({ + "node_modules/@langchain/core/dist/runnables/config.js"() { + init_manager(); + init_singletons(); + DEFAULT_RECURSION_LIMIT = 25; + PRIMITIVES = /* @__PURE__ */ new Set(["string", "number", "boolean"]); + } +}); + +// node_modules/@langchain/core/dist/utils/signal.js +async function raceWithSignal(promise, signal) { + if (signal === void 0) { + return promise; + } + let listener; + return Promise.race([ + promise.catch((err) => { + if (!signal?.aborted) { + throw err; + } else { + return void 0; + } + }), + new Promise((_, reject) => { + listener = () => { + reject(new Error("Aborted")); + }; + signal.addEventListener("abort", listener); + if (signal.aborted) { + reject(new Error("Aborted")); + } + }) + ]).finally(() => signal.removeEventListener("abort", listener)); +} +var init_signal = __esm({ + "node_modules/@langchain/core/dist/utils/signal.js"() { + } +}); + +// node_modules/@langchain/core/dist/utils/stream.js +var stream_exports = {}; +__export(stream_exports, { + AsyncGeneratorWithSetup: () => AsyncGeneratorWithSetup, + IterableReadableStream: () => IterableReadableStream, + atee: () => atee, + concat: () => concat, + pipeGeneratorWithSetup: () => pipeGeneratorWithSetup +}); +function atee(iter, length = 2) { + const buffers = Array.from({ length }, () => []); + return buffers.map(async function* makeIter(buffer) { + while (true) { + if (buffer.length === 0) { + const result = await iter.next(); + for (const buffer2 of buffers) { + buffer2.push(result); + } + } else if (buffer[0].done) { + return; + } else { + yield buffer.shift().value; + } + } + }); +} +function concat(first, second) { + if (Array.isArray(first) && Array.isArray(second)) { + return first.concat(second); + } else if (typeof first === "string" && typeof second === "string") { + return first + second; + } else if (typeof first === "number" && typeof second === "number") { + return first + second; + } else if ( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + "concat" in first && // eslint-disable-next-line @typescript-eslint/no-explicit-any + typeof first.concat === "function" + ) { + return first.concat(second); + } else if (typeof first === "object" && typeof second === "object") { + const chunk = { ...first }; + for (const [key, value] of Object.entries(second)) { + if (key in chunk && !Array.isArray(chunk[key])) { + chunk[key] = concat(chunk[key], value); + } else { + chunk[key] = value; + } + } + return chunk; + } else { + throw new Error(`Cannot concat ${typeof first} and ${typeof second}`); + } +} +async function pipeGeneratorWithSetup(to, generator, startSetup, signal, ...args) { + const gen = new AsyncGeneratorWithSetup({ + generator, + startSetup, + signal + }); + const setup = await gen.setup; + return { output: to(gen, setup, ...args), setup }; +} +var IterableReadableStream, AsyncGeneratorWithSetup; +var init_stream = __esm({ + "node_modules/@langchain/core/dist/utils/stream.js"() { + init_config(); + init_singletons(); + init_signal(); + IterableReadableStream = class _IterableReadableStream extends ReadableStream { + constructor() { + super(...arguments); + Object.defineProperty(this, "reader", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + } + ensureReader() { + if (!this.reader) { + this.reader = this.getReader(); + } + } + async next() { + this.ensureReader(); + try { + const result = await this.reader.read(); + if (result.done) { + this.reader.releaseLock(); + return { + done: true, + value: void 0 + }; + } else { + return { + done: false, + value: result.value + }; + } + } catch (e) { + this.reader.releaseLock(); + throw e; + } + } + async return() { + this.ensureReader(); + if (this.locked) { + const cancelPromise = this.reader.cancel(); + this.reader.releaseLock(); + await cancelPromise; + } + return { done: true, value: void 0 }; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + async throw(e) { + this.ensureReader(); + if (this.locked) { + const cancelPromise = this.reader.cancel(); + this.reader.releaseLock(); + await cancelPromise; + } + throw e; + } + [Symbol.asyncIterator]() { + return this; + } + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore Not present in Node 18 types, required in latest Node 22 + async [Symbol.asyncDispose]() { + await this.return(); + } + static fromReadableStream(stream) { + const reader = stream.getReader(); + return new _IterableReadableStream({ + start(controller) { + return pump(); + function pump() { + return reader.read().then(({ done, value }) => { + if (done) { + controller.close(); + return; + } + controller.enqueue(value); + return pump(); + }); + } + }, + cancel() { + reader.releaseLock(); + } + }); + } + static fromAsyncGenerator(generator) { + return new _IterableReadableStream({ + async pull(controller) { + const { value, done } = await generator.next(); + if (done) { + controller.close(); + } + controller.enqueue(value); + }, + async cancel(reason) { + await generator.return(reason); + } + }); + } + }; + AsyncGeneratorWithSetup = class { + constructor(params) { + Object.defineProperty(this, "generator", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "setup", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "config", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "signal", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "firstResult", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "firstResultUsed", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + this.generator = params.generator; + this.config = params.config; + this.signal = params.signal ?? this.config?.signal; + this.setup = new Promise((resolve, reject) => { + void AsyncLocalStorageProviderSingleton2.runWithConfig(pickRunnableConfigKeys(params.config), async () => { + this.firstResult = params.generator.next(); + if (params.startSetup) { + this.firstResult.then(params.startSetup).then(resolve, reject); + } else { + this.firstResult.then((_result) => resolve(void 0), reject); + } + }, true); + }); + } + async next(...args) { + this.signal?.throwIfAborted(); + if (!this.firstResultUsed) { + this.firstResultUsed = true; + return this.firstResult; + } + return AsyncLocalStorageProviderSingleton2.runWithConfig(pickRunnableConfigKeys(this.config), this.signal ? async () => { + return raceWithSignal(this.generator.next(...args), this.signal); + } : async () => { + return this.generator.next(...args); + }, true); + } + async return(value) { + return this.generator.return(value); + } + async throw(e) { + return this.generator.throw(e); + } + [Symbol.asyncIterator]() { + return this; + } + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore Not present in Node 18 types, required in latest Node 22 + async [Symbol.asyncDispose]() { + await this.return(); + } + }; + } +}); + +// node_modules/@langchain/core/dist/tracers/log_stream.js +var log_stream_exports = {}; +__export(log_stream_exports, { + LogStreamCallbackHandler: () => LogStreamCallbackHandler, + RunLog: () => RunLog, + RunLogPatch: () => RunLogPatch, + isLogStreamHandler: () => isLogStreamHandler +}); +async function _getStandardizedInputs(run, schemaFormat) { + if (schemaFormat === "original") { + throw new Error("Do not assign inputs with original schema drop the key for now. When inputs are added to streamLog they should be added with standardized schema for streaming events."); + } + const { inputs } = run; + if (["retriever", "llm", "prompt"].includes(run.run_type)) { + return inputs; + } + if (Object.keys(inputs).length === 1 && inputs?.input === "") { + return void 0; + } + return inputs.input; +} +async function _getStandardizedOutputs(run, schemaFormat) { + const { outputs } = run; + if (schemaFormat === "original") { + return outputs; + } + if (["retriever", "llm", "prompt"].includes(run.run_type)) { + return outputs; + } + if (outputs !== void 0 && Object.keys(outputs).length === 1 && outputs?.output !== void 0) { + return outputs.output; + } + return outputs; +} +function isChatGenerationChunk(x) { + return x !== void 0 && x.message !== void 0; +} +var RunLogPatch, RunLog, isLogStreamHandler, LogStreamCallbackHandler; +var init_log_stream = __esm({ + "node_modules/@langchain/core/dist/tracers/log_stream.js"() { + init_fast_json_patch(); + init_base3(); + init_stream(); + init_ai(); + RunLogPatch = class { + constructor(fields) { + Object.defineProperty(this, "ops", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.ops = fields.ops ?? []; + } + concat(other) { + const ops = this.ops.concat(other.ops); + const states = applyPatch({}, ops); + return new RunLog({ + ops, + state: states[states.length - 1].newDocument + }); + } + }; + RunLog = class _RunLog extends RunLogPatch { + constructor(fields) { + super(fields); + Object.defineProperty(this, "state", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.state = fields.state; + } + concat(other) { + const ops = this.ops.concat(other.ops); + const states = applyPatch(this.state, other.ops); + return new _RunLog({ ops, state: states[states.length - 1].newDocument }); + } + static fromRunLogPatch(patch) { + const states = applyPatch({}, patch.ops); + return new _RunLog({ + ops: patch.ops, + state: states[states.length - 1].newDocument + }); + } + }; + isLogStreamHandler = (handler) => handler.name === "log_stream_tracer"; + LogStreamCallbackHandler = class extends BaseTracer { + constructor(fields) { + super({ _awaitHandler: true, ...fields }); + Object.defineProperty(this, "autoClose", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "includeNames", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "includeTypes", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "includeTags", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "excludeNames", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "excludeTypes", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "excludeTags", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "_schemaFormat", { + enumerable: true, + configurable: true, + writable: true, + value: "original" + }); + Object.defineProperty(this, "rootId", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "keyMapByRunId", { + enumerable: true, + configurable: true, + writable: true, + value: {} + }); + Object.defineProperty(this, "counterMapByRunName", { + enumerable: true, + configurable: true, + writable: true, + value: {} + }); + Object.defineProperty(this, "transformStream", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "writer", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "receiveStream", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "log_stream_tracer" + }); + Object.defineProperty(this, "lc_prefer_streaming", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + this.autoClose = fields?.autoClose ?? true; + this.includeNames = fields?.includeNames; + this.includeTypes = fields?.includeTypes; + this.includeTags = fields?.includeTags; + this.excludeNames = fields?.excludeNames; + this.excludeTypes = fields?.excludeTypes; + this.excludeTags = fields?.excludeTags; + this._schemaFormat = fields?._schemaFormat ?? this._schemaFormat; + this.transformStream = new TransformStream(); + this.writer = this.transformStream.writable.getWriter(); + this.receiveStream = IterableReadableStream.fromReadableStream(this.transformStream.readable); + } + [Symbol.asyncIterator]() { + return this.receiveStream; + } + async persistRun(_run) { + } + _includeRun(run) { + if (run.id === this.rootId) { + return false; + } + const runTags = run.tags ?? []; + let include = this.includeNames === void 0 && this.includeTags === void 0 && this.includeTypes === void 0; + if (this.includeNames !== void 0) { + include = include || this.includeNames.includes(run.name); + } + if (this.includeTypes !== void 0) { + include = include || this.includeTypes.includes(run.run_type); + } + if (this.includeTags !== void 0) { + include = include || runTags.find((tag) => this.includeTags?.includes(tag)) !== void 0; + } + if (this.excludeNames !== void 0) { + include = include && !this.excludeNames.includes(run.name); + } + if (this.excludeTypes !== void 0) { + include = include && !this.excludeTypes.includes(run.run_type); + } + if (this.excludeTags !== void 0) { + include = include && runTags.every((tag) => !this.excludeTags?.includes(tag)); + } + return include; + } + async *tapOutputIterable(runId, output) { + for await (const chunk of output) { + if (runId !== this.rootId) { + const key = this.keyMapByRunId[runId]; + if (key) { + await this.writer.write(new RunLogPatch({ + ops: [ + { + op: "add", + path: `/logs/${key}/streamed_output/-`, + value: chunk + } + ] + })); + } + } + yield chunk; + } + } + async onRunCreate(run) { + if (this.rootId === void 0) { + this.rootId = run.id; + await this.writer.write(new RunLogPatch({ + ops: [ + { + op: "replace", + path: "", + value: { + id: run.id, + name: run.name, + type: run.run_type, + streamed_output: [], + final_output: void 0, + logs: {} + } + } + ] + })); + } + if (!this._includeRun(run)) { + return; + } + if (this.counterMapByRunName[run.name] === void 0) { + this.counterMapByRunName[run.name] = 0; + } + this.counterMapByRunName[run.name] += 1; + const count = this.counterMapByRunName[run.name]; + this.keyMapByRunId[run.id] = count === 1 ? run.name : `${run.name}:${count}`; + const logEntry = { + id: run.id, + name: run.name, + type: run.run_type, + tags: run.tags ?? [], + metadata: run.extra?.metadata ?? {}, + start_time: new Date(run.start_time).toISOString(), + streamed_output: [], + streamed_output_str: [], + final_output: void 0, + end_time: void 0 + }; + if (this._schemaFormat === "streaming_events") { + logEntry.inputs = await _getStandardizedInputs(run, this._schemaFormat); + } + await this.writer.write(new RunLogPatch({ + ops: [ + { + op: "add", + path: `/logs/${this.keyMapByRunId[run.id]}`, + value: logEntry + } + ] + })); + } + async onRunUpdate(run) { + try { + const runName = this.keyMapByRunId[run.id]; + if (runName === void 0) { + return; + } + const ops = []; + if (this._schemaFormat === "streaming_events") { + ops.push({ + op: "replace", + path: `/logs/${runName}/inputs`, + value: await _getStandardizedInputs(run, this._schemaFormat) + }); + } + ops.push({ + op: "add", + path: `/logs/${runName}/final_output`, + value: await _getStandardizedOutputs(run, this._schemaFormat) + }); + if (run.end_time !== void 0) { + ops.push({ + op: "add", + path: `/logs/${runName}/end_time`, + value: new Date(run.end_time).toISOString() + }); + } + const patch = new RunLogPatch({ ops }); + await this.writer.write(patch); + } finally { + if (run.id === this.rootId) { + const patch = new RunLogPatch({ + ops: [ + { + op: "replace", + path: "/final_output", + value: await _getStandardizedOutputs(run, this._schemaFormat) + } + ] + }); + await this.writer.write(patch); + if (this.autoClose) { + await this.writer.close(); + } + } + } + } + async onLLMNewToken(run, token, kwargs) { + const runName = this.keyMapByRunId[run.id]; + if (runName === void 0) { + return; + } + const isChatModel2 = run.inputs.messages !== void 0; + let streamedOutputValue; + if (isChatModel2) { + if (isChatGenerationChunk(kwargs?.chunk)) { + streamedOutputValue = kwargs?.chunk; + } else { + streamedOutputValue = new AIMessageChunk({ + id: `run-${run.id}`, + content: token + }); + } + } else { + streamedOutputValue = token; + } + const patch = new RunLogPatch({ + ops: [ + { + op: "add", + path: `/logs/${runName}/streamed_output_str/-`, + value: token + }, + { + op: "add", + path: `/logs/${runName}/streamed_output/-`, + value: streamedOutputValue + } + ] + }); + await this.writer.write(patch); + } + }; + } +}); + +// node_modules/@langchain/core/dist/outputs.js +var outputs_exports = {}; +__export(outputs_exports, { + ChatGenerationChunk: () => ChatGenerationChunk, + GenerationChunk: () => GenerationChunk, + RUN_KEY: () => RUN_KEY +}); +var RUN_KEY, GenerationChunk, ChatGenerationChunk; +var init_outputs = __esm({ + "node_modules/@langchain/core/dist/outputs.js"() { + RUN_KEY = "__run"; + GenerationChunk = class _GenerationChunk { + constructor(fields) { + Object.defineProperty(this, "text", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "generationInfo", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.text = fields.text; + this.generationInfo = fields.generationInfo; + } + concat(chunk) { + return new _GenerationChunk({ + text: this.text + chunk.text, + generationInfo: { + ...this.generationInfo, + ...chunk.generationInfo + } + }); + } + }; + ChatGenerationChunk = class _ChatGenerationChunk extends GenerationChunk { + constructor(fields) { + super(fields); + Object.defineProperty(this, "message", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.message = fields.message; + } + concat(chunk) { + return new _ChatGenerationChunk({ + text: this.text + chunk.text, + generationInfo: { + ...this.generationInfo, + ...chunk.generationInfo + }, + message: this.message.concat(chunk.message) + }); + } + }; + } +}); + +// node_modules/@langchain/core/dist/tracers/event_stream.js +function assignName({ name, serialized }) { + if (name !== void 0) { + return name; + } + if (serialized?.name !== void 0) { + return serialized.name; + } else if (serialized?.id !== void 0 && Array.isArray(serialized?.id)) { + return serialized.id[serialized.id.length - 1]; + } + return "Unnamed"; +} +var isStreamEventsHandler, EventStreamCallbackHandler; +var init_event_stream = __esm({ + "node_modules/@langchain/core/dist/tracers/event_stream.js"() { + init_base3(); + init_stream(); + init_ai(); + init_outputs(); + isStreamEventsHandler = (handler) => handler.name === "event_stream_tracer"; + EventStreamCallbackHandler = class extends BaseTracer { + constructor(fields) { + super({ _awaitHandler: true, ...fields }); + Object.defineProperty(this, "autoClose", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "includeNames", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "includeTypes", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "includeTags", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "excludeNames", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "excludeTypes", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "excludeTags", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "runInfoMap", { + enumerable: true, + configurable: true, + writable: true, + value: /* @__PURE__ */ new Map() + }); + Object.defineProperty(this, "tappedPromises", { + enumerable: true, + configurable: true, + writable: true, + value: /* @__PURE__ */ new Map() + }); + Object.defineProperty(this, "transformStream", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "writer", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "receiveStream", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "event_stream_tracer" + }); + Object.defineProperty(this, "lc_prefer_streaming", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + this.autoClose = fields?.autoClose ?? true; + this.includeNames = fields?.includeNames; + this.includeTypes = fields?.includeTypes; + this.includeTags = fields?.includeTags; + this.excludeNames = fields?.excludeNames; + this.excludeTypes = fields?.excludeTypes; + this.excludeTags = fields?.excludeTags; + this.transformStream = new TransformStream(); + this.writer = this.transformStream.writable.getWriter(); + this.receiveStream = IterableReadableStream.fromReadableStream(this.transformStream.readable); + } + [Symbol.asyncIterator]() { + return this.receiveStream; + } + async persistRun(_run) { + } + _includeRun(run) { + const runTags = run.tags ?? []; + let include = this.includeNames === void 0 && this.includeTags === void 0 && this.includeTypes === void 0; + if (this.includeNames !== void 0) { + include = include || this.includeNames.includes(run.name); + } + if (this.includeTypes !== void 0) { + include = include || this.includeTypes.includes(run.runType); + } + if (this.includeTags !== void 0) { + include = include || runTags.find((tag) => this.includeTags?.includes(tag)) !== void 0; + } + if (this.excludeNames !== void 0) { + include = include && !this.excludeNames.includes(run.name); + } + if (this.excludeTypes !== void 0) { + include = include && !this.excludeTypes.includes(run.runType); + } + if (this.excludeTags !== void 0) { + include = include && runTags.every((tag) => !this.excludeTags?.includes(tag)); + } + return include; + } + async *tapOutputIterable(runId, outputStream) { + const firstChunk = await outputStream.next(); + if (firstChunk.done) { + return; + } + const runInfo = this.runInfoMap.get(runId); + if (runInfo === void 0) { + yield firstChunk.value; + return; + } + function _formatOutputChunk(eventType, data) { + if (eventType === "llm" && typeof data === "string") { + return new GenerationChunk({ text: data }); + } + return data; + } + let tappedPromise = this.tappedPromises.get(runId); + if (tappedPromise === void 0) { + let tappedPromiseResolver; + tappedPromise = new Promise((resolve) => { + tappedPromiseResolver = resolve; + }); + this.tappedPromises.set(runId, tappedPromise); + try { + const event = { + event: `on_${runInfo.runType}_stream`, + run_id: runId, + name: runInfo.name, + tags: runInfo.tags, + metadata: runInfo.metadata, + data: {} + }; + await this.send({ + ...event, + data: { + chunk: _formatOutputChunk(runInfo.runType, firstChunk.value) + } + }, runInfo); + yield firstChunk.value; + for await (const chunk of outputStream) { + if (runInfo.runType !== "tool" && runInfo.runType !== "retriever") { + await this.send({ + ...event, + data: { + chunk: _formatOutputChunk(runInfo.runType, chunk) + } + }, runInfo); + } + yield chunk; + } + } finally { + tappedPromiseResolver(); + } + } else { + yield firstChunk.value; + for await (const chunk of outputStream) { + yield chunk; + } + } + } + async send(payload, run) { + if (this._includeRun(run)) { + await this.writer.write(payload); + } + } + async sendEndEvent(payload, run) { + const tappedPromise = this.tappedPromises.get(payload.run_id); + if (tappedPromise !== void 0) { + void tappedPromise.then(() => { + void this.send(payload, run); + }); + } else { + await this.send(payload, run); + } + } + async onLLMStart(run) { + const runName = assignName(run); + const runType = run.inputs.messages !== void 0 ? "chat_model" : "llm"; + const runInfo = { + tags: run.tags ?? [], + metadata: run.extra?.metadata ?? {}, + name: runName, + runType, + inputs: run.inputs + }; + this.runInfoMap.set(run.id, runInfo); + const eventName = `on_${runType}_start`; + await this.send({ + event: eventName, + data: { + input: run.inputs + }, + name: runName, + tags: run.tags ?? [], + run_id: run.id, + metadata: run.extra?.metadata ?? {} + }, runInfo); + } + async onLLMNewToken(run, token, kwargs) { + const runInfo = this.runInfoMap.get(run.id); + let chunk; + let eventName; + if (runInfo === void 0) { + throw new Error(`onLLMNewToken: Run ID ${run.id} not found in run map.`); + } + if (this.runInfoMap.size === 1) { + return; + } + if (runInfo.runType === "chat_model") { + eventName = "on_chat_model_stream"; + if (kwargs?.chunk === void 0) { + chunk = new AIMessageChunk({ content: token, id: `run-${run.id}` }); + } else { + chunk = kwargs.chunk.message; + } + } else if (runInfo.runType === "llm") { + eventName = "on_llm_stream"; + if (kwargs?.chunk === void 0) { + chunk = new GenerationChunk({ text: token }); + } else { + chunk = kwargs.chunk; + } + } else { + throw new Error(`Unexpected run type ${runInfo.runType}`); + } + await this.send({ + event: eventName, + data: { + chunk + }, + run_id: run.id, + name: runInfo.name, + tags: runInfo.tags, + metadata: runInfo.metadata + }, runInfo); + } + async onLLMEnd(run) { + const runInfo = this.runInfoMap.get(run.id); + this.runInfoMap.delete(run.id); + let eventName; + if (runInfo === void 0) { + throw new Error(`onLLMEnd: Run ID ${run.id} not found in run map.`); + } + const generations = run.outputs?.generations; + let output; + if (runInfo.runType === "chat_model") { + for (const generation of generations ?? []) { + if (output !== void 0) { + break; + } + output = generation[0]?.message; + } + eventName = "on_chat_model_end"; + } else if (runInfo.runType === "llm") { + output = { + generations: generations?.map((generation) => { + return generation.map((chunk) => { + return { + text: chunk.text, + generationInfo: chunk.generationInfo + }; + }); + }), + llmOutput: run.outputs?.llmOutput ?? {} + }; + eventName = "on_llm_end"; + } else { + throw new Error(`onLLMEnd: Unexpected run type: ${runInfo.runType}`); + } + await this.sendEndEvent({ + event: eventName, + data: { + output, + input: runInfo.inputs + }, + run_id: run.id, + name: runInfo.name, + tags: runInfo.tags, + metadata: runInfo.metadata + }, runInfo); + } + async onChainStart(run) { + const runName = assignName(run); + const runType = run.run_type ?? "chain"; + const runInfo = { + tags: run.tags ?? [], + metadata: run.extra?.metadata ?? {}, + name: runName, + runType: run.run_type + }; + let eventData = {}; + if (run.inputs.input === "" && Object.keys(run.inputs).length === 1) { + eventData = {}; + runInfo.inputs = {}; + } else if (run.inputs.input !== void 0) { + eventData.input = run.inputs.input; + runInfo.inputs = run.inputs.input; + } else { + eventData.input = run.inputs; + runInfo.inputs = run.inputs; + } + this.runInfoMap.set(run.id, runInfo); + await this.send({ + event: `on_${runType}_start`, + data: eventData, + name: runName, + tags: run.tags ?? [], + run_id: run.id, + metadata: run.extra?.metadata ?? {} + }, runInfo); + } + async onChainEnd(run) { + const runInfo = this.runInfoMap.get(run.id); + this.runInfoMap.delete(run.id); + if (runInfo === void 0) { + throw new Error(`onChainEnd: Run ID ${run.id} not found in run map.`); + } + const eventName = `on_${run.run_type}_end`; + const inputs = run.inputs ?? runInfo.inputs ?? {}; + const outputs = run.outputs?.output ?? run.outputs; + const data = { + output: outputs, + input: inputs + }; + if (inputs.input && Object.keys(inputs).length === 1) { + data.input = inputs.input; + runInfo.inputs = inputs.input; + } + await this.sendEndEvent({ + event: eventName, + data, + run_id: run.id, + name: runInfo.name, + tags: runInfo.tags, + metadata: runInfo.metadata ?? {} + }, runInfo); + } + async onToolStart(run) { + const runName = assignName(run); + const runInfo = { + tags: run.tags ?? [], + metadata: run.extra?.metadata ?? {}, + name: runName, + runType: "tool", + inputs: run.inputs ?? {} + }; + this.runInfoMap.set(run.id, runInfo); + await this.send({ + event: "on_tool_start", + data: { + input: run.inputs ?? {} + }, + name: runName, + run_id: run.id, + tags: run.tags ?? [], + metadata: run.extra?.metadata ?? {} + }, runInfo); + } + async onToolEnd(run) { + const runInfo = this.runInfoMap.get(run.id); + this.runInfoMap.delete(run.id); + if (runInfo === void 0) { + throw new Error(`onToolEnd: Run ID ${run.id} not found in run map.`); + } + if (runInfo.inputs === void 0) { + throw new Error(`onToolEnd: Run ID ${run.id} is a tool call, and is expected to have traced inputs.`); + } + const output = run.outputs?.output === void 0 ? run.outputs : run.outputs.output; + await this.sendEndEvent({ + event: "on_tool_end", + data: { + output, + input: runInfo.inputs + }, + run_id: run.id, + name: runInfo.name, + tags: runInfo.tags, + metadata: runInfo.metadata + }, runInfo); + } + async onRetrieverStart(run) { + const runName = assignName(run); + const runType = "retriever"; + const runInfo = { + tags: run.tags ?? [], + metadata: run.extra?.metadata ?? {}, + name: runName, + runType, + inputs: { + query: run.inputs.query + } + }; + this.runInfoMap.set(run.id, runInfo); + await this.send({ + event: "on_retriever_start", + data: { + input: { + query: run.inputs.query + } + }, + name: runName, + tags: run.tags ?? [], + run_id: run.id, + metadata: run.extra?.metadata ?? {} + }, runInfo); + } + async onRetrieverEnd(run) { + const runInfo = this.runInfoMap.get(run.id); + this.runInfoMap.delete(run.id); + if (runInfo === void 0) { + throw new Error(`onRetrieverEnd: Run ID ${run.id} not found in run map.`); + } + await this.sendEndEvent({ + event: "on_retriever_end", + data: { + output: run.outputs?.documents ?? run.outputs, + input: runInfo.inputs + }, + run_id: run.id, + name: runInfo.name, + tags: runInfo.tags, + metadata: runInfo.metadata + }, runInfo); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + async handleCustomEvent(eventName, data, runId) { + const runInfo = this.runInfoMap.get(runId); + if (runInfo === void 0) { + throw new Error(`handleCustomEvent: Run ID ${runId} not found in run map.`); + } + await this.send({ + event: "on_custom_event", + run_id: runId, + name: eventName, + tags: runInfo.tags, + metadata: runInfo.metadata, + data + }, runInfo); + } + async finish() { + const pendingPromises = [...this.tappedPromises.values()]; + void Promise.all(pendingPromises).finally(() => { + void this.writer.close(); + }); + } + }; + } +}); + +// node_modules/@langchain/core/dist/utils/async_caller.js +var async_caller_exports = {}; +__export(async_caller_exports, { + AsyncCaller: () => AsyncCaller2 +}); +var import_p_retry2, import_p_queue3, STATUS_NO_RETRY2, defaultFailedAttemptHandler, AsyncCaller2; +var init_async_caller2 = __esm({ + "node_modules/@langchain/core/dist/utils/async_caller.js"() { + import_p_retry2 = __toESM(require_p_retry(), 1); + import_p_queue3 = __toESM(require_dist(), 1); + STATUS_NO_RETRY2 = [ + 400, + // Bad Request + 401, + // Unauthorized + 402, + // Payment Required + 403, + // Forbidden + 404, + // Not Found + 405, + // Method Not Allowed + 406, + // Not Acceptable + 407, + // Proxy Authentication Required + 409 + // Conflict + ]; + defaultFailedAttemptHandler = (error) => { + if (error.message.startsWith("Cancel") || error.message.startsWith("AbortError") || error.name === "AbortError") { + throw error; + } + if (error?.code === "ECONNABORTED") { + throw error; + } + const status = ( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + error?.response?.status ?? error?.status + ); + if (status && STATUS_NO_RETRY2.includes(+status)) { + throw error; + } + if (error?.error?.code === "insufficient_quota") { + const err = new Error(error?.message); + err.name = "InsufficientQuotaError"; + throw err; + } + }; + AsyncCaller2 = class { + constructor(params) { + Object.defineProperty(this, "maxConcurrency", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "maxRetries", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "onFailedAttempt", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "queue", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.maxConcurrency = params.maxConcurrency ?? Infinity; + this.maxRetries = params.maxRetries ?? 6; + this.onFailedAttempt = params.onFailedAttempt ?? defaultFailedAttemptHandler; + const PQueue = "default" in import_p_queue3.default ? import_p_queue3.default.default : import_p_queue3.default; + this.queue = new PQueue({ concurrency: this.maxConcurrency }); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + call(callable, ...args) { + return this.queue.add(() => (0, import_p_retry2.default)(() => callable(...args).catch((error) => { + if (error instanceof Error) { + throw error; + } else { + throw new Error(error); + } + }), { + onFailedAttempt: this.onFailedAttempt, + retries: this.maxRetries, + randomize: true + // If needed we can change some of the defaults here, + // but they're quite sensible. + }), { throwOnTimeout: true }); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + callWithOptions(options, callable, ...args) { + if (options.signal) { + return Promise.race([ + this.call(callable, ...args), + new Promise((_, reject) => { + options.signal?.addEventListener("abort", () => { + reject(new Error("AbortError")); + }); + }) + ]); + } + return this.call(callable, ...args); + } + fetch(...args) { + return this.call(() => fetch(...args).then((res) => res.ok ? res : Promise.reject(res))); + } + }; + } +}); + +// node_modules/@langchain/core/dist/tracers/root_listener.js +var RootListenersTracer; +var init_root_listener = __esm({ + "node_modules/@langchain/core/dist/tracers/root_listener.js"() { + init_base3(); + RootListenersTracer = class extends BaseTracer { + constructor({ config: config2, onStart, onEnd, onError }) { + super({ _awaitHandler: true }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "RootListenersTracer" + }); + Object.defineProperty(this, "rootId", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "config", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "argOnStart", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "argOnEnd", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "argOnError", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.config = config2; + this.argOnStart = onStart; + this.argOnEnd = onEnd; + this.argOnError = onError; + } + /** + * This is a legacy method only called once for an entire run tree + * therefore not useful here + * @param {Run} _ Not used + */ + persistRun(_) { + return Promise.resolve(); + } + async onRunCreate(run) { + if (this.rootId) { + return; + } + this.rootId = run.id; + if (this.argOnStart) { + await this.argOnStart(run, this.config); + } + } + async onRunUpdate(run) { + if (run.id !== this.rootId) { + return; + } + if (!run.error) { + if (this.argOnEnd) { + await this.argOnEnd(run, this.config); + } + } else if (this.argOnError) { + await this.argOnError(run, this.config); + } + } + }; + } +}); + +// node_modules/@langchain/core/dist/runnables/utils.js +function isRunnableInterface(thing) { + return thing ? thing.lc_runnable : false; +} +var _RootEventFilter; +var init_utils3 = __esm({ + "node_modules/@langchain/core/dist/runnables/utils.js"() { + _RootEventFilter = class { + constructor(fields) { + Object.defineProperty(this, "includeNames", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "includeTypes", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "includeTags", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "excludeNames", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "excludeTypes", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "excludeTags", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.includeNames = fields.includeNames; + this.includeTypes = fields.includeTypes; + this.includeTags = fields.includeTags; + this.excludeNames = fields.excludeNames; + this.excludeTypes = fields.excludeTypes; + this.excludeTags = fields.excludeTags; + } + includeEvent(event, rootType) { + let include = this.includeNames === void 0 && this.includeTypes === void 0 && this.includeTags === void 0; + const eventTags = event.tags ?? []; + if (this.includeNames !== void 0) { + include = include || this.includeNames.includes(event.name); + } + if (this.includeTypes !== void 0) { + include = include || this.includeTypes.includes(rootType); + } + if (this.includeTags !== void 0) { + include = include || eventTags.some((tag) => this.includeTags?.includes(tag)); + } + if (this.excludeNames !== void 0) { + include = include && !this.excludeNames.includes(event.name); + } + if (this.excludeTypes !== void 0) { + include = include && !this.excludeTypes.includes(rootType); + } + if (this.excludeTags !== void 0) { + include = include && eventTags.every((tag) => !this.excludeTags?.includes(tag)); + } + return include; + } + }; + } +}); + +// node_modules/@langchain/core/dist/runnables/graph_mermaid.js +function _escapeNodeLabel(nodeLabel) { + return nodeLabel.replace(/[^a-zA-Z-_0-9]/g, "_"); +} +function _generateMermaidGraphStyles(nodeColors) { + let styles2 = ""; + for (const [className, color2] of Object.entries(nodeColors)) { + styles2 += ` classDef ${className} ${color2}; +`; + } + return styles2; +} +function drawMermaid(nodes, edges, config2) { + const { firstNode, lastNode, nodeColors, withStyles = true, curveStyle = "linear", wrapLabelNWords = 9 } = config2 ?? {}; + let mermaidGraph = withStyles ? `%%{init: {'flowchart': {'curve': '${curveStyle}'}}}%% +graph TD; +` : "graph TD;\n"; + if (withStyles) { + const defaultClassLabel = "default"; + const formatDict = { + [defaultClassLabel]: "{0}({1})" + }; + if (firstNode !== void 0) { + formatDict[firstNode] = "{0}([{1}]):::first"; + } + if (lastNode !== void 0) { + formatDict[lastNode] = "{0}([{1}]):::last"; + } + for (const [key, node] of Object.entries(nodes)) { + const nodeName = node.name.split(":").pop() ?? ""; + const label = MARKDOWN_SPECIAL_CHARS.some((char) => nodeName.startsWith(char) && nodeName.endsWith(char)) ? `

${nodeName}

` : nodeName; + let finalLabel = label; + if (Object.keys(node.metadata ?? {}).length) { + finalLabel += `
${Object.entries(node.metadata ?? {}).map(([k, v]) => `${k} = ${v}`).join("\n")}`; + } + const nodeLabel = (formatDict[key] ?? formatDict[defaultClassLabel]).replace("{0}", _escapeNodeLabel(key)).replace("{1}", finalLabel); + mermaidGraph += ` ${nodeLabel} +`; + } + } + const edgeGroups = {}; + for (const edge of edges) { + const srcParts = edge.source.split(":"); + const tgtParts = edge.target.split(":"); + const commonPrefix = srcParts.filter((src, i) => src === tgtParts[i]).join(":"); + if (!edgeGroups[commonPrefix]) { + edgeGroups[commonPrefix] = []; + } + edgeGroups[commonPrefix].push(edge); + } + const seenSubgraphs = /* @__PURE__ */ new Set(); + function addSubgraph(edges2, prefix) { + const selfLoop = edges2.length === 1 && edges2[0].source === edges2[0].target; + if (prefix && !selfLoop) { + const subgraph = prefix.split(":").pop(); + if (seenSubgraphs.has(subgraph)) { + throw new Error(`Found duplicate subgraph '${subgraph}' -- this likely means that you're reusing a subgraph node with the same name. Please adjust your graph to have subgraph nodes with unique names.`); + } + seenSubgraphs.add(subgraph); + mermaidGraph += ` subgraph ${subgraph} +`; + } + for (const edge of edges2) { + const { source, target, data, conditional } = edge; + let edgeLabel = ""; + if (data !== void 0) { + let edgeData = data; + const words = edgeData.split(" "); + if (words.length > wrapLabelNWords) { + edgeData = Array.from({ length: Math.ceil(words.length / wrapLabelNWords) }, (_, i) => words.slice(i * wrapLabelNWords, (i + 1) * wrapLabelNWords).join(" ")).join(" 
 "); + } + edgeLabel = conditional ? ` -.  ${edgeData}  .-> ` : ` --  ${edgeData}  --> `; + } else { + edgeLabel = conditional ? " -.-> " : " --> "; + } + mermaidGraph += ` ${_escapeNodeLabel(source)}${edgeLabel}${_escapeNodeLabel(target)}; +`; + } + for (const nestedPrefix in edgeGroups) { + if (nestedPrefix.startsWith(`${prefix}:`) && nestedPrefix !== prefix) { + addSubgraph(edgeGroups[nestedPrefix], nestedPrefix); + } + } + if (prefix && !selfLoop) { + mermaidGraph += " end\n"; + } + } + addSubgraph(edgeGroups[""] ?? [], ""); + for (const prefix in edgeGroups) { + if (!prefix.includes(":") && prefix !== "") { + addSubgraph(edgeGroups[prefix], prefix); + } + } + if (withStyles) { + mermaidGraph += _generateMermaidGraphStyles(nodeColors ?? {}); + } + return mermaidGraph; +} +async function drawMermaidPng(mermaidSyntax, config2) { + let { backgroundColor = "white" } = config2 ?? {}; + const mermaidSyntaxEncoded = btoa(mermaidSyntax); + if (backgroundColor !== void 0) { + const hexColorPattern = /^#(?:[0-9a-fA-F]{3}){1,2}$/; + if (!hexColorPattern.test(backgroundColor)) { + backgroundColor = `!${backgroundColor}`; + } + } + const imageUrl = `https://mermaid.ink/img/${mermaidSyntaxEncoded}?bgColor=${backgroundColor}`; + const res = await fetch(imageUrl); + if (!res.ok) { + throw new Error([ + `Failed to render the graph using the Mermaid.INK API.`, + `Status code: ${res.status}`, + `Status text: ${res.statusText}` + ].join("\n")); + } + const content = await res.blob(); + return content; +} +var MARKDOWN_SPECIAL_CHARS; +var init_graph_mermaid = __esm({ + "node_modules/@langchain/core/dist/runnables/graph_mermaid.js"() { + MARKDOWN_SPECIAL_CHARS = ["*", "_", "`"]; + } +}); + +// node_modules/zod/v4/core/core.js +// @__NO_SIDE_EFFECTS__ +function $constructor(name, initializer2, params) { + function init(inst, def) { + var _a2; + Object.defineProperty(inst, "_zod", { + value: inst._zod ?? {}, + enumerable: false + }); + (_a2 = inst._zod).traits ?? (_a2.traits = /* @__PURE__ */ new Set()); + inst._zod.traits.add(name); + initializer2(inst, def); + for (const k in _.prototype) { + if (!(k in inst)) + Object.defineProperty(inst, k, { value: _.prototype[k].bind(inst) }); + } + inst._zod.constr = _; + inst._zod.def = def; + } + const Parent = params?.Parent ?? Object; + class Definition extends Parent { + } + Object.defineProperty(Definition, "name", { value: name }); + function _(def) { + var _a2; + const inst = params?.Parent ? new Definition() : this; + init(inst, def); + (_a2 = inst._zod).deferred ?? (_a2.deferred = []); + for (const fn of inst._zod.deferred) { + fn(); + } + return inst; + } + Object.defineProperty(_, "init", { value: init }); + Object.defineProperty(_, Symbol.hasInstance, { + value: (inst) => { + if (params?.Parent && inst instanceof params.Parent) + return true; + return inst?._zod?.traits?.has(name); + } + }); + Object.defineProperty(_, "name", { value: name }); + return _; +} +function config(newConfig) { + if (newConfig) + Object.assign(globalConfig, newConfig); + return globalConfig; +} +var NEVER2, $brand, $ZodAsyncError, globalConfig; +var init_core2 = __esm({ + "node_modules/zod/v4/core/core.js"() { + NEVER2 = Object.freeze({ + status: "aborted" + }); + $brand = Symbol("zod_brand"); + $ZodAsyncError = class extends Error { + constructor() { + super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); + } + }; + globalConfig = {}; + } +}); + +// node_modules/zod/v4/core/util.js +var util_exports = {}; +__export(util_exports, { + BIGINT_FORMAT_RANGES: () => BIGINT_FORMAT_RANGES, + Class: () => Class, + NUMBER_FORMAT_RANGES: () => NUMBER_FORMAT_RANGES, + aborted: () => aborted, + allowsEval: () => allowsEval, + assert: () => assert, + assertEqual: () => assertEqual, + assertIs: () => assertIs, + assertNever: () => assertNever, + assertNotEqual: () => assertNotEqual, + assignProp: () => assignProp, + cached: () => cached, + captureStackTrace: () => captureStackTrace, + cleanEnum: () => cleanEnum, + cleanRegex: () => cleanRegex, + clone: () => clone, + createTransparentProxy: () => createTransparentProxy, + defineLazy: () => defineLazy, + esc: () => esc, + escapeRegex: () => escapeRegex, + extend: () => extend, + finalizeIssue: () => finalizeIssue, + floatSafeRemainder: () => floatSafeRemainder2, + getElementAtPath: () => getElementAtPath, + getEnumValues: () => getEnumValues, + getLengthableOrigin: () => getLengthableOrigin, + getParsedType: () => getParsedType2, + getSizableOrigin: () => getSizableOrigin, + isObject: () => isObject, + isPlainObject: () => isPlainObject, + issue: () => issue, + joinValues: () => joinValues, + jsonStringifyReplacer: () => jsonStringifyReplacer, + merge: () => merge, + normalizeParams: () => normalizeParams, + nullish: () => nullish, + numKeys: () => numKeys, + omit: () => omit, + optionalKeys: () => optionalKeys, + partial: () => partial, + pick: () => pick, + prefixIssues: () => prefixIssues, + primitiveTypes: () => primitiveTypes, + promiseAllObject: () => promiseAllObject, + propertyKeyTypes: () => propertyKeyTypes, + randomString: () => randomString, + required: () => required, + stringifyPrimitive: () => stringifyPrimitive, + unwrapMessage: () => unwrapMessage +}); +function assertEqual(val) { + return val; +} +function assertNotEqual(val) { + return val; +} +function assertIs(_arg) { +} +function assertNever(_x) { + throw new Error(); +} +function assert(_) { +} +function getEnumValues(entries) { + const numericValues = Object.values(entries).filter((v) => typeof v === "number"); + const values = Object.entries(entries).filter(([k, _]) => numericValues.indexOf(+k) === -1).map(([_, v]) => v); + return values; +} +function joinValues(array, separator = "|") { + return array.map((val) => stringifyPrimitive(val)).join(separator); +} +function jsonStringifyReplacer(_, value) { + if (typeof value === "bigint") + return value.toString(); + return value; +} +function cached(getter) { + const set = false; + return { + get value() { + if (!set) { + const value = getter(); + Object.defineProperty(this, "value", { value }); + return value; + } + throw new Error("cached value already set"); + } + }; +} +function nullish(input) { + return input === null || input === void 0; +} +function cleanRegex(source) { + const start = source.startsWith("^") ? 1 : 0; + const end = source.endsWith("$") ? source.length - 1 : source.length; + return source.slice(start, end); +} +function floatSafeRemainder2(val, step) { + const valDecCount = (val.toString().split(".")[1] || "").length; + const stepDecCount = (step.toString().split(".")[1] || "").length; + const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; + const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); + const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); + return valInt % stepInt / 10 ** decCount; +} +function defineLazy(object, key, getter) { + const set = false; + Object.defineProperty(object, key, { + get() { + if (!set) { + const value = getter(); + object[key] = value; + return value; + } + throw new Error("cached value already set"); + }, + set(v) { + Object.defineProperty(object, key, { + value: v + // configurable: true, + }); + }, + configurable: true + }); +} +function assignProp(target, prop, value) { + Object.defineProperty(target, prop, { + value, + writable: true, + enumerable: true, + configurable: true + }); +} +function getElementAtPath(obj, path) { + if (!path) + return obj; + return path.reduce((acc, key) => acc?.[key], obj); +} +function promiseAllObject(promisesObj) { + const keys = Object.keys(promisesObj); + const promises = keys.map((key) => promisesObj[key]); + return Promise.all(promises).then((results) => { + const resolvedObj = {}; + for (let i = 0; i < keys.length; i++) { + resolvedObj[keys[i]] = results[i]; + } + return resolvedObj; + }); +} +function randomString(length = 10) { + const chars = "abcdefghijklmnopqrstuvwxyz"; + let str = ""; + for (let i = 0; i < length; i++) { + str += chars[Math.floor(Math.random() * chars.length)]; + } + return str; +} +function esc(str) { + return JSON.stringify(str); +} +function isObject(data) { + return typeof data === "object" && data !== null && !Array.isArray(data); +} +function isPlainObject(o) { + if (isObject(o) === false) + return false; + const ctor = o.constructor; + if (ctor === void 0) + return true; + const prot = ctor.prototype; + if (isObject(prot) === false) + return false; + if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) { + return false; + } + return true; +} +function numKeys(data) { + let keyCount = 0; + for (const key in data) { + if (Object.prototype.hasOwnProperty.call(data, key)) { + keyCount++; + } + } + return keyCount; +} +function escapeRegex(str) { + return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} +function clone(inst, def, params) { + const cl = new inst._zod.constr(def ?? inst._zod.def); + if (!def || params?.parent) + cl._zod.parent = inst; + return cl; +} +function normalizeParams(_params) { + const params = _params; + if (!params) + return {}; + if (typeof params === "string") + return { error: () => params }; + if (params?.message !== void 0) { + if (params?.error !== void 0) + throw new Error("Cannot specify both `message` and `error` params"); + params.error = params.message; + } + delete params.message; + if (typeof params.error === "string") + return { ...params, error: () => params.error }; + return params; +} +function createTransparentProxy(getter) { + let target; + return new Proxy({}, { + get(_, prop, receiver) { + target ?? (target = getter()); + return Reflect.get(target, prop, receiver); + }, + set(_, prop, value, receiver) { + target ?? (target = getter()); + return Reflect.set(target, prop, value, receiver); + }, + has(_, prop) { + target ?? (target = getter()); + return Reflect.has(target, prop); + }, + deleteProperty(_, prop) { + target ?? (target = getter()); + return Reflect.deleteProperty(target, prop); + }, + ownKeys(_) { + target ?? (target = getter()); + return Reflect.ownKeys(target); + }, + getOwnPropertyDescriptor(_, prop) { + target ?? (target = getter()); + return Reflect.getOwnPropertyDescriptor(target, prop); + }, + defineProperty(_, prop, descriptor) { + target ?? (target = getter()); + return Reflect.defineProperty(target, prop, descriptor); + } + }); +} +function stringifyPrimitive(value) { + if (typeof value === "bigint") + return value.toString() + "n"; + if (typeof value === "string") + return `"${value}"`; + return `${value}`; +} +function optionalKeys(shape) { + return Object.keys(shape).filter((k) => { + return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional"; + }); +} +function pick(schema, mask) { + const newShape = {}; + const currDef = schema._zod.def; + for (const key in mask) { + if (!(key in currDef.shape)) { + throw new Error(`Unrecognized key: "${key}"`); + } + if (!mask[key]) + continue; + newShape[key] = currDef.shape[key]; + } + return clone(schema, { + ...schema._zod.def, + shape: newShape, + checks: [] + }); +} +function omit(schema, mask) { + const newShape = { ...schema._zod.def.shape }; + const currDef = schema._zod.def; + for (const key in mask) { + if (!(key in currDef.shape)) { + throw new Error(`Unrecognized key: "${key}"`); + } + if (!mask[key]) + continue; + delete newShape[key]; + } + return clone(schema, { + ...schema._zod.def, + shape: newShape, + checks: [] + }); +} +function extend(schema, shape) { + if (!isPlainObject(shape)) { + throw new Error("Invalid input to extend: expected a plain object"); + } + const def = { + ...schema._zod.def, + get shape() { + const _shape = { ...schema._zod.def.shape, ...shape }; + assignProp(this, "shape", _shape); + return _shape; + }, + checks: [] + // delete existing checks + }; + return clone(schema, def); +} +function merge(a, b) { + return clone(a, { + ...a._zod.def, + get shape() { + const _shape = { ...a._zod.def.shape, ...b._zod.def.shape }; + assignProp(this, "shape", _shape); + return _shape; + }, + catchall: b._zod.def.catchall, + checks: [] + // delete existing checks + }); +} +function partial(Class2, schema, mask) { + const oldShape = schema._zod.def.shape; + const shape = { ...oldShape }; + if (mask) { + for (const key in mask) { + if (!(key in oldShape)) { + throw new Error(`Unrecognized key: "${key}"`); + } + if (!mask[key]) + continue; + shape[key] = Class2 ? new Class2({ + type: "optional", + innerType: oldShape[key] + }) : oldShape[key]; + } + } else { + for (const key in oldShape) { + shape[key] = Class2 ? new Class2({ + type: "optional", + innerType: oldShape[key] + }) : oldShape[key]; + } + } + return clone(schema, { + ...schema._zod.def, + shape, + checks: [] + }); +} +function required(Class2, schema, mask) { + const oldShape = schema._zod.def.shape; + const shape = { ...oldShape }; + if (mask) { + for (const key in mask) { + if (!(key in shape)) { + throw new Error(`Unrecognized key: "${key}"`); + } + if (!mask[key]) + continue; + shape[key] = new Class2({ + type: "nonoptional", + innerType: oldShape[key] + }); + } + } else { + for (const key in oldShape) { + shape[key] = new Class2({ + type: "nonoptional", + innerType: oldShape[key] + }); + } + } + return clone(schema, { + ...schema._zod.def, + shape, + // optional: [], + checks: [] + }); +} +function aborted(x, startIndex = 0) { + for (let i = startIndex; i < x.issues.length; i++) { + if (x.issues[i]?.continue !== true) + return true; + } + return false; +} +function prefixIssues(path, issues) { + return issues.map((iss) => { + var _a2; + (_a2 = iss).path ?? (_a2.path = []); + iss.path.unshift(path); + return iss; + }); +} +function unwrapMessage(message) { + return typeof message === "string" ? message : message?.message; +} +function finalizeIssue(iss, ctx, config2) { + const full = { ...iss, path: iss.path ?? [] }; + if (!iss.message) { + const message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config2.customError?.(iss)) ?? unwrapMessage(config2.localeError?.(iss)) ?? "Invalid input"; + full.message = message; + } + delete full.inst; + delete full.continue; + if (!ctx?.reportInput) { + delete full.input; + } + return full; +} +function getSizableOrigin(input) { + if (input instanceof Set) + return "set"; + if (input instanceof Map) + return "map"; + if (input instanceof File) + return "file"; + return "unknown"; +} +function getLengthableOrigin(input) { + if (Array.isArray(input)) + return "array"; + if (typeof input === "string") + return "string"; + return "unknown"; +} +function issue(...args) { + const [iss, input, inst] = args; + if (typeof iss === "string") { + return { + message: iss, + code: "custom", + input, + inst + }; + } + return { ...iss }; +} +function cleanEnum(obj) { + return Object.entries(obj).filter(([k, _]) => { + return Number.isNaN(Number.parseInt(k, 10)); + }).map((el) => el[1]); +} +var captureStackTrace, allowsEval, getParsedType2, propertyKeyTypes, primitiveTypes, NUMBER_FORMAT_RANGES, BIGINT_FORMAT_RANGES, Class; +var init_util2 = __esm({ + "node_modules/zod/v4/core/util.js"() { + captureStackTrace = Error.captureStackTrace ? Error.captureStackTrace : (..._args) => { + }; + allowsEval = cached(() => { + if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) { + return false; + } + try { + const F = Function; + new F(""); + return true; + } catch (_) { + return false; + } + }); + getParsedType2 = (data) => { + const t = typeof data; + switch (t) { + case "undefined": + return "undefined"; + case "string": + return "string"; + case "number": + return Number.isNaN(data) ? "nan" : "number"; + case "boolean": + return "boolean"; + case "function": + return "function"; + case "bigint": + return "bigint"; + case "symbol": + return "symbol"; + case "object": + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { + return "promise"; + } + if (typeof Map !== "undefined" && data instanceof Map) { + return "map"; + } + if (typeof Set !== "undefined" && data instanceof Set) { + return "set"; + } + if (typeof Date !== "undefined" && data instanceof Date) { + return "date"; + } + if (typeof File !== "undefined" && data instanceof File) { + return "file"; + } + return "object"; + default: + throw new Error(`Unknown data type: ${t}`); + } + }; + propertyKeyTypes = /* @__PURE__ */ new Set(["string", "number", "symbol"]); + primitiveTypes = /* @__PURE__ */ new Set(["string", "number", "bigint", "boolean", "symbol", "undefined"]); + NUMBER_FORMAT_RANGES = { + safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], + int32: [-2147483648, 2147483647], + uint32: [0, 4294967295], + float32: [-34028234663852886e22, 34028234663852886e22], + float64: [-Number.MAX_VALUE, Number.MAX_VALUE] + }; + BIGINT_FORMAT_RANGES = { + int64: [/* @__PURE__ */ BigInt("-9223372036854775808"), /* @__PURE__ */ BigInt("9223372036854775807")], + uint64: [/* @__PURE__ */ BigInt(0), /* @__PURE__ */ BigInt("18446744073709551615")] + }; + Class = class { + constructor(..._args) { + } + }; + } +}); + +// node_modules/zod/v4/core/errors.js +var initializer, $ZodError, $ZodRealError; +var init_errors3 = __esm({ + "node_modules/zod/v4/core/errors.js"() { + init_core2(); + init_util2(); + initializer = (inst, def) => { + inst.name = "$ZodError"; + Object.defineProperty(inst, "_zod", { + value: inst._zod, + enumerable: false + }); + Object.defineProperty(inst, "issues", { + value: def, + enumerable: false + }); + Object.defineProperty(inst, "message", { + get() { + return JSON.stringify(def, jsonStringifyReplacer, 2); + }, + enumerable: true + // configurable: false, + }); + Object.defineProperty(inst, "toString", { + value: () => inst.message, + enumerable: false + }); + }; + $ZodError = $constructor("$ZodError", initializer); + $ZodRealError = $constructor("$ZodError", initializer, { Parent: Error }); + } +}); + +// node_modules/zod/v4/core/parse.js +var _parse, parse2, _parseAsync, parseAsync, _safeParse, safeParse, _safeParseAsync, safeParseAsync; +var init_parse2 = __esm({ + "node_modules/zod/v4/core/parse.js"() { + init_core2(); + init_errors3(); + init_util2(); + _parse = (_Err) => (schema, value, _ctx, _params) => { + const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false }; + const result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) { + throw new $ZodAsyncError(); + } + if (result.issues.length) { + const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); + captureStackTrace(e, _params?.callee); + throw e; + } + return result.value; + }; + parse2 = /* @__PURE__ */ _parse($ZodRealError); + _parseAsync = (_Err) => async (schema, value, _ctx, params) => { + const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + if (result.issues.length) { + const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); + captureStackTrace(e, params?.callee); + throw e; + } + return result.value; + }; + parseAsync = /* @__PURE__ */ _parseAsync($ZodRealError); + _safeParse = (_Err) => (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; + const result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) { + throw new $ZodAsyncError(); + } + return result.issues.length ? { + success: false, + error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) + } : { success: true, data: result.value }; + }; + safeParse = /* @__PURE__ */ _safeParse($ZodRealError); + _safeParseAsync = (_Err) => async (schema, value, _ctx) => { + const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + return result.issues.length ? { + success: false, + error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) + } : { success: true, data: result.value }; + }; + safeParseAsync = /* @__PURE__ */ _safeParseAsync($ZodRealError); + } +}); + +// node_modules/zod/v4/core/regexes.js +var dateSource, date; +var init_regexes = __esm({ + "node_modules/zod/v4/core/regexes.js"() { + dateSource = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`; + date = /* @__PURE__ */ new RegExp(`^${dateSource}$`); + } +}); + +// node_modules/zod/v4/core/checks.js +var init_checks = __esm({ + "node_modules/zod/v4/core/checks.js"() { + } +}); + +// node_modules/zod/v4/core/doc.js +var init_doc = __esm({ + "node_modules/zod/v4/core/doc.js"() { + } +}); + +// node_modules/zod/v4/core/versions.js +var version; +var init_versions = __esm({ + "node_modules/zod/v4/core/versions.js"() { + version = { + major: 4, + minor: 0, + patch: 0 + }; + } +}); + +// node_modules/zod/v4/core/schemas.js +var $ZodType, $ZodUnknown, $ZodNever, $ZodOptional; +var init_schemas = __esm({ + "node_modules/zod/v4/core/schemas.js"() { + init_core2(); + init_parse2(); + init_util2(); + init_versions(); + init_util2(); + $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { + var _a2; + inst ?? (inst = {}); + inst._zod.def = def; + inst._zod.bag = inst._zod.bag || {}; + inst._zod.version = version; + const checks = [...inst._zod.def.checks ?? []]; + if (inst._zod.traits.has("$ZodCheck")) { + checks.unshift(inst); + } + for (const ch of checks) { + for (const fn of ch._zod.onattach) { + fn(inst); + } + } + if (checks.length === 0) { + (_a2 = inst._zod).deferred ?? (_a2.deferred = []); + inst._zod.deferred?.push(() => { + inst._zod.run = inst._zod.parse; + }); + } else { + const runChecks = (payload, checks2, ctx) => { + let isAborted2 = aborted(payload); + let asyncResult; + for (const ch of checks2) { + if (ch._zod.def.when) { + const shouldRun = ch._zod.def.when(payload); + if (!shouldRun) + continue; + } else if (isAborted2) { + continue; + } + const currLen = payload.issues.length; + const _ = ch._zod.check(payload); + if (_ instanceof Promise && ctx?.async === false) { + throw new $ZodAsyncError(); + } + if (asyncResult || _ instanceof Promise) { + asyncResult = (asyncResult ?? Promise.resolve()).then(async () => { + await _; + const nextLen = payload.issues.length; + if (nextLen === currLen) + return; + if (!isAborted2) + isAborted2 = aborted(payload, currLen); + }); + } else { + const nextLen = payload.issues.length; + if (nextLen === currLen) + continue; + if (!isAborted2) + isAborted2 = aborted(payload, currLen); + } + } + if (asyncResult) { + return asyncResult.then(() => { + return payload; + }); + } + return payload; + }; + inst._zod.run = (payload, ctx) => { + const result = inst._zod.parse(payload, ctx); + if (result instanceof Promise) { + if (ctx.async === false) + throw new $ZodAsyncError(); + return result.then((result2) => runChecks(result2, checks, ctx)); + } + return runChecks(result, checks, ctx); + }; + } + inst["~standard"] = { + validate: (value) => { + try { + const r = safeParse(inst, value); + return r.success ? { value: r.data } : { issues: r.error?.issues }; + } catch (_) { + return safeParseAsync(inst, value).then((r) => r.success ? { value: r.data } : { issues: r.error?.issues }); + } + }, + vendor: "zod", + version: 1 + }; + }); + $ZodUnknown = /* @__PURE__ */ $constructor("$ZodUnknown", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload) => payload; + }); + $ZodNever = /* @__PURE__ */ $constructor("$ZodNever", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + payload.issues.push({ + expected: "never", + code: "invalid_type", + input: payload.value, + inst + }); + return payload; + }; + }); + $ZodOptional = /* @__PURE__ */ $constructor("$ZodOptional", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.optin = "optional"; + inst._zod.optout = "optional"; + defineLazy(inst._zod, "values", () => { + return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, void 0]) : void 0; + }); + defineLazy(inst._zod, "pattern", () => { + const pattern = def.innerType._zod.pattern; + return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : void 0; + }); + inst._zod.parse = (payload, ctx) => { + if (def.innerType._zod.optin === "optional") { + return def.innerType._zod.run(payload, ctx); + } + if (payload.value === void 0) { + return payload; + } + return def.innerType._zod.run(payload, ctx); + }; + }); + } +}); + +// node_modules/zod/v4/locales/index.js +var init_locales = __esm({ + "node_modules/zod/v4/locales/index.js"() { + } +}); + +// node_modules/zod/v4/core/registries.js +function registry() { + return new $ZodRegistry(); +} +var $output, $input, $ZodRegistry, globalRegistry; +var init_registries = __esm({ + "node_modules/zod/v4/core/registries.js"() { + $output = Symbol("ZodOutput"); + $input = Symbol("ZodInput"); + $ZodRegistry = class { + constructor() { + this._map = /* @__PURE__ */ new Map(); + this._idmap = /* @__PURE__ */ new Map(); + } + add(schema, ..._meta) { + const meta = _meta[0]; + this._map.set(schema, meta); + if (meta && typeof meta === "object" && "id" in meta) { + if (this._idmap.has(meta.id)) { + throw new Error(`ID ${meta.id} already exists in the registry`); + } + this._idmap.set(meta.id, schema); + } + return this; + } + clear() { + this._map = /* @__PURE__ */ new Map(); + this._idmap = /* @__PURE__ */ new Map(); + return this; + } + remove(schema) { + const meta = this._map.get(schema); + if (meta && typeof meta === "object" && "id" in meta) { + this._idmap.delete(meta.id); + } + this._map.delete(schema); + return this; + } + get(schema) { + const p = schema._zod.parent; + if (p) { + const pm = { ...this.get(p) ?? {} }; + delete pm.id; + return { ...pm, ...this._map.get(schema) }; + } + return this._map.get(schema); + } + has(schema) { + return this._map.has(schema); + } + }; + globalRegistry = /* @__PURE__ */ registry(); + } +}); + +// node_modules/zod/v4/core/api.js +function _unknown(Class2) { + return new Class2({ + type: "unknown" + }); +} +function _never(Class2, params) { + return new Class2({ + type: "never", + ...normalizeParams(params) + }); +} +var init_api = __esm({ + "node_modules/zod/v4/core/api.js"() { + init_util2(); + } +}); + +// node_modules/zod/v4/core/function.js +var init_function2 = __esm({ + "node_modules/zod/v4/core/function.js"() { + } +}); + +// node_modules/zod/v4/core/to-json-schema.js +function toJSONSchema(input, _params) { + if (input instanceof $ZodRegistry) { + const gen2 = new JSONSchemaGenerator(_params); + const defs = {}; + for (const entry of input._idmap.entries()) { + const [_, schema] = entry; + gen2.process(schema); + } + const schemas = {}; + const external = { + registry: input, + uri: _params?.uri, + defs + }; + for (const entry of input._idmap.entries()) { + const [key, schema] = entry; + schemas[key] = gen2.emit(schema, { + ..._params, + external + }); + } + if (Object.keys(defs).length > 0) { + const defsSegment = gen2.target === "draft-2020-12" ? "$defs" : "definitions"; + schemas.__shared = { + [defsSegment]: defs + }; + } + return { schemas }; + } + const gen = new JSONSchemaGenerator(_params); + gen.process(input); + return gen.emit(input, _params); +} +function isTransforming(_schema, _ctx) { + const ctx = _ctx ?? { seen: /* @__PURE__ */ new Set() }; + if (ctx.seen.has(_schema)) + return false; + ctx.seen.add(_schema); + const schema = _schema; + const def = schema._zod.def; + switch (def.type) { + case "string": + case "number": + case "bigint": + case "boolean": + case "date": + case "symbol": + case "undefined": + case "null": + case "any": + case "unknown": + case "never": + case "void": + case "literal": + case "enum": + case "nan": + case "file": + case "template_literal": + return false; + case "array": { + return isTransforming(def.element, ctx); + } + case "object": { + for (const key in def.shape) { + if (isTransforming(def.shape[key], ctx)) + return true; + } + return false; + } + case "union": { + for (const option of def.options) { + if (isTransforming(option, ctx)) + return true; + } + return false; + } + case "intersection": { + return isTransforming(def.left, ctx) || isTransforming(def.right, ctx); + } + case "tuple": { + for (const item of def.items) { + if (isTransforming(item, ctx)) + return true; + } + if (def.rest && isTransforming(def.rest, ctx)) + return true; + return false; + } + case "record": { + return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx); + } + case "map": { + return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx); + } + case "set": { + return isTransforming(def.valueType, ctx); + } + // inner types + case "promise": + case "optional": + case "nonoptional": + case "nullable": + case "readonly": + return isTransforming(def.innerType, ctx); + case "lazy": + return isTransforming(def.getter(), ctx); + case "default": { + return isTransforming(def.innerType, ctx); + } + case "prefault": { + return isTransforming(def.innerType, ctx); + } + case "custom": { + return false; + } + case "transform": { + return true; + } + case "pipe": { + return isTransforming(def.in, ctx) || isTransforming(def.out, ctx); + } + case "success": { + return false; + } + case "catch": { + return false; + } + default: + def; + } + throw new Error(`Unknown schema type: ${def.type}`); +} +var JSONSchemaGenerator; +var init_to_json_schema = __esm({ + "node_modules/zod/v4/core/to-json-schema.js"() { + init_registries(); + init_util2(); + JSONSchemaGenerator = class { + constructor(params) { + this.counter = 0; + this.metadataRegistry = params?.metadata ?? globalRegistry; + this.target = params?.target ?? "draft-2020-12"; + this.unrepresentable = params?.unrepresentable ?? "throw"; + this.override = params?.override ?? (() => { + }); + this.io = params?.io ?? "output"; + this.seen = /* @__PURE__ */ new Map(); + } + process(schema, _params = { path: [], schemaPath: [] }) { + var _a2; + const def = schema._zod.def; + const formatMap = { + guid: "uuid", + url: "uri", + datetime: "date-time", + json_string: "json-string", + regex: "" + // do not set + }; + const seen = this.seen.get(schema); + if (seen) { + seen.count++; + const isCycle = _params.schemaPath.includes(schema); + if (isCycle) { + seen.cycle = _params.path; + } + return seen.schema; + } + const result = { schema: {}, count: 1, cycle: void 0, path: _params.path }; + this.seen.set(schema, result); + const overrideSchema = schema._zod.toJSONSchema?.(); + if (overrideSchema) { + result.schema = overrideSchema; + } else { + const params = { + ..._params, + schemaPath: [..._params.schemaPath, schema], + path: _params.path + }; + const parent = schema._zod.parent; + if (parent) { + result.ref = parent; + this.process(parent, params); + this.seen.get(parent).isParent = true; + } else { + const _json = result.schema; + switch (def.type) { + case "string": { + const json = _json; + json.type = "string"; + const { minimum, maximum, format: format2, patterns, contentEncoding } = schema._zod.bag; + if (typeof minimum === "number") + json.minLength = minimum; + if (typeof maximum === "number") + json.maxLength = maximum; + if (format2) { + json.format = formatMap[format2] ?? format2; + if (json.format === "") + delete json.format; + } + if (contentEncoding) + json.contentEncoding = contentEncoding; + if (patterns && patterns.size > 0) { + const regexes = [...patterns]; + if (regexes.length === 1) + json.pattern = regexes[0].source; + else if (regexes.length > 1) { + result.schema.allOf = [ + ...regexes.map((regex2) => ({ + ...this.target === "draft-7" ? { type: "string" } : {}, + pattern: regex2.source + })) + ]; + } + } + break; + } + case "number": { + const json = _json; + const { minimum, maximum, format: format2, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag; + if (typeof format2 === "string" && format2.includes("int")) + json.type = "integer"; + else + json.type = "number"; + if (typeof exclusiveMinimum === "number") + json.exclusiveMinimum = exclusiveMinimum; + if (typeof minimum === "number") { + json.minimum = minimum; + if (typeof exclusiveMinimum === "number") { + if (exclusiveMinimum >= minimum) + delete json.minimum; + else + delete json.exclusiveMinimum; + } + } + if (typeof exclusiveMaximum === "number") + json.exclusiveMaximum = exclusiveMaximum; + if (typeof maximum === "number") { + json.maximum = maximum; + if (typeof exclusiveMaximum === "number") { + if (exclusiveMaximum <= maximum) + delete json.maximum; + else + delete json.exclusiveMaximum; + } + } + if (typeof multipleOf === "number") + json.multipleOf = multipleOf; + break; + } + case "boolean": { + const json = _json; + json.type = "boolean"; + break; + } + case "bigint": { + if (this.unrepresentable === "throw") { + throw new Error("BigInt cannot be represented in JSON Schema"); + } + break; + } + case "symbol": { + if (this.unrepresentable === "throw") { + throw new Error("Symbols cannot be represented in JSON Schema"); + } + break; + } + case "null": { + _json.type = "null"; + break; + } + case "any": { + break; + } + case "unknown": { + break; + } + case "undefined": { + if (this.unrepresentable === "throw") { + throw new Error("Undefined cannot be represented in JSON Schema"); + } + break; + } + case "void": { + if (this.unrepresentable === "throw") { + throw new Error("Void cannot be represented in JSON Schema"); + } + break; + } + case "never": { + _json.not = {}; + break; + } + case "date": { + if (this.unrepresentable === "throw") { + throw new Error("Date cannot be represented in JSON Schema"); + } + break; + } + case "array": { + const json = _json; + const { minimum, maximum } = schema._zod.bag; + if (typeof minimum === "number") + json.minItems = minimum; + if (typeof maximum === "number") + json.maxItems = maximum; + json.type = "array"; + json.items = this.process(def.element, { ...params, path: [...params.path, "items"] }); + break; + } + case "object": { + const json = _json; + json.type = "object"; + json.properties = {}; + const shape = def.shape; + for (const key in shape) { + json.properties[key] = this.process(shape[key], { + ...params, + path: [...params.path, "properties", key] + }); + } + const allKeys = new Set(Object.keys(shape)); + const requiredKeys = new Set([...allKeys].filter((key) => { + const v = def.shape[key]._zod; + if (this.io === "input") { + return v.optin === void 0; + } else { + return v.optout === void 0; + } + })); + if (requiredKeys.size > 0) { + json.required = Array.from(requiredKeys); + } + if (def.catchall?._zod.def.type === "never") { + json.additionalProperties = false; + } else if (!def.catchall) { + if (this.io === "output") + json.additionalProperties = false; + } else if (def.catchall) { + json.additionalProperties = this.process(def.catchall, { + ...params, + path: [...params.path, "additionalProperties"] + }); + } + break; + } + case "union": { + const json = _json; + json.anyOf = def.options.map((x, i) => this.process(x, { + ...params, + path: [...params.path, "anyOf", i] + })); + break; + } + case "intersection": { + const json = _json; + const a = this.process(def.left, { + ...params, + path: [...params.path, "allOf", 0] + }); + const b = this.process(def.right, { + ...params, + path: [...params.path, "allOf", 1] + }); + const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1; + const allOf = [ + ...isSimpleIntersection(a) ? a.allOf : [a], + ...isSimpleIntersection(b) ? b.allOf : [b] + ]; + json.allOf = allOf; + break; + } + case "tuple": { + const json = _json; + json.type = "array"; + const prefixItems = def.items.map((x, i) => this.process(x, { ...params, path: [...params.path, "prefixItems", i] })); + if (this.target === "draft-2020-12") { + json.prefixItems = prefixItems; + } else { + json.items = prefixItems; + } + if (def.rest) { + const rest = this.process(def.rest, { + ...params, + path: [...params.path, "items"] + }); + if (this.target === "draft-2020-12") { + json.items = rest; + } else { + json.additionalItems = rest; + } + } + if (def.rest) { + json.items = this.process(def.rest, { + ...params, + path: [...params.path, "items"] + }); + } + const { minimum, maximum } = schema._zod.bag; + if (typeof minimum === "number") + json.minItems = minimum; + if (typeof maximum === "number") + json.maxItems = maximum; + break; + } + case "record": { + const json = _json; + json.type = "object"; + json.propertyNames = this.process(def.keyType, { ...params, path: [...params.path, "propertyNames"] }); + json.additionalProperties = this.process(def.valueType, { + ...params, + path: [...params.path, "additionalProperties"] + }); + break; + } + case "map": { + if (this.unrepresentable === "throw") { + throw new Error("Map cannot be represented in JSON Schema"); + } + break; + } + case "set": { + if (this.unrepresentable === "throw") { + throw new Error("Set cannot be represented in JSON Schema"); + } + break; + } + case "enum": { + const json = _json; + const values = getEnumValues(def.entries); + if (values.every((v) => typeof v === "number")) + json.type = "number"; + if (values.every((v) => typeof v === "string")) + json.type = "string"; + json.enum = values; + break; + } + case "literal": { + const json = _json; + const vals = []; + for (const val of def.values) { + if (val === void 0) { + if (this.unrepresentable === "throw") { + throw new Error("Literal `undefined` cannot be represented in JSON Schema"); + } else { + } + } else if (typeof val === "bigint") { + if (this.unrepresentable === "throw") { + throw new Error("BigInt literals cannot be represented in JSON Schema"); + } else { + vals.push(Number(val)); + } + } else { + vals.push(val); + } + } + if (vals.length === 0) { + } else if (vals.length === 1) { + const val = vals[0]; + json.type = val === null ? "null" : typeof val; + json.const = val; + } else { + if (vals.every((v) => typeof v === "number")) + json.type = "number"; + if (vals.every((v) => typeof v === "string")) + json.type = "string"; + if (vals.every((v) => typeof v === "boolean")) + json.type = "string"; + if (vals.every((v) => v === null)) + json.type = "null"; + json.enum = vals; + } + break; + } + case "file": { + const json = _json; + const file = { + type: "string", + format: "binary", + contentEncoding: "binary" + }; + const { minimum, maximum, mime } = schema._zod.bag; + if (minimum !== void 0) + file.minLength = minimum; + if (maximum !== void 0) + file.maxLength = maximum; + if (mime) { + if (mime.length === 1) { + file.contentMediaType = mime[0]; + Object.assign(json, file); + } else { + json.anyOf = mime.map((m) => { + const mFile = { ...file, contentMediaType: m }; + return mFile; + }); + } + } else { + Object.assign(json, file); + } + break; + } + case "transform": { + if (this.unrepresentable === "throw") { + throw new Error("Transforms cannot be represented in JSON Schema"); + } + break; + } + case "nullable": { + const inner = this.process(def.innerType, params); + _json.anyOf = [inner, { type: "null" }]; + break; + } + case "nonoptional": { + this.process(def.innerType, params); + result.ref = def.innerType; + break; + } + case "success": { + const json = _json; + json.type = "boolean"; + break; + } + case "default": { + this.process(def.innerType, params); + result.ref = def.innerType; + _json.default = JSON.parse(JSON.stringify(def.defaultValue)); + break; + } + case "prefault": { + this.process(def.innerType, params); + result.ref = def.innerType; + if (this.io === "input") + _json._prefault = JSON.parse(JSON.stringify(def.defaultValue)); + break; + } + case "catch": { + this.process(def.innerType, params); + result.ref = def.innerType; + let catchValue; + try { + catchValue = def.catchValue(void 0); + } catch { + throw new Error("Dynamic catch values are not supported in JSON Schema"); + } + _json.default = catchValue; + break; + } + case "nan": { + if (this.unrepresentable === "throw") { + throw new Error("NaN cannot be represented in JSON Schema"); + } + break; + } + case "template_literal": { + const json = _json; + const pattern = schema._zod.pattern; + if (!pattern) + throw new Error("Pattern not found in template literal"); + json.type = "string"; + json.pattern = pattern.source; + break; + } + case "pipe": { + const innerType = this.io === "input" ? def.in._zod.def.type === "transform" ? def.out : def.in : def.out; + this.process(innerType, params); + result.ref = innerType; + break; + } + case "readonly": { + this.process(def.innerType, params); + result.ref = def.innerType; + _json.readOnly = true; + break; + } + // passthrough types + case "promise": { + this.process(def.innerType, params); + result.ref = def.innerType; + break; + } + case "optional": { + this.process(def.innerType, params); + result.ref = def.innerType; + break; + } + case "lazy": { + const innerType = schema._zod.innerType; + this.process(innerType, params); + result.ref = innerType; + break; + } + case "custom": { + if (this.unrepresentable === "throw") { + throw new Error("Custom types cannot be represented in JSON Schema"); + } + break; + } + default: { + def; + } + } + } + } + const meta = this.metadataRegistry.get(schema); + if (meta) + Object.assign(result.schema, meta); + if (this.io === "input" && isTransforming(schema)) { + delete result.schema.examples; + delete result.schema.default; + } + if (this.io === "input" && result.schema._prefault) + (_a2 = result.schema).default ?? (_a2.default = result.schema._prefault); + delete result.schema._prefault; + const _result = this.seen.get(schema); + return _result.schema; + } + emit(schema, _params) { + const params = { + cycles: _params?.cycles ?? "ref", + reused: _params?.reused ?? "inline", + // unrepresentable: _params?.unrepresentable ?? "throw", + // uri: _params?.uri ?? ((id) => `${id}`), + external: _params?.external ?? void 0 + }; + const root2 = this.seen.get(schema); + if (!root2) + throw new Error("Unprocessed schema. This is a bug in Zod."); + const makeURI = (entry) => { + const defsSegment = this.target === "draft-2020-12" ? "$defs" : "definitions"; + if (params.external) { + const externalId = params.external.registry.get(entry[0])?.id; + const uriGenerator = params.external.uri ?? ((id2) => id2); + if (externalId) { + return { ref: uriGenerator(externalId) }; + } + const id = entry[1].defId ?? entry[1].schema.id ?? `schema${this.counter++}`; + entry[1].defId = id; + return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` }; + } + if (entry[1] === root2) { + return { ref: "#" }; + } + const uriPrefix = `#`; + const defUriPrefix = `${uriPrefix}/${defsSegment}/`; + const defId = entry[1].schema.id ?? `__schema${this.counter++}`; + return { defId, ref: defUriPrefix + defId }; + }; + const extractToDef = (entry) => { + if (entry[1].schema.$ref) { + return; + } + const seen = entry[1]; + const { ref, defId } = makeURI(entry); + seen.def = { ...seen.schema }; + if (defId) + seen.defId = defId; + const schema2 = seen.schema; + for (const key in schema2) { + delete schema2[key]; + } + schema2.$ref = ref; + }; + if (params.cycles === "throw") { + for (const entry of this.seen.entries()) { + const seen = entry[1]; + if (seen.cycle) { + throw new Error(`Cycle detected: #/${seen.cycle?.join("/")}/ + +Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`); + } + } + } + for (const entry of this.seen.entries()) { + const seen = entry[1]; + if (schema === entry[0]) { + extractToDef(entry); + continue; + } + if (params.external) { + const ext = params.external.registry.get(entry[0])?.id; + if (schema !== entry[0] && ext) { + extractToDef(entry); + continue; + } + } + const id = this.metadataRegistry.get(entry[0])?.id; + if (id) { + extractToDef(entry); + continue; + } + if (seen.cycle) { + extractToDef(entry); + continue; + } + if (seen.count > 1) { + if (params.reused === "ref") { + extractToDef(entry); + continue; + } + } + } + const flattenRef = (zodSchema, params2) => { + const seen = this.seen.get(zodSchema); + const schema2 = seen.def ?? seen.schema; + const _cached = { ...schema2 }; + if (seen.ref === null) { + return; + } + const ref = seen.ref; + seen.ref = null; + if (ref) { + flattenRef(ref, params2); + const refSchema = this.seen.get(ref).schema; + if (refSchema.$ref && params2.target === "draft-7") { + schema2.allOf = schema2.allOf ?? []; + schema2.allOf.push(refSchema); + } else { + Object.assign(schema2, refSchema); + Object.assign(schema2, _cached); + } + } + if (!seen.isParent) + this.override({ + zodSchema, + jsonSchema: schema2, + path: seen.path ?? [] + }); + }; + for (const entry of [...this.seen.entries()].reverse()) { + flattenRef(entry[0], { target: this.target }); + } + const result = {}; + if (this.target === "draft-2020-12") { + result.$schema = "https://json-schema.org/draft/2020-12/schema"; + } else if (this.target === "draft-7") { + result.$schema = "http://json-schema.org/draft-07/schema#"; + } else { + console.warn(`Invalid target: ${this.target}`); + } + if (params.external?.uri) { + const id = params.external.registry.get(schema)?.id; + if (!id) + throw new Error("Schema is missing an `id` property"); + result.$id = params.external.uri(id); + } + Object.assign(result, root2.def); + const defs = params.external?.defs ?? {}; + for (const entry of this.seen.entries()) { + const seen = entry[1]; + if (seen.def && seen.defId) { + defs[seen.defId] = seen.def; + } + } + if (params.external) { + } else { + if (Object.keys(defs).length > 0) { + if (this.target === "draft-2020-12") { + result.$defs = defs; + } else { + result.definitions = defs; + } + } + } + try { + return JSON.parse(JSON.stringify(result)); + } catch (_err) { + throw new Error("Error converting schema to JSON."); + } + } + }; + } +}); + +// node_modules/zod/v4/core/json-schema.js +var init_json_schema = __esm({ + "node_modules/zod/v4/core/json-schema.js"() { + } +}); + +// node_modules/zod/v4/core/index.js +var init_core3 = __esm({ + "node_modules/zod/v4/core/index.js"() { + init_core2(); + init_parse2(); + init_errors3(); + init_schemas(); + init_checks(); + init_versions(); + init_util2(); + init_regexes(); + init_locales(); + init_registries(); + init_doc(); + init_function2(); + init_api(); + init_to_json_schema(); + init_json_schema(); + } +}); + +// node_modules/zod-to-json-schema/dist/esm/Options.js +var ignoreOverride, defaultOptions2, getDefaultOptions; +var init_Options = __esm({ + "node_modules/zod-to-json-schema/dist/esm/Options.js"() { + ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use"); + defaultOptions2 = { + name: void 0, + $refStrategy: "root", + basePath: ["#"], + effectStrategy: "input", + pipeStrategy: "all", + dateStrategy: "format:date-time", + mapStrategy: "entries", + removeAdditionalStrategy: "passthrough", + allowedAdditionalProperties: true, + rejectedAdditionalProperties: false, + definitionPath: "definitions", + target: "jsonSchema7", + strictUnions: false, + definitions: {}, + errorMessages: false, + markdownDescription: false, + patternStrategy: "escape", + applyRegexFlags: false, + emailStrategy: "format:email", + base64Strategy: "contentEncoding:base64", + nameStrategy: "ref", + openAiAnyTypeName: "OpenAiAnyType" + }; + getDefaultOptions = (options) => typeof options === "string" ? { + ...defaultOptions2, + name: options + } : { + ...defaultOptions2, + ...options + }; + } +}); + +// node_modules/zod-to-json-schema/dist/esm/Refs.js +var getRefs; +var init_Refs = __esm({ + "node_modules/zod-to-json-schema/dist/esm/Refs.js"() { + init_Options(); + getRefs = (options) => { + const _options = getDefaultOptions(options); + const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath; + return { + ..._options, + flags: { hasReferencedOpenAiAnyType: false }, + currentPath, + propertyPath: void 0, + seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [ + def._def, + { + def: def._def, + path: [..._options.basePath, _options.definitionPath, name], + // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now. + jsonSchema: void 0 + } + ])) + }; + }; + } +}); + +// node_modules/zod-to-json-schema/dist/esm/errorMessages.js +function addErrorMessage(res, key, errorMessage, refs) { + if (!refs?.errorMessages) + return; + if (errorMessage) { + res.errorMessage = { + ...res.errorMessage, + [key]: errorMessage + }; + } +} +function setResponseValueAndErrors(res, key, value, errorMessage, refs) { + res[key] = value; + addErrorMessage(res, key, errorMessage, refs); +} +var init_errorMessages = __esm({ + "node_modules/zod-to-json-schema/dist/esm/errorMessages.js"() { + } +}); + +// node_modules/zod-to-json-schema/dist/esm/getRelativePath.js +var getRelativePath; +var init_getRelativePath = __esm({ + "node_modules/zod-to-json-schema/dist/esm/getRelativePath.js"() { + getRelativePath = (pathA, pathB) => { + let i = 0; + for (; i < pathA.length && i < pathB.length; i++) { + if (pathA[i] !== pathB[i]) + break; + } + return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/"); + }; + } +}); + +// node_modules/zod/index.js +var init_zod = __esm({ + "node_modules/zod/index.js"() { + init_external(); + init_external(); + } +}); + +// node_modules/zod-to-json-schema/dist/esm/parsers/any.js +function parseAnyDef(refs) { + if (refs.target !== "openAi") { + return {}; + } + const anyDefinitionPath = [ + ...refs.basePath, + refs.definitionPath, + refs.openAiAnyTypeName + ]; + refs.flags.hasReferencedOpenAiAnyType = true; + return { + $ref: refs.$refStrategy === "relative" ? getRelativePath(anyDefinitionPath, refs.currentPath) : anyDefinitionPath.join("/") + }; +} +var init_any = __esm({ + "node_modules/zod-to-json-schema/dist/esm/parsers/any.js"() { + init_getRelativePath(); + } +}); + +// node_modules/zod-to-json-schema/dist/esm/parsers/array.js +function parseArrayDef(def, refs) { + const res = { + type: "array" + }; + if (def.type?._def && def.type?._def?.typeName !== ZodFirstPartyTypeKind.ZodAny) { + res.items = parseDef(def.type._def, { + ...refs, + currentPath: [...refs.currentPath, "items"] + }); + } + if (def.minLength) { + setResponseValueAndErrors(res, "minItems", def.minLength.value, def.minLength.message, refs); + } + if (def.maxLength) { + setResponseValueAndErrors(res, "maxItems", def.maxLength.value, def.maxLength.message, refs); + } + if (def.exactLength) { + setResponseValueAndErrors(res, "minItems", def.exactLength.value, def.exactLength.message, refs); + setResponseValueAndErrors(res, "maxItems", def.exactLength.value, def.exactLength.message, refs); + } + return res; +} +var init_array = __esm({ + "node_modules/zod-to-json-schema/dist/esm/parsers/array.js"() { + init_zod(); + init_errorMessages(); + init_parseDef(); + } +}); + +// node_modules/zod-to-json-schema/dist/esm/parsers/bigint.js +function parseBigintDef(def, refs) { + const res = { + type: "integer", + format: "int64" + }; + if (!def.checks) + return res; + for (const check of def.checks) { + switch (check.kind) { + case "min": + if (refs.target === "jsonSchema7") { + if (check.inclusive) { + setResponseValueAndErrors(res, "minimum", check.value, check.message, refs); + } else { + setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs); + } + } else { + if (!check.inclusive) { + res.exclusiveMinimum = true; + } + setResponseValueAndErrors(res, "minimum", check.value, check.message, refs); + } + break; + case "max": + if (refs.target === "jsonSchema7") { + if (check.inclusive) { + setResponseValueAndErrors(res, "maximum", check.value, check.message, refs); + } else { + setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs); + } + } else { + if (!check.inclusive) { + res.exclusiveMaximum = true; + } + setResponseValueAndErrors(res, "maximum", check.value, check.message, refs); + } + break; + case "multipleOf": + setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs); + break; + } + } + return res; +} +var init_bigint = __esm({ + "node_modules/zod-to-json-schema/dist/esm/parsers/bigint.js"() { + init_errorMessages(); + } +}); + +// node_modules/zod-to-json-schema/dist/esm/parsers/boolean.js +function parseBooleanDef() { + return { + type: "boolean" + }; +} +var init_boolean = __esm({ + "node_modules/zod-to-json-schema/dist/esm/parsers/boolean.js"() { + } +}); + +// node_modules/zod-to-json-schema/dist/esm/parsers/branded.js +function parseBrandedDef(_def, refs) { + return parseDef(_def.type._def, refs); +} +var init_branded = __esm({ + "node_modules/zod-to-json-schema/dist/esm/parsers/branded.js"() { + init_parseDef(); + } +}); + +// node_modules/zod-to-json-schema/dist/esm/parsers/catch.js +var parseCatchDef; +var init_catch = __esm({ + "node_modules/zod-to-json-schema/dist/esm/parsers/catch.js"() { + init_parseDef(); + parseCatchDef = (def, refs) => { + return parseDef(def.innerType._def, refs); + }; + } +}); + +// node_modules/zod-to-json-schema/dist/esm/parsers/date.js +function parseDateDef(def, refs, overrideDateStrategy) { + const strategy = overrideDateStrategy ?? refs.dateStrategy; + if (Array.isArray(strategy)) { + return { + anyOf: strategy.map((item, i) => parseDateDef(def, refs, item)) + }; + } + switch (strategy) { + case "string": + case "format:date-time": + return { + type: "string", + format: "date-time" + }; + case "format:date": + return { + type: "string", + format: "date" + }; + case "integer": + return integerDateParser(def, refs); + } +} +var integerDateParser; +var init_date = __esm({ + "node_modules/zod-to-json-schema/dist/esm/parsers/date.js"() { + init_errorMessages(); + integerDateParser = (def, refs) => { + const res = { + type: "integer", + format: "unix-time" + }; + if (refs.target === "openApi3") { + return res; + } + for (const check of def.checks) { + switch (check.kind) { + case "min": + setResponseValueAndErrors( + res, + "minimum", + check.value, + // This is in milliseconds + check.message, + refs + ); + break; + case "max": + setResponseValueAndErrors( + res, + "maximum", + check.value, + // This is in milliseconds + check.message, + refs + ); + break; + } + } + return res; + }; + } +}); + +// node_modules/zod-to-json-schema/dist/esm/parsers/default.js +function parseDefaultDef(_def, refs) { + return { + ...parseDef(_def.innerType._def, refs), + default: _def.defaultValue() + }; +} +var init_default = __esm({ + "node_modules/zod-to-json-schema/dist/esm/parsers/default.js"() { + init_parseDef(); + } +}); + +// node_modules/zod-to-json-schema/dist/esm/parsers/effects.js +function parseEffectsDef(_def, refs) { + return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : parseAnyDef(refs); +} +var init_effects = __esm({ + "node_modules/zod-to-json-schema/dist/esm/parsers/effects.js"() { + init_parseDef(); + init_any(); + } +}); + +// node_modules/zod-to-json-schema/dist/esm/parsers/enum.js +function parseEnumDef(def) { + return { + type: "string", + enum: Array.from(def.values) + }; +} +var init_enum = __esm({ + "node_modules/zod-to-json-schema/dist/esm/parsers/enum.js"() { + } +}); + +// node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js +function parseIntersectionDef(def, refs) { + const allOf = [ + parseDef(def.left._def, { + ...refs, + currentPath: [...refs.currentPath, "allOf", "0"] + }), + parseDef(def.right._def, { + ...refs, + currentPath: [...refs.currentPath, "allOf", "1"] + }) + ].filter((x) => !!x); + let unevaluatedProperties = refs.target === "jsonSchema2019-09" ? { unevaluatedProperties: false } : void 0; + const mergedAllOf = []; + allOf.forEach((schema) => { + if (isJsonSchema7AllOfType(schema)) { + mergedAllOf.push(...schema.allOf); + if (schema.unevaluatedProperties === void 0) { + unevaluatedProperties = void 0; + } + } else { + let nestedSchema = schema; + if ("additionalProperties" in schema && schema.additionalProperties === false) { + const { additionalProperties, ...rest } = schema; + nestedSchema = rest; + } else { + unevaluatedProperties = void 0; + } + mergedAllOf.push(nestedSchema); + } + }); + return mergedAllOf.length ? { + allOf: mergedAllOf, + ...unevaluatedProperties + } : void 0; +} +var isJsonSchema7AllOfType; +var init_intersection = __esm({ + "node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js"() { + init_parseDef(); + isJsonSchema7AllOfType = (type) => { + if ("type" in type && type.type === "string") + return false; + return "allOf" in type; + }; + } +}); + +// node_modules/zod-to-json-schema/dist/esm/parsers/literal.js +function parseLiteralDef(def, refs) { + const parsedType = typeof def.value; + if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") { + return { + type: Array.isArray(def.value) ? "array" : "object" + }; + } + if (refs.target === "openApi3") { + return { + type: parsedType === "bigint" ? "integer" : parsedType, + enum: [def.value] + }; + } + return { + type: parsedType === "bigint" ? "integer" : parsedType, + const: def.value + }; +} +var init_literal = __esm({ + "node_modules/zod-to-json-schema/dist/esm/parsers/literal.js"() { + } +}); + +// node_modules/zod-to-json-schema/dist/esm/parsers/string.js +function parseStringDef(def, refs) { + const res = { + type: "string" + }; + if (def.checks) { + for (const check of def.checks) { + switch (check.kind) { + case "min": + setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs); + break; + case "max": + setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs); + break; + case "email": + switch (refs.emailStrategy) { + case "format:email": + addFormat(res, "email", check.message, refs); + break; + case "format:idn-email": + addFormat(res, "idn-email", check.message, refs); + break; + case "pattern:zod": + addPattern(res, zodPatterns.email, check.message, refs); + break; + } + break; + case "url": + addFormat(res, "uri", check.message, refs); + break; + case "uuid": + addFormat(res, "uuid", check.message, refs); + break; + case "regex": + addPattern(res, check.regex, check.message, refs); + break; + case "cuid": + addPattern(res, zodPatterns.cuid, check.message, refs); + break; + case "cuid2": + addPattern(res, zodPatterns.cuid2, check.message, refs); + break; + case "startsWith": + addPattern(res, RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`), check.message, refs); + break; + case "endsWith": + addPattern(res, RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`), check.message, refs); + break; + case "datetime": + addFormat(res, "date-time", check.message, refs); + break; + case "date": + addFormat(res, "date", check.message, refs); + break; + case "time": + addFormat(res, "time", check.message, refs); + break; + case "duration": + addFormat(res, "duration", check.message, refs); + break; + case "length": + setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs); + setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs); + break; + case "includes": { + addPattern(res, RegExp(escapeLiteralCheckValue(check.value, refs)), check.message, refs); + break; + } + case "ip": { + if (check.version !== "v6") { + addFormat(res, "ipv4", check.message, refs); + } + if (check.version !== "v4") { + addFormat(res, "ipv6", check.message, refs); + } + break; + } + case "base64url": + addPattern(res, zodPatterns.base64url, check.message, refs); + break; + case "jwt": + addPattern(res, zodPatterns.jwt, check.message, refs); + break; + case "cidr": { + if (check.version !== "v6") { + addPattern(res, zodPatterns.ipv4Cidr, check.message, refs); + } + if (check.version !== "v4") { + addPattern(res, zodPatterns.ipv6Cidr, check.message, refs); + } + break; + } + case "emoji": + addPattern(res, zodPatterns.emoji(), check.message, refs); + break; + case "ulid": { + addPattern(res, zodPatterns.ulid, check.message, refs); + break; + } + case "base64": { + switch (refs.base64Strategy) { + case "format:binary": { + addFormat(res, "binary", check.message, refs); + break; + } + case "contentEncoding:base64": { + setResponseValueAndErrors(res, "contentEncoding", "base64", check.message, refs); + break; + } + case "pattern:zod": { + addPattern(res, zodPatterns.base64, check.message, refs); + break; + } + } + break; + } + case "nanoid": { + addPattern(res, zodPatterns.nanoid, check.message, refs); + } + case "toLowerCase": + case "toUpperCase": + case "trim": + break; + default: + /* @__PURE__ */ ((_) => { + })(check); + } + } + } + return res; +} +function escapeLiteralCheckValue(literal, refs) { + return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal) : literal; +} +function escapeNonAlphaNumeric(source) { + let result = ""; + for (let i = 0; i < source.length; i++) { + if (!ALPHA_NUMERIC.has(source[i])) { + result += "\\"; + } + result += source[i]; + } + return result; +} +function addFormat(schema, value, message, refs) { + if (schema.format || schema.anyOf?.some((x) => x.format)) { + if (!schema.anyOf) { + schema.anyOf = []; + } + if (schema.format) { + schema.anyOf.push({ + format: schema.format, + ...schema.errorMessage && refs.errorMessages && { + errorMessage: { format: schema.errorMessage.format } + } + }); + delete schema.format; + if (schema.errorMessage) { + delete schema.errorMessage.format; + if (Object.keys(schema.errorMessage).length === 0) { + delete schema.errorMessage; + } + } + } + schema.anyOf.push({ + format: value, + ...message && refs.errorMessages && { errorMessage: { format: message } } + }); + } else { + setResponseValueAndErrors(schema, "format", value, message, refs); + } +} +function addPattern(schema, regex2, message, refs) { + if (schema.pattern || schema.allOf?.some((x) => x.pattern)) { + if (!schema.allOf) { + schema.allOf = []; + } + if (schema.pattern) { + schema.allOf.push({ + pattern: schema.pattern, + ...schema.errorMessage && refs.errorMessages && { + errorMessage: { pattern: schema.errorMessage.pattern } + } + }); + delete schema.pattern; + if (schema.errorMessage) { + delete schema.errorMessage.pattern; + if (Object.keys(schema.errorMessage).length === 0) { + delete schema.errorMessage; + } + } + } + schema.allOf.push({ + pattern: stringifyRegExpWithFlags(regex2, refs), + ...message && refs.errorMessages && { errorMessage: { pattern: message } } + }); + } else { + setResponseValueAndErrors(schema, "pattern", stringifyRegExpWithFlags(regex2, refs), message, refs); + } +} +function stringifyRegExpWithFlags(regex2, refs) { + if (!refs.applyRegexFlags || !regex2.flags) { + return regex2.source; + } + const flags = { + i: regex2.flags.includes("i"), + m: regex2.flags.includes("m"), + s: regex2.flags.includes("s") + // `.` matches newlines + }; + const source = flags.i ? regex2.source.toLowerCase() : regex2.source; + let pattern = ""; + let isEscaped = false; + let inCharGroup = false; + let inCharRange = false; + for (let i = 0; i < source.length; i++) { + if (isEscaped) { + pattern += source[i]; + isEscaped = false; + continue; + } + if (flags.i) { + if (inCharGroup) { + if (source[i].match(/[a-z]/)) { + if (inCharRange) { + pattern += source[i]; + pattern += `${source[i - 2]}-${source[i]}`.toUpperCase(); + inCharRange = false; + } else if (source[i + 1] === "-" && source[i + 2]?.match(/[a-z]/)) { + pattern += source[i]; + inCharRange = true; + } else { + pattern += `${source[i]}${source[i].toUpperCase()}`; + } + continue; + } + } else if (source[i].match(/[a-z]/)) { + pattern += `[${source[i]}${source[i].toUpperCase()}]`; + continue; + } + } + if (flags.m) { + if (source[i] === "^") { + pattern += `(^|(?<=[\r +]))`; + continue; + } else if (source[i] === "$") { + pattern += `($|(?=[\r +]))`; + continue; + } + } + if (flags.s && source[i] === ".") { + pattern += inCharGroup ? `${source[i]}\r +` : `[${source[i]}\r +]`; + continue; + } + pattern += source[i]; + if (source[i] === "\\") { + isEscaped = true; + } else if (inCharGroup && source[i] === "]") { + inCharGroup = false; + } else if (!inCharGroup && source[i] === "[") { + inCharGroup = true; + } + } + try { + new RegExp(pattern); + } catch { + console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`); + return regex2.source; + } + return pattern; +} +var emojiRegex2, zodPatterns, ALPHA_NUMERIC; +var init_string = __esm({ + "node_modules/zod-to-json-schema/dist/esm/parsers/string.js"() { + init_errorMessages(); + emojiRegex2 = void 0; + zodPatterns = { + /** + * `c` was changed to `[cC]` to replicate /i flag + */ + cuid: /^[cC][^\s-]{8,}$/, + cuid2: /^[0-9a-z]+$/, + ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/, + /** + * `a-z` was added to replicate /i flag + */ + email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/, + /** + * Constructed a valid Unicode RegExp + * + * Lazily instantiate since this type of regex isn't supported + * in all envs (e.g. React Native). + * + * See: + * https://github.com/colinhacks/zod/issues/2433 + * Fix in Zod: + * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b + */ + emoji: () => { + if (emojiRegex2 === void 0) { + emojiRegex2 = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u"); + } + return emojiRegex2; + }, + /** + * Unused + */ + uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/, + /** + * Unused + */ + ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/, + ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/, + /** + * Unused + */ + ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/, + ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/, + base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/, + base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/, + nanoid: /^[a-zA-Z0-9_-]{21}$/, + jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/ + }; + ALPHA_NUMERIC = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789"); + } +}); + +// node_modules/zod-to-json-schema/dist/esm/parsers/record.js +function parseRecordDef(def, refs) { + if (refs.target === "openAi") { + console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."); + } + if (refs.target === "openApi3" && def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) { + return { + type: "object", + required: def.keyType._def.values, + properties: def.keyType._def.values.reduce((acc, key) => ({ + ...acc, + [key]: parseDef(def.valueType._def, { + ...refs, + currentPath: [...refs.currentPath, "properties", key] + }) ?? parseAnyDef(refs) + }), {}), + additionalProperties: refs.rejectedAdditionalProperties + }; + } + const schema = { + type: "object", + additionalProperties: parseDef(def.valueType._def, { + ...refs, + currentPath: [...refs.currentPath, "additionalProperties"] + }) ?? refs.allowedAdditionalProperties + }; + if (refs.target === "openApi3") { + return schema; + } + if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.checks?.length) { + const { type, ...keyType } = parseStringDef(def.keyType._def, refs); + return { + ...schema, + propertyNames: keyType + }; + } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) { + return { + ...schema, + propertyNames: { + enum: def.keyType._def.values + } + }; + } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.type._def.checks?.length) { + const { type, ...keyType } = parseBrandedDef(def.keyType._def, refs); + return { + ...schema, + propertyNames: keyType + }; + } + return schema; +} +var init_record = __esm({ + "node_modules/zod-to-json-schema/dist/esm/parsers/record.js"() { + init_zod(); + init_parseDef(); + init_string(); + init_branded(); + init_any(); + } +}); + +// node_modules/zod-to-json-schema/dist/esm/parsers/map.js +function parseMapDef(def, refs) { + if (refs.mapStrategy === "record") { + return parseRecordDef(def, refs); + } + const keys = parseDef(def.keyType._def, { + ...refs, + currentPath: [...refs.currentPath, "items", "items", "0"] + }) || parseAnyDef(refs); + const values = parseDef(def.valueType._def, { + ...refs, + currentPath: [...refs.currentPath, "items", "items", "1"] + }) || parseAnyDef(refs); + return { + type: "array", + maxItems: 125, + items: { + type: "array", + items: [keys, values], + minItems: 2, + maxItems: 2 + } + }; +} +var init_map = __esm({ + "node_modules/zod-to-json-schema/dist/esm/parsers/map.js"() { + init_parseDef(); + init_record(); + init_any(); + } +}); + +// node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js +function parseNativeEnumDef(def) { + const object = def.values; + const actualKeys = Object.keys(def.values).filter((key) => { + return typeof object[object[key]] !== "number"; + }); + const actualValues = actualKeys.map((key) => object[key]); + const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values))); + return { + type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"], + enum: actualValues + }; +} +var init_nativeEnum = __esm({ + "node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js"() { + } +}); + +// node_modules/zod-to-json-schema/dist/esm/parsers/never.js +function parseNeverDef(refs) { + return refs.target === "openAi" ? void 0 : { + not: parseAnyDef({ + ...refs, + currentPath: [...refs.currentPath, "not"] + }) + }; +} +var init_never = __esm({ + "node_modules/zod-to-json-schema/dist/esm/parsers/never.js"() { + init_any(); + } +}); + +// node_modules/zod-to-json-schema/dist/esm/parsers/null.js +function parseNullDef(refs) { + return refs.target === "openApi3" ? { + enum: ["null"], + nullable: true + } : { + type: "null" + }; +} +var init_null = __esm({ + "node_modules/zod-to-json-schema/dist/esm/parsers/null.js"() { + } +}); + +// node_modules/zod-to-json-schema/dist/esm/parsers/union.js +function parseUnionDef(def, refs) { + if (refs.target === "openApi3") + return asAnyOf(def, refs); + const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options; + if (options.every((x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length))) { + const types = options.reduce((types2, x) => { + const type = primitiveMappings[x._def.typeName]; + return type && !types2.includes(type) ? [...types2, type] : types2; + }, []); + return { + type: types.length > 1 ? types : types[0] + }; + } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) { + const types = options.reduce((acc, x) => { + const type = typeof x._def.value; + switch (type) { + case "string": + case "number": + case "boolean": + return [...acc, type]; + case "bigint": + return [...acc, "integer"]; + case "object": + if (x._def.value === null) + return [...acc, "null"]; + case "symbol": + case "undefined": + case "function": + default: + return acc; + } + }, []); + if (types.length === options.length) { + const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i); + return { + type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0], + enum: options.reduce((acc, x) => { + return acc.includes(x._def.value) ? acc : [...acc, x._def.value]; + }, []) + }; + } + } else if (options.every((x) => x._def.typeName === "ZodEnum")) { + return { + type: "string", + enum: options.reduce((acc, x) => [ + ...acc, + ...x._def.values.filter((x2) => !acc.includes(x2)) + ], []) + }; + } + return asAnyOf(def, refs); +} +var primitiveMappings, asAnyOf; +var init_union = __esm({ + "node_modules/zod-to-json-schema/dist/esm/parsers/union.js"() { + init_parseDef(); + primitiveMappings = { + ZodString: "string", + ZodNumber: "number", + ZodBigInt: "integer", + ZodBoolean: "boolean", + ZodNull: "null" + }; + asAnyOf = (def, refs) => { + const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x, i) => parseDef(x._def, { + ...refs, + currentPath: [...refs.currentPath, "anyOf", `${i}`] + })).filter((x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0)); + return anyOf.length ? { anyOf } : void 0; + }; + } +}); + +// node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js +function parseNullableDef(def, refs) { + if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(def.innerType._def.typeName) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) { + if (refs.target === "openApi3") { + return { + type: primitiveMappings[def.innerType._def.typeName], + nullable: true + }; + } + return { + type: [ + primitiveMappings[def.innerType._def.typeName], + "null" + ] + }; + } + if (refs.target === "openApi3") { + const base2 = parseDef(def.innerType._def, { + ...refs, + currentPath: [...refs.currentPath] + }); + if (base2 && "$ref" in base2) + return { allOf: [base2], nullable: true }; + return base2 && { ...base2, nullable: true }; + } + const base = parseDef(def.innerType._def, { + ...refs, + currentPath: [...refs.currentPath, "anyOf", "0"] + }); + return base && { anyOf: [base, { type: "null" }] }; +} +var init_nullable = __esm({ + "node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js"() { + init_parseDef(); + init_union(); + } +}); + +// node_modules/zod-to-json-schema/dist/esm/parsers/number.js +function parseNumberDef(def, refs) { + const res = { + type: "number" + }; + if (!def.checks) + return res; + for (const check of def.checks) { + switch (check.kind) { + case "int": + res.type = "integer"; + addErrorMessage(res, "type", check.message, refs); + break; + case "min": + if (refs.target === "jsonSchema7") { + if (check.inclusive) { + setResponseValueAndErrors(res, "minimum", check.value, check.message, refs); + } else { + setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs); + } + } else { + if (!check.inclusive) { + res.exclusiveMinimum = true; + } + setResponseValueAndErrors(res, "minimum", check.value, check.message, refs); + } + break; + case "max": + if (refs.target === "jsonSchema7") { + if (check.inclusive) { + setResponseValueAndErrors(res, "maximum", check.value, check.message, refs); + } else { + setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs); + } + } else { + if (!check.inclusive) { + res.exclusiveMaximum = true; + } + setResponseValueAndErrors(res, "maximum", check.value, check.message, refs); + } + break; + case "multipleOf": + setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs); + break; + } + } + return res; +} +var init_number = __esm({ + "node_modules/zod-to-json-schema/dist/esm/parsers/number.js"() { + init_errorMessages(); + } +}); + +// node_modules/zod-to-json-schema/dist/esm/parsers/object.js +function parseObjectDef(def, refs) { + const forceOptionalIntoNullable = refs.target === "openAi"; + const result = { + type: "object", + properties: {} + }; + const required2 = []; + const shape = def.shape(); + for (const propName in shape) { + let propDef = shape[propName]; + if (propDef === void 0 || propDef._def === void 0) { + continue; + } + let propOptional = safeIsOptional(propDef); + if (propOptional && forceOptionalIntoNullable) { + if (propDef._def.typeName === "ZodOptional") { + propDef = propDef._def.innerType; + } + if (!propDef.isNullable()) { + propDef = propDef.nullable(); + } + propOptional = false; + } + const parsedDef = parseDef(propDef._def, { + ...refs, + currentPath: [...refs.currentPath, "properties", propName], + propertyPath: [...refs.currentPath, "properties", propName] + }); + if (parsedDef === void 0) { + continue; + } + result.properties[propName] = parsedDef; + if (!propOptional) { + required2.push(propName); + } + } + if (required2.length) { + result.required = required2; + } + const additionalProperties = decideAdditionalProperties(def, refs); + if (additionalProperties !== void 0) { + result.additionalProperties = additionalProperties; + } + return result; +} +function decideAdditionalProperties(def, refs) { + if (def.catchall._def.typeName !== "ZodNever") { + return parseDef(def.catchall._def, { + ...refs, + currentPath: [...refs.currentPath, "additionalProperties"] + }); + } + switch (def.unknownKeys) { + case "passthrough": + return refs.allowedAdditionalProperties; + case "strict": + return refs.rejectedAdditionalProperties; + case "strip": + return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties; + } +} +function safeIsOptional(schema) { + try { + return schema.isOptional(); + } catch { + return true; + } +} +var init_object = __esm({ + "node_modules/zod-to-json-schema/dist/esm/parsers/object.js"() { + init_parseDef(); + } +}); + +// node_modules/zod-to-json-schema/dist/esm/parsers/optional.js +var parseOptionalDef; +var init_optional = __esm({ + "node_modules/zod-to-json-schema/dist/esm/parsers/optional.js"() { + init_parseDef(); + init_any(); + parseOptionalDef = (def, refs) => { + if (refs.currentPath.toString() === refs.propertyPath?.toString()) { + return parseDef(def.innerType._def, refs); + } + const innerSchema = parseDef(def.innerType._def, { + ...refs, + currentPath: [...refs.currentPath, "anyOf", "1"] + }); + return innerSchema ? { + anyOf: [ + { + not: parseAnyDef(refs) + }, + innerSchema + ] + } : parseAnyDef(refs); + }; + } +}); + +// node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js +var parsePipelineDef; +var init_pipeline = __esm({ + "node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js"() { + init_parseDef(); + parsePipelineDef = (def, refs) => { + if (refs.pipeStrategy === "input") { + return parseDef(def.in._def, refs); + } else if (refs.pipeStrategy === "output") { + return parseDef(def.out._def, refs); + } + const a = parseDef(def.in._def, { + ...refs, + currentPath: [...refs.currentPath, "allOf", "0"] + }); + const b = parseDef(def.out._def, { + ...refs, + currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"] + }); + return { + allOf: [a, b].filter((x) => x !== void 0) + }; + }; + } +}); + +// node_modules/zod-to-json-schema/dist/esm/parsers/promise.js +function parsePromiseDef(def, refs) { + return parseDef(def.type._def, refs); +} +var init_promise = __esm({ + "node_modules/zod-to-json-schema/dist/esm/parsers/promise.js"() { + init_parseDef(); + } +}); + +// node_modules/zod-to-json-schema/dist/esm/parsers/set.js +function parseSetDef(def, refs) { + const items = parseDef(def.valueType._def, { + ...refs, + currentPath: [...refs.currentPath, "items"] + }); + const schema = { + type: "array", + uniqueItems: true, + items + }; + if (def.minSize) { + setResponseValueAndErrors(schema, "minItems", def.minSize.value, def.minSize.message, refs); + } + if (def.maxSize) { + setResponseValueAndErrors(schema, "maxItems", def.maxSize.value, def.maxSize.message, refs); + } + return schema; +} +var init_set = __esm({ + "node_modules/zod-to-json-schema/dist/esm/parsers/set.js"() { + init_errorMessages(); + init_parseDef(); + } +}); + +// node_modules/zod-to-json-schema/dist/esm/parsers/tuple.js +function parseTupleDef(def, refs) { + if (def.rest) { + return { + type: "array", + minItems: def.items.length, + items: def.items.map((x, i) => parseDef(x._def, { + ...refs, + currentPath: [...refs.currentPath, "items", `${i}`] + })).reduce((acc, x) => x === void 0 ? acc : [...acc, x], []), + additionalItems: parseDef(def.rest._def, { + ...refs, + currentPath: [...refs.currentPath, "additionalItems"] + }) + }; + } else { + return { + type: "array", + minItems: def.items.length, + maxItems: def.items.length, + items: def.items.map((x, i) => parseDef(x._def, { + ...refs, + currentPath: [...refs.currentPath, "items", `${i}`] + })).reduce((acc, x) => x === void 0 ? acc : [...acc, x], []) + }; + } +} +var init_tuple = __esm({ + "node_modules/zod-to-json-schema/dist/esm/parsers/tuple.js"() { + init_parseDef(); + } +}); + +// node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js +function parseUndefinedDef(refs) { + return { + not: parseAnyDef(refs) + }; +} +var init_undefined = __esm({ + "node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js"() { + init_any(); + } +}); + +// node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js +function parseUnknownDef(refs) { + return parseAnyDef(refs); +} +var init_unknown = __esm({ + "node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js"() { + init_any(); + } +}); + +// node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js +var parseReadonlyDef; +var init_readonly = __esm({ + "node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js"() { + init_parseDef(); + parseReadonlyDef = (def, refs) => { + return parseDef(def.innerType._def, refs); + }; + } +}); + +// node_modules/zod-to-json-schema/dist/esm/selectParser.js +var selectParser; +var init_selectParser = __esm({ + "node_modules/zod-to-json-schema/dist/esm/selectParser.js"() { + init_zod(); + init_any(); + init_array(); + init_bigint(); + init_boolean(); + init_branded(); + init_catch(); + init_date(); + init_default(); + init_effects(); + init_enum(); + init_intersection(); + init_literal(); + init_map(); + init_nativeEnum(); + init_never(); + init_null(); + init_nullable(); + init_number(); + init_object(); + init_optional(); + init_pipeline(); + init_promise(); + init_record(); + init_set(); + init_string(); + init_tuple(); + init_undefined(); + init_union(); + init_unknown(); + init_readonly(); + selectParser = (def, typeName, refs) => { + switch (typeName) { + case ZodFirstPartyTypeKind.ZodString: + return parseStringDef(def, refs); + case ZodFirstPartyTypeKind.ZodNumber: + return parseNumberDef(def, refs); + case ZodFirstPartyTypeKind.ZodObject: + return parseObjectDef(def, refs); + case ZodFirstPartyTypeKind.ZodBigInt: + return parseBigintDef(def, refs); + case ZodFirstPartyTypeKind.ZodBoolean: + return parseBooleanDef(); + case ZodFirstPartyTypeKind.ZodDate: + return parseDateDef(def, refs); + case ZodFirstPartyTypeKind.ZodUndefined: + return parseUndefinedDef(refs); + case ZodFirstPartyTypeKind.ZodNull: + return parseNullDef(refs); + case ZodFirstPartyTypeKind.ZodArray: + return parseArrayDef(def, refs); + case ZodFirstPartyTypeKind.ZodUnion: + case ZodFirstPartyTypeKind.ZodDiscriminatedUnion: + return parseUnionDef(def, refs); + case ZodFirstPartyTypeKind.ZodIntersection: + return parseIntersectionDef(def, refs); + case ZodFirstPartyTypeKind.ZodTuple: + return parseTupleDef(def, refs); + case ZodFirstPartyTypeKind.ZodRecord: + return parseRecordDef(def, refs); + case ZodFirstPartyTypeKind.ZodLiteral: + return parseLiteralDef(def, refs); + case ZodFirstPartyTypeKind.ZodEnum: + return parseEnumDef(def); + case ZodFirstPartyTypeKind.ZodNativeEnum: + return parseNativeEnumDef(def); + case ZodFirstPartyTypeKind.ZodNullable: + return parseNullableDef(def, refs); + case ZodFirstPartyTypeKind.ZodOptional: + return parseOptionalDef(def, refs); + case ZodFirstPartyTypeKind.ZodMap: + return parseMapDef(def, refs); + case ZodFirstPartyTypeKind.ZodSet: + return parseSetDef(def, refs); + case ZodFirstPartyTypeKind.ZodLazy: + return () => def.getter()._def; + case ZodFirstPartyTypeKind.ZodPromise: + return parsePromiseDef(def, refs); + case ZodFirstPartyTypeKind.ZodNaN: + case ZodFirstPartyTypeKind.ZodNever: + return parseNeverDef(refs); + case ZodFirstPartyTypeKind.ZodEffects: + return parseEffectsDef(def, refs); + case ZodFirstPartyTypeKind.ZodAny: + return parseAnyDef(refs); + case ZodFirstPartyTypeKind.ZodUnknown: + return parseUnknownDef(refs); + case ZodFirstPartyTypeKind.ZodDefault: + return parseDefaultDef(def, refs); + case ZodFirstPartyTypeKind.ZodBranded: + return parseBrandedDef(def, refs); + case ZodFirstPartyTypeKind.ZodReadonly: + return parseReadonlyDef(def, refs); + case ZodFirstPartyTypeKind.ZodCatch: + return parseCatchDef(def, refs); + case ZodFirstPartyTypeKind.ZodPipeline: + return parsePipelineDef(def, refs); + case ZodFirstPartyTypeKind.ZodFunction: + case ZodFirstPartyTypeKind.ZodVoid: + case ZodFirstPartyTypeKind.ZodSymbol: + return void 0; + default: + return /* @__PURE__ */ ((_) => void 0)(typeName); + } + }; + } +}); + +// node_modules/zod-to-json-schema/dist/esm/parseDef.js +function parseDef(def, refs, forceResolution = false) { + const seenItem = refs.seen.get(def); + if (refs.override) { + const overrideResult = refs.override?.(def, refs, seenItem, forceResolution); + if (overrideResult !== ignoreOverride) { + return overrideResult; + } + } + if (seenItem && !forceResolution) { + const seenSchema = get$ref(seenItem, refs); + if (seenSchema !== void 0) { + return seenSchema; + } + } + const newItem = { def, path: refs.currentPath, jsonSchema: void 0 }; + refs.seen.set(def, newItem); + const jsonSchemaOrGetter = selectParser(def, def.typeName, refs); + const jsonSchema = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter; + if (jsonSchema) { + addMeta(def, refs, jsonSchema); + } + if (refs.postProcess) { + const postProcessResult = refs.postProcess(jsonSchema, def, refs); + newItem.jsonSchema = jsonSchema; + return postProcessResult; + } + newItem.jsonSchema = jsonSchema; + return jsonSchema; +} +var get$ref, addMeta; +var init_parseDef = __esm({ + "node_modules/zod-to-json-schema/dist/esm/parseDef.js"() { + init_Options(); + init_selectParser(); + init_getRelativePath(); + init_any(); + get$ref = (item, refs) => { + switch (refs.$refStrategy) { + case "root": + return { $ref: item.path.join("/") }; + case "relative": + return { $ref: getRelativePath(refs.currentPath, item.path) }; + case "none": + case "seen": { + if (item.path.length < refs.currentPath.length && item.path.every((value, index2) => refs.currentPath[index2] === value)) { + console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`); + return parseAnyDef(refs); + } + return refs.$refStrategy === "seen" ? parseAnyDef(refs) : void 0; + } + } + }; + addMeta = (def, refs, jsonSchema) => { + if (def.description) { + jsonSchema.description = def.description; + if (refs.markdownDescription) { + jsonSchema.markdownDescription = def.description; + } + } + return jsonSchema; + }; + } +}); + +// node_modules/zod-to-json-schema/dist/esm/parseTypes.js +var init_parseTypes = __esm({ + "node_modules/zod-to-json-schema/dist/esm/parseTypes.js"() { + } +}); + +// node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js +var zodToJsonSchema; +var init_zodToJsonSchema = __esm({ + "node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js"() { + init_parseDef(); + init_Refs(); + init_any(); + zodToJsonSchema = (schema, options) => { + const refs = getRefs(options); + let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name2, schema2]) => ({ + ...acc, + [name2]: parseDef(schema2._def, { + ...refs, + currentPath: [...refs.basePath, refs.definitionPath, name2] + }, true) ?? parseAnyDef(refs) + }), {}) : void 0; + const name = typeof options === "string" ? options : options?.nameStrategy === "title" ? void 0 : options?.name; + const main = parseDef(schema._def, name === void 0 ? refs : { + ...refs, + currentPath: [...refs.basePath, refs.definitionPath, name] + }, false) ?? parseAnyDef(refs); + const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0; + if (title !== void 0) { + main.title = title; + } + if (refs.flags.hasReferencedOpenAiAnyType) { + if (!definitions) { + definitions = {}; + } + if (!definitions[refs.openAiAnyTypeName]) { + definitions[refs.openAiAnyTypeName] = { + // Skipping "object" as no properties can be defined and additionalProperties must be "false" + type: ["string", "number", "integer", "boolean", "array", "null"], + items: { + $ref: refs.$refStrategy === "relative" ? "1" : [ + ...refs.basePath, + refs.definitionPath, + refs.openAiAnyTypeName + ].join("/") + } + }; + } + } + const combined = name === void 0 ? definitions ? { + ...main, + [refs.definitionPath]: definitions + } : main : { + $ref: [ + ...refs.$refStrategy === "relative" ? [] : refs.basePath, + refs.definitionPath, + name + ].join("/"), + [refs.definitionPath]: { + ...definitions, + [name]: main + } + }; + if (refs.target === "jsonSchema7") { + combined.$schema = "http://json-schema.org/draft-07/schema#"; + } else if (refs.target === "jsonSchema2019-09" || refs.target === "openAi") { + combined.$schema = "https://json-schema.org/draft/2019-09/schema#"; + } + if (refs.target === "openAi" && ("anyOf" in combined || "oneOf" in combined || "allOf" in combined || "type" in combined && Array.isArray(combined.type))) { + console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."); + } + return combined; + }; + } +}); + +// node_modules/zod-to-json-schema/dist/esm/index.js +var init_esm = __esm({ + "node_modules/zod-to-json-schema/dist/esm/index.js"() { + init_Options(); + init_Refs(); + init_errorMessages(); + init_getRelativePath(); + init_parseDef(); + init_parseTypes(); + init_any(); + init_array(); + init_bigint(); + init_boolean(); + init_branded(); + init_catch(); + init_date(); + init_default(); + init_effects(); + init_enum(); + init_intersection(); + init_literal(); + init_map(); + init_nativeEnum(); + init_never(); + init_null(); + init_nullable(); + init_number(); + init_object(); + init_optional(); + init_pipeline(); + init_promise(); + init_readonly(); + init_record(); + init_set(); + init_string(); + init_tuple(); + init_undefined(); + init_union(); + init_unknown(); + init_selectParser(); + init_zodToJsonSchema(); + init_zodToJsonSchema(); + } +}); + +// node_modules/@cfworker/json-schema/dist/esm/deep-compare-strict.js +function deepCompareStrict(a, b) { + const typeofa = typeof a; + if (typeofa !== typeof b) { + return false; + } + if (Array.isArray(a)) { + if (!Array.isArray(b)) { + return false; + } + const length = a.length; + if (length !== b.length) { + return false; + } + for (let i = 0; i < length; i++) { + if (!deepCompareStrict(a[i], b[i])) { + return false; + } + } + return true; + } + if (typeofa === "object") { + if (!a || !b) { + return a === b; + } + const aKeys = Object.keys(a); + const bKeys = Object.keys(b); + const length = aKeys.length; + if (length !== bKeys.length) { + return false; + } + for (const k of aKeys) { + if (!deepCompareStrict(a[k], b[k])) { + return false; + } + } + return true; + } + return a === b; +} +var init_deep_compare_strict = __esm({ + "node_modules/@cfworker/json-schema/dist/esm/deep-compare-strict.js"() { + } +}); + +// node_modules/@cfworker/json-schema/dist/esm/pointer.js +function encodePointer(p) { + return encodeURI(escapePointer(p)); +} +function escapePointer(p) { + return p.replace(/~/g, "~0").replace(/\//g, "~1"); +} +var init_pointer = __esm({ + "node_modules/@cfworker/json-schema/dist/esm/pointer.js"() { + } +}); + +// node_modules/@cfworker/json-schema/dist/esm/dereference.js +function dereference(schema, lookup3 = /* @__PURE__ */ Object.create(null), baseURI = initialBaseURI, basePointer = "") { + if (schema && typeof schema === "object" && !Array.isArray(schema)) { + const id = schema.$id || schema.id; + if (id) { + const url = new URL(id, baseURI.href); + if (url.hash.length > 1) { + lookup3[url.href] = schema; + } else { + url.hash = ""; + if (basePointer === "") { + baseURI = url; + } else { + dereference(schema, lookup3, baseURI); + } + } + } + } else if (schema !== true && schema !== false) { + return lookup3; + } + const schemaURI = baseURI.href + (basePointer ? "#" + basePointer : ""); + if (lookup3[schemaURI] !== void 0) { + throw new Error(`Duplicate schema URI "${schemaURI}".`); + } + lookup3[schemaURI] = schema; + if (schema === true || schema === false) { + return lookup3; + } + if (schema.__absolute_uri__ === void 0) { + Object.defineProperty(schema, "__absolute_uri__", { + enumerable: false, + value: schemaURI + }); + } + if (schema.$ref && schema.__absolute_ref__ === void 0) { + const url = new URL(schema.$ref, baseURI.href); + url.hash = url.hash; + Object.defineProperty(schema, "__absolute_ref__", { + enumerable: false, + value: url.href + }); + } + if (schema.$recursiveRef && schema.__absolute_recursive_ref__ === void 0) { + const url = new URL(schema.$recursiveRef, baseURI.href); + url.hash = url.hash; + Object.defineProperty(schema, "__absolute_recursive_ref__", { + enumerable: false, + value: url.href + }); + } + if (schema.$anchor) { + const url = new URL("#" + schema.$anchor, baseURI.href); + lookup3[url.href] = schema; + } + for (let key in schema) { + if (ignoredKeyword[key]) { + continue; + } + const keyBase = `${basePointer}/${encodePointer(key)}`; + const subSchema = schema[key]; + if (Array.isArray(subSchema)) { + if (schemaArrayKeyword[key]) { + const length = subSchema.length; + for (let i = 0; i < length; i++) { + dereference(subSchema[i], lookup3, baseURI, `${keyBase}/${i}`); + } + } + } else if (schemaMapKeyword[key]) { + for (let subKey in subSchema) { + dereference(subSchema[subKey], lookup3, baseURI, `${keyBase}/${encodePointer(subKey)}`); + } + } else { + dereference(subSchema, lookup3, baseURI, keyBase); + } + } + return lookup3; +} +var schemaArrayKeyword, schemaMapKeyword, ignoredKeyword, initialBaseURI; +var init_dereference = __esm({ + "node_modules/@cfworker/json-schema/dist/esm/dereference.js"() { + init_pointer(); + schemaArrayKeyword = { + prefixItems: true, + items: true, + allOf: true, + anyOf: true, + oneOf: true + }; + schemaMapKeyword = { + $defs: true, + definitions: true, + properties: true, + patternProperties: true, + dependentSchemas: true + }; + ignoredKeyword = { + id: true, + $id: true, + $ref: true, + $schema: true, + $anchor: true, + $vocabulary: true, + $comment: true, + default: true, + enum: true, + const: true, + required: true, + type: true, + maximum: true, + minimum: true, + exclusiveMaximum: true, + exclusiveMinimum: true, + multipleOf: true, + maxLength: true, + minLength: true, + pattern: true, + format: true, + maxItems: true, + minItems: true, + uniqueItems: true, + maxProperties: true, + minProperties: true + }; + initialBaseURI = typeof self !== "undefined" && self.location && self.location.origin !== "null" ? new URL(self.location.origin + self.location.pathname + location.search) : new URL("https://github.com/cfworker"); + } +}); + +// node_modules/@cfworker/json-schema/dist/esm/format.js +function bind(r) { + return r.test.bind(r); +} +function isLeapYear(year) { + return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); +} +function date2(str) { + const matches = str.match(DATE); + if (!matches) + return false; + const year = +matches[1]; + const month = +matches[2]; + const day = +matches[3]; + return month >= 1 && month <= 12 && day >= 1 && day <= (month == 2 && isLeapYear(year) ? 29 : DAYS[month]); +} +function time(full, str) { + const matches = str.match(TIME); + if (!matches) + return false; + const hour = +matches[1]; + const minute = +matches[2]; + const second = +matches[3]; + const timeZone = !!matches[5]; + return (hour <= 23 && minute <= 59 && second <= 59 || hour == 23 && minute == 59 && second == 60) && (!full || timeZone); +} +function date_time(str) { + const dateTime = str.split(DATE_TIME_SEPARATOR); + return dateTime.length == 2 && date2(dateTime[0]) && time(true, dateTime[1]); +} +function uri(str) { + return NOT_URI_FRAGMENT.test(str) && URI_PATTERN.test(str); +} +function regex(str) { + if (Z_ANCHOR.test(str)) + return false; + try { + new RegExp(str, "u"); + return true; + } catch (e) { + return false; + } +} +var DATE, DAYS, TIME, HOSTNAME, URIREF, URITEMPLATE, URL_, UUID, JSON_POINTER, JSON_POINTER_URI_FRAGMENT, RELATIVE_JSON_POINTER, EMAIL, IPV4, IPV6, DURATION, format, DATE_TIME_SEPARATOR, NOT_URI_FRAGMENT, URI_PATTERN, Z_ANCHOR; +var init_format = __esm({ + "node_modules/@cfworker/json-schema/dist/esm/format.js"() { + DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; + DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; + TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i; + HOSTNAME = /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i; + URIREF = /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; + URITEMPLATE = /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i; + URL_ = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu; + UUID = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i; + JSON_POINTER = /^(?:\/(?:[^~/]|~0|~1)*)*$/; + JSON_POINTER_URI_FRAGMENT = /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i; + RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/; + EMAIL = (input) => { + if (input[0] === '"') + return false; + const [name, host, ...rest] = input.split("@"); + if (!name || !host || rest.length !== 0 || name.length > 64 || host.length > 253) + return false; + if (name[0] === "." || name.endsWith(".") || name.includes("..")) + return false; + if (!/^[a-z0-9.-]+$/i.test(host) || !/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(name)) + return false; + return host.split(".").every((part) => /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(part)); + }; + IPV4 = /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/; + IPV6 = /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i; + DURATION = (input) => input.length > 1 && input.length < 80 && (/^P\d+([.,]\d+)?W$/.test(input) || /^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(input) && /^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(input)); + format = { + date: date2, + time: time.bind(void 0, false), + "date-time": date_time, + duration: DURATION, + uri, + "uri-reference": bind(URIREF), + "uri-template": bind(URITEMPLATE), + url: bind(URL_), + email: EMAIL, + hostname: bind(HOSTNAME), + ipv4: bind(IPV4), + ipv6: bind(IPV6), + regex, + uuid: bind(UUID), + "json-pointer": bind(JSON_POINTER), + "json-pointer-uri-fragment": bind(JSON_POINTER_URI_FRAGMENT), + "relative-json-pointer": bind(RELATIVE_JSON_POINTER) + }; + DATE_TIME_SEPARATOR = /t|\s/i; + NOT_URI_FRAGMENT = /\/|:/; + URI_PATTERN = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; + Z_ANCHOR = /[^\\]\\Z/; + } +}); + +// node_modules/@cfworker/json-schema/dist/esm/types.js +var OutputFormat; +var init_types2 = __esm({ + "node_modules/@cfworker/json-schema/dist/esm/types.js"() { + (function(OutputFormat2) { + OutputFormat2[OutputFormat2["Flag"] = 1] = "Flag"; + OutputFormat2[OutputFormat2["Basic"] = 2] = "Basic"; + OutputFormat2[OutputFormat2["Detailed"] = 4] = "Detailed"; + })(OutputFormat || (OutputFormat = {})); + } +}); + +// node_modules/@cfworker/json-schema/dist/esm/ucs2-length.js +function ucs2length(s) { + let result = 0; + let length = s.length; + let index2 = 0; + let charCode; + while (index2 < length) { + result++; + charCode = s.charCodeAt(index2++); + if (charCode >= 55296 && charCode <= 56319 && index2 < length) { + charCode = s.charCodeAt(index2); + if ((charCode & 64512) == 56320) { + index2++; + } + } + } + return result; +} +var init_ucs2_length = __esm({ + "node_modules/@cfworker/json-schema/dist/esm/ucs2-length.js"() { + } +}); + +// node_modules/@cfworker/json-schema/dist/esm/validate.js +function validate3(instance, schema, draft = "2019-09", lookup3 = dereference(schema), shortCircuit = true, recursiveAnchor = null, instanceLocation = "#", schemaLocation = "#", evaluated = /* @__PURE__ */ Object.create(null)) { + if (schema === true) { + return { valid: true, errors: [] }; + } + if (schema === false) { + return { + valid: false, + errors: [ + { + instanceLocation, + keyword: "false", + keywordLocation: instanceLocation, + error: "False boolean schema." + } + ] + }; + } + const rawInstanceType = typeof instance; + let instanceType; + switch (rawInstanceType) { + case "boolean": + case "number": + case "string": + instanceType = rawInstanceType; + break; + case "object": + if (instance === null) { + instanceType = "null"; + } else if (Array.isArray(instance)) { + instanceType = "array"; + } else { + instanceType = "object"; + } + break; + default: + throw new Error(`Instances of "${rawInstanceType}" type are not supported.`); + } + const { $ref, $recursiveRef, $recursiveAnchor, type: $type, const: $const, enum: $enum, required: $required, not: $not, anyOf: $anyOf, allOf: $allOf, oneOf: $oneOf, if: $if, then: $then, else: $else, format: $format, properties: $properties, patternProperties: $patternProperties, additionalProperties: $additionalProperties, unevaluatedProperties: $unevaluatedProperties, minProperties: $minProperties, maxProperties: $maxProperties, propertyNames: $propertyNames, dependentRequired: $dependentRequired, dependentSchemas: $dependentSchemas, dependencies: $dependencies, prefixItems: $prefixItems, items: $items, additionalItems: $additionalItems, unevaluatedItems: $unevaluatedItems, contains: $contains, minContains: $minContains, maxContains: $maxContains, minItems: $minItems, maxItems: $maxItems, uniqueItems: $uniqueItems, minimum: $minimum, maximum: $maximum, exclusiveMinimum: $exclusiveMinimum, exclusiveMaximum: $exclusiveMaximum, multipleOf: $multipleOf, minLength: $minLength, maxLength: $maxLength, pattern: $pattern, __absolute_ref__, __absolute_recursive_ref__ } = schema; + const errors = []; + if ($recursiveAnchor === true && recursiveAnchor === null) { + recursiveAnchor = schema; + } + if ($recursiveRef === "#") { + const refSchema = recursiveAnchor === null ? lookup3[__absolute_recursive_ref__] : recursiveAnchor; + const keywordLocation = `${schemaLocation}/$recursiveRef`; + const result = validate3(instance, recursiveAnchor === null ? schema : recursiveAnchor, draft, lookup3, shortCircuit, refSchema, instanceLocation, keywordLocation, evaluated); + if (!result.valid) { + errors.push({ + instanceLocation, + keyword: "$recursiveRef", + keywordLocation, + error: "A subschema had errors." + }, ...result.errors); + } + } + if ($ref !== void 0) { + const uri2 = __absolute_ref__ || $ref; + const refSchema = lookup3[uri2]; + if (refSchema === void 0) { + let message = `Unresolved $ref "${$ref}".`; + if (__absolute_ref__ && __absolute_ref__ !== $ref) { + message += ` Absolute URI "${__absolute_ref__}".`; + } + message += ` +Known schemas: +- ${Object.keys(lookup3).join("\n- ")}`; + throw new Error(message); + } + const keywordLocation = `${schemaLocation}/$ref`; + const result = validate3(instance, refSchema, draft, lookup3, shortCircuit, recursiveAnchor, instanceLocation, keywordLocation, evaluated); + if (!result.valid) { + errors.push({ + instanceLocation, + keyword: "$ref", + keywordLocation, + error: "A subschema had errors." + }, ...result.errors); + } + if (draft === "4" || draft === "7") { + return { valid: errors.length === 0, errors }; + } + } + if (Array.isArray($type)) { + let length = $type.length; + let valid = false; + for (let i = 0; i < length; i++) { + if (instanceType === $type[i] || $type[i] === "integer" && instanceType === "number" && instance % 1 === 0 && instance === instance) { + valid = true; + break; + } + } + if (!valid) { + errors.push({ + instanceLocation, + keyword: "type", + keywordLocation: `${schemaLocation}/type`, + error: `Instance type "${instanceType}" is invalid. Expected "${$type.join('", "')}".` + }); + } + } else if ($type === "integer") { + if (instanceType !== "number" || instance % 1 || instance !== instance) { + errors.push({ + instanceLocation, + keyword: "type", + keywordLocation: `${schemaLocation}/type`, + error: `Instance type "${instanceType}" is invalid. Expected "${$type}".` + }); + } + } else if ($type !== void 0 && instanceType !== $type) { + errors.push({ + instanceLocation, + keyword: "type", + keywordLocation: `${schemaLocation}/type`, + error: `Instance type "${instanceType}" is invalid. Expected "${$type}".` + }); + } + if ($const !== void 0) { + if (instanceType === "object" || instanceType === "array") { + if (!deepCompareStrict(instance, $const)) { + errors.push({ + instanceLocation, + keyword: "const", + keywordLocation: `${schemaLocation}/const`, + error: `Instance does not match ${JSON.stringify($const)}.` + }); + } + } else if (instance !== $const) { + errors.push({ + instanceLocation, + keyword: "const", + keywordLocation: `${schemaLocation}/const`, + error: `Instance does not match ${JSON.stringify($const)}.` + }); + } + } + if ($enum !== void 0) { + if (instanceType === "object" || instanceType === "array") { + if (!$enum.some((value) => deepCompareStrict(instance, value))) { + errors.push({ + instanceLocation, + keyword: "enum", + keywordLocation: `${schemaLocation}/enum`, + error: `Instance does not match any of ${JSON.stringify($enum)}.` + }); + } + } else if (!$enum.some((value) => instance === value)) { + errors.push({ + instanceLocation, + keyword: "enum", + keywordLocation: `${schemaLocation}/enum`, + error: `Instance does not match any of ${JSON.stringify($enum)}.` + }); + } + } + if ($not !== void 0) { + const keywordLocation = `${schemaLocation}/not`; + const result = validate3(instance, $not, draft, lookup3, shortCircuit, recursiveAnchor, instanceLocation, keywordLocation); + if (result.valid) { + errors.push({ + instanceLocation, + keyword: "not", + keywordLocation, + error: 'Instance matched "not" schema.' + }); + } + } + let subEvaluateds = []; + if ($anyOf !== void 0) { + const keywordLocation = `${schemaLocation}/anyOf`; + const errorsLength = errors.length; + let anyValid = false; + for (let i = 0; i < $anyOf.length; i++) { + const subSchema = $anyOf[i]; + const subEvaluated = Object.create(evaluated); + const result = validate3(instance, subSchema, draft, lookup3, shortCircuit, $recursiveAnchor === true ? recursiveAnchor : null, instanceLocation, `${keywordLocation}/${i}`, subEvaluated); + errors.push(...result.errors); + anyValid = anyValid || result.valid; + if (result.valid) { + subEvaluateds.push(subEvaluated); + } + } + if (anyValid) { + errors.length = errorsLength; + } else { + errors.splice(errorsLength, 0, { + instanceLocation, + keyword: "anyOf", + keywordLocation, + error: "Instance does not match any subschemas." + }); + } + } + if ($allOf !== void 0) { + const keywordLocation = `${schemaLocation}/allOf`; + const errorsLength = errors.length; + let allValid = true; + for (let i = 0; i < $allOf.length; i++) { + const subSchema = $allOf[i]; + const subEvaluated = Object.create(evaluated); + const result = validate3(instance, subSchema, draft, lookup3, shortCircuit, $recursiveAnchor === true ? recursiveAnchor : null, instanceLocation, `${keywordLocation}/${i}`, subEvaluated); + errors.push(...result.errors); + allValid = allValid && result.valid; + if (result.valid) { + subEvaluateds.push(subEvaluated); + } + } + if (allValid) { + errors.length = errorsLength; + } else { + errors.splice(errorsLength, 0, { + instanceLocation, + keyword: "allOf", + keywordLocation, + error: `Instance does not match every subschema.` + }); + } + } + if ($oneOf !== void 0) { + const keywordLocation = `${schemaLocation}/oneOf`; + const errorsLength = errors.length; + const matches = $oneOf.filter((subSchema, i) => { + const subEvaluated = Object.create(evaluated); + const result = validate3(instance, subSchema, draft, lookup3, shortCircuit, $recursiveAnchor === true ? recursiveAnchor : null, instanceLocation, `${keywordLocation}/${i}`, subEvaluated); + errors.push(...result.errors); + if (result.valid) { + subEvaluateds.push(subEvaluated); + } + return result.valid; + }).length; + if (matches === 1) { + errors.length = errorsLength; + } else { + errors.splice(errorsLength, 0, { + instanceLocation, + keyword: "oneOf", + keywordLocation, + error: `Instance does not match exactly one subschema (${matches} matches).` + }); + } + } + if (instanceType === "object" || instanceType === "array") { + Object.assign(evaluated, ...subEvaluateds); + } + if ($if !== void 0) { + const keywordLocation = `${schemaLocation}/if`; + const conditionResult = validate3(instance, $if, draft, lookup3, shortCircuit, recursiveAnchor, instanceLocation, keywordLocation, evaluated).valid; + if (conditionResult) { + if ($then !== void 0) { + const thenResult = validate3(instance, $then, draft, lookup3, shortCircuit, recursiveAnchor, instanceLocation, `${schemaLocation}/then`, evaluated); + if (!thenResult.valid) { + errors.push({ + instanceLocation, + keyword: "if", + keywordLocation, + error: `Instance does not match "then" schema.` + }, ...thenResult.errors); + } + } + } else if ($else !== void 0) { + const elseResult = validate3(instance, $else, draft, lookup3, shortCircuit, recursiveAnchor, instanceLocation, `${schemaLocation}/else`, evaluated); + if (!elseResult.valid) { + errors.push({ + instanceLocation, + keyword: "if", + keywordLocation, + error: `Instance does not match "else" schema.` + }, ...elseResult.errors); + } + } + } + if (instanceType === "object") { + if ($required !== void 0) { + for (const key of $required) { + if (!(key in instance)) { + errors.push({ + instanceLocation, + keyword: "required", + keywordLocation: `${schemaLocation}/required`, + error: `Instance does not have required property "${key}".` + }); + } + } + } + const keys = Object.keys(instance); + if ($minProperties !== void 0 && keys.length < $minProperties) { + errors.push({ + instanceLocation, + keyword: "minProperties", + keywordLocation: `${schemaLocation}/minProperties`, + error: `Instance does not have at least ${$minProperties} properties.` + }); + } + if ($maxProperties !== void 0 && keys.length > $maxProperties) { + errors.push({ + instanceLocation, + keyword: "maxProperties", + keywordLocation: `${schemaLocation}/maxProperties`, + error: `Instance does not have at least ${$maxProperties} properties.` + }); + } + if ($propertyNames !== void 0) { + const keywordLocation = `${schemaLocation}/propertyNames`; + for (const key in instance) { + const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; + const result = validate3(key, $propertyNames, draft, lookup3, shortCircuit, recursiveAnchor, subInstancePointer, keywordLocation); + if (!result.valid) { + errors.push({ + instanceLocation, + keyword: "propertyNames", + keywordLocation, + error: `Property name "${key}" does not match schema.` + }, ...result.errors); + } + } + } + if ($dependentRequired !== void 0) { + const keywordLocation = `${schemaLocation}/dependantRequired`; + for (const key in $dependentRequired) { + if (key in instance) { + const required2 = $dependentRequired[key]; + for (const dependantKey of required2) { + if (!(dependantKey in instance)) { + errors.push({ + instanceLocation, + keyword: "dependentRequired", + keywordLocation, + error: `Instance has "${key}" but does not have "${dependantKey}".` + }); + } + } + } + } + } + if ($dependentSchemas !== void 0) { + for (const key in $dependentSchemas) { + const keywordLocation = `${schemaLocation}/dependentSchemas`; + if (key in instance) { + const result = validate3(instance, $dependentSchemas[key], draft, lookup3, shortCircuit, recursiveAnchor, instanceLocation, `${keywordLocation}/${encodePointer(key)}`, evaluated); + if (!result.valid) { + errors.push({ + instanceLocation, + keyword: "dependentSchemas", + keywordLocation, + error: `Instance has "${key}" but does not match dependant schema.` + }, ...result.errors); + } + } + } + } + if ($dependencies !== void 0) { + const keywordLocation = `${schemaLocation}/dependencies`; + for (const key in $dependencies) { + if (key in instance) { + const propsOrSchema = $dependencies[key]; + if (Array.isArray(propsOrSchema)) { + for (const dependantKey of propsOrSchema) { + if (!(dependantKey in instance)) { + errors.push({ + instanceLocation, + keyword: "dependencies", + keywordLocation, + error: `Instance has "${key}" but does not have "${dependantKey}".` + }); + } + } + } else { + const result = validate3(instance, propsOrSchema, draft, lookup3, shortCircuit, recursiveAnchor, instanceLocation, `${keywordLocation}/${encodePointer(key)}`); + if (!result.valid) { + errors.push({ + instanceLocation, + keyword: "dependencies", + keywordLocation, + error: `Instance has "${key}" but does not match dependant schema.` + }, ...result.errors); + } + } + } + } + } + const thisEvaluated = /* @__PURE__ */ Object.create(null); + let stop = false; + if ($properties !== void 0) { + const keywordLocation = `${schemaLocation}/properties`; + for (const key in $properties) { + if (!(key in instance)) { + continue; + } + const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; + const result = validate3(instance[key], $properties[key], draft, lookup3, shortCircuit, recursiveAnchor, subInstancePointer, `${keywordLocation}/${encodePointer(key)}`); + if (result.valid) { + evaluated[key] = thisEvaluated[key] = true; + } else { + stop = shortCircuit; + errors.push({ + instanceLocation, + keyword: "properties", + keywordLocation, + error: `Property "${key}" does not match schema.` + }, ...result.errors); + if (stop) + break; + } + } + } + if (!stop && $patternProperties !== void 0) { + const keywordLocation = `${schemaLocation}/patternProperties`; + for (const pattern in $patternProperties) { + const regex2 = new RegExp(pattern, "u"); + const subSchema = $patternProperties[pattern]; + for (const key in instance) { + if (!regex2.test(key)) { + continue; + } + const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; + const result = validate3(instance[key], subSchema, draft, lookup3, shortCircuit, recursiveAnchor, subInstancePointer, `${keywordLocation}/${encodePointer(pattern)}`); + if (result.valid) { + evaluated[key] = thisEvaluated[key] = true; + } else { + stop = shortCircuit; + errors.push({ + instanceLocation, + keyword: "patternProperties", + keywordLocation, + error: `Property "${key}" matches pattern "${pattern}" but does not match associated schema.` + }, ...result.errors); + } + } + } + } + if (!stop && $additionalProperties !== void 0) { + const keywordLocation = `${schemaLocation}/additionalProperties`; + for (const key in instance) { + if (thisEvaluated[key]) { + continue; + } + const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; + const result = validate3(instance[key], $additionalProperties, draft, lookup3, shortCircuit, recursiveAnchor, subInstancePointer, keywordLocation); + if (result.valid) { + evaluated[key] = true; + } else { + stop = shortCircuit; + errors.push({ + instanceLocation, + keyword: "additionalProperties", + keywordLocation, + error: `Property "${key}" does not match additional properties schema.` + }, ...result.errors); + } + } + } else if (!stop && $unevaluatedProperties !== void 0) { + const keywordLocation = `${schemaLocation}/unevaluatedProperties`; + for (const key in instance) { + if (!evaluated[key]) { + const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; + const result = validate3(instance[key], $unevaluatedProperties, draft, lookup3, shortCircuit, recursiveAnchor, subInstancePointer, keywordLocation); + if (result.valid) { + evaluated[key] = true; + } else { + errors.push({ + instanceLocation, + keyword: "unevaluatedProperties", + keywordLocation, + error: `Property "${key}" does not match unevaluated properties schema.` + }, ...result.errors); + } + } + } + } + } else if (instanceType === "array") { + if ($maxItems !== void 0 && instance.length > $maxItems) { + errors.push({ + instanceLocation, + keyword: "maxItems", + keywordLocation: `${schemaLocation}/maxItems`, + error: `Array has too many items (${instance.length} > ${$maxItems}).` + }); + } + if ($minItems !== void 0 && instance.length < $minItems) { + errors.push({ + instanceLocation, + keyword: "minItems", + keywordLocation: `${schemaLocation}/minItems`, + error: `Array has too few items (${instance.length} < ${$minItems}).` + }); + } + const length = instance.length; + let i = 0; + let stop = false; + if ($prefixItems !== void 0) { + const keywordLocation = `${schemaLocation}/prefixItems`; + const length2 = Math.min($prefixItems.length, length); + for (; i < length2; i++) { + const result = validate3(instance[i], $prefixItems[i], draft, lookup3, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, `${keywordLocation}/${i}`); + evaluated[i] = true; + if (!result.valid) { + stop = shortCircuit; + errors.push({ + instanceLocation, + keyword: "prefixItems", + keywordLocation, + error: `Items did not match schema.` + }, ...result.errors); + if (stop) + break; + } + } + } + if ($items !== void 0) { + const keywordLocation = `${schemaLocation}/items`; + if (Array.isArray($items)) { + const length2 = Math.min($items.length, length); + for (; i < length2; i++) { + const result = validate3(instance[i], $items[i], draft, lookup3, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, `${keywordLocation}/${i}`); + evaluated[i] = true; + if (!result.valid) { + stop = shortCircuit; + errors.push({ + instanceLocation, + keyword: "items", + keywordLocation, + error: `Items did not match schema.` + }, ...result.errors); + if (stop) + break; + } + } + } else { + for (; i < length; i++) { + const result = validate3(instance[i], $items, draft, lookup3, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, keywordLocation); + evaluated[i] = true; + if (!result.valid) { + stop = shortCircuit; + errors.push({ + instanceLocation, + keyword: "items", + keywordLocation, + error: `Items did not match schema.` + }, ...result.errors); + if (stop) + break; + } + } + } + if (!stop && $additionalItems !== void 0) { + const keywordLocation2 = `${schemaLocation}/additionalItems`; + for (; i < length; i++) { + const result = validate3(instance[i], $additionalItems, draft, lookup3, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, keywordLocation2); + evaluated[i] = true; + if (!result.valid) { + stop = shortCircuit; + errors.push({ + instanceLocation, + keyword: "additionalItems", + keywordLocation: keywordLocation2, + error: `Items did not match additional items schema.` + }, ...result.errors); + } + } + } + } + if ($contains !== void 0) { + if (length === 0 && $minContains === void 0) { + errors.push({ + instanceLocation, + keyword: "contains", + keywordLocation: `${schemaLocation}/contains`, + error: `Array is empty. It must contain at least one item matching the schema.` + }); + } else if ($minContains !== void 0 && length < $minContains) { + errors.push({ + instanceLocation, + keyword: "minContains", + keywordLocation: `${schemaLocation}/minContains`, + error: `Array has less items (${length}) than minContains (${$minContains}).` + }); + } else { + const keywordLocation = `${schemaLocation}/contains`; + const errorsLength = errors.length; + let contained = 0; + for (let j = 0; j < length; j++) { + const result = validate3(instance[j], $contains, draft, lookup3, shortCircuit, recursiveAnchor, `${instanceLocation}/${j}`, keywordLocation); + if (result.valid) { + evaluated[j] = true; + contained++; + } else { + errors.push(...result.errors); + } + } + if (contained >= ($minContains || 0)) { + errors.length = errorsLength; + } + if ($minContains === void 0 && $maxContains === void 0 && contained === 0) { + errors.splice(errorsLength, 0, { + instanceLocation, + keyword: "contains", + keywordLocation, + error: `Array does not contain item matching schema.` + }); + } else if ($minContains !== void 0 && contained < $minContains) { + errors.push({ + instanceLocation, + keyword: "minContains", + keywordLocation: `${schemaLocation}/minContains`, + error: `Array must contain at least ${$minContains} items matching schema. Only ${contained} items were found.` + }); + } else if ($maxContains !== void 0 && contained > $maxContains) { + errors.push({ + instanceLocation, + keyword: "maxContains", + keywordLocation: `${schemaLocation}/maxContains`, + error: `Array may contain at most ${$maxContains} items matching schema. ${contained} items were found.` + }); + } + } + } + if (!stop && $unevaluatedItems !== void 0) { + const keywordLocation = `${schemaLocation}/unevaluatedItems`; + for (i; i < length; i++) { + if (evaluated[i]) { + continue; + } + const result = validate3(instance[i], $unevaluatedItems, draft, lookup3, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, keywordLocation); + evaluated[i] = true; + if (!result.valid) { + errors.push({ + instanceLocation, + keyword: "unevaluatedItems", + keywordLocation, + error: `Items did not match unevaluated items schema.` + }, ...result.errors); + } + } + } + if ($uniqueItems) { + for (let j = 0; j < length; j++) { + const a = instance[j]; + const ao = typeof a === "object" && a !== null; + for (let k = 0; k < length; k++) { + if (j === k) { + continue; + } + const b = instance[k]; + const bo = typeof b === "object" && b !== null; + if (a === b || ao && bo && deepCompareStrict(a, b)) { + errors.push({ + instanceLocation, + keyword: "uniqueItems", + keywordLocation: `${schemaLocation}/uniqueItems`, + error: `Duplicate items at indexes ${j} and ${k}.` + }); + j = Number.MAX_SAFE_INTEGER; + k = Number.MAX_SAFE_INTEGER; + } + } + } + } + } else if (instanceType === "number") { + if (draft === "4") { + if ($minimum !== void 0 && ($exclusiveMinimum === true && instance <= $minimum || instance < $minimum)) { + errors.push({ + instanceLocation, + keyword: "minimum", + keywordLocation: `${schemaLocation}/minimum`, + error: `${instance} is less than ${$exclusiveMinimum ? "or equal to " : ""} ${$minimum}.` + }); + } + if ($maximum !== void 0 && ($exclusiveMaximum === true && instance >= $maximum || instance > $maximum)) { + errors.push({ + instanceLocation, + keyword: "maximum", + keywordLocation: `${schemaLocation}/maximum`, + error: `${instance} is greater than ${$exclusiveMaximum ? "or equal to " : ""} ${$maximum}.` + }); + } + } else { + if ($minimum !== void 0 && instance < $minimum) { + errors.push({ + instanceLocation, + keyword: "minimum", + keywordLocation: `${schemaLocation}/minimum`, + error: `${instance} is less than ${$minimum}.` + }); + } + if ($maximum !== void 0 && instance > $maximum) { + errors.push({ + instanceLocation, + keyword: "maximum", + keywordLocation: `${schemaLocation}/maximum`, + error: `${instance} is greater than ${$maximum}.` + }); + } + if ($exclusiveMinimum !== void 0 && instance <= $exclusiveMinimum) { + errors.push({ + instanceLocation, + keyword: "exclusiveMinimum", + keywordLocation: `${schemaLocation}/exclusiveMinimum`, + error: `${instance} is less than ${$exclusiveMinimum}.` + }); + } + if ($exclusiveMaximum !== void 0 && instance >= $exclusiveMaximum) { + errors.push({ + instanceLocation, + keyword: "exclusiveMaximum", + keywordLocation: `${schemaLocation}/exclusiveMaximum`, + error: `${instance} is greater than or equal to ${$exclusiveMaximum}.` + }); + } + } + if ($multipleOf !== void 0) { + const remainder = instance % $multipleOf; + if (Math.abs(0 - remainder) >= 11920929e-14 && Math.abs($multipleOf - remainder) >= 11920929e-14) { + errors.push({ + instanceLocation, + keyword: "multipleOf", + keywordLocation: `${schemaLocation}/multipleOf`, + error: `${instance} is not a multiple of ${$multipleOf}.` + }); + } + } + } else if (instanceType === "string") { + const length = $minLength === void 0 && $maxLength === void 0 ? 0 : ucs2length(instance); + if ($minLength !== void 0 && length < $minLength) { + errors.push({ + instanceLocation, + keyword: "minLength", + keywordLocation: `${schemaLocation}/minLength`, + error: `String is too short (${length} < ${$minLength}).` + }); + } + if ($maxLength !== void 0 && length > $maxLength) { + errors.push({ + instanceLocation, + keyword: "maxLength", + keywordLocation: `${schemaLocation}/maxLength`, + error: `String is too long (${length} > ${$maxLength}).` + }); + } + if ($pattern !== void 0 && !new RegExp($pattern, "u").test(instance)) { + errors.push({ + instanceLocation, + keyword: "pattern", + keywordLocation: `${schemaLocation}/pattern`, + error: `String does not match pattern.` + }); + } + if ($format !== void 0 && format[$format] && !format[$format](instance)) { + errors.push({ + instanceLocation, + keyword: "format", + keywordLocation: `${schemaLocation}/format`, + error: `String does not match format "${$format}".` + }); + } + } + return { valid: errors.length === 0, errors }; +} +var init_validate2 = __esm({ + "node_modules/@cfworker/json-schema/dist/esm/validate.js"() { + init_deep_compare_strict(); + init_dereference(); + init_format(); + init_pointer(); + init_ucs2_length(); + } +}); + +// node_modules/@cfworker/json-schema/dist/esm/validator.js +var Validator; +var init_validator = __esm({ + "node_modules/@cfworker/json-schema/dist/esm/validator.js"() { + init_dereference(); + init_validate2(); + Validator = class { + schema; + draft; + shortCircuit; + lookup; + constructor(schema, draft = "2019-09", shortCircuit = true) { + this.schema = schema; + this.draft = draft; + this.shortCircuit = shortCircuit; + this.lookup = dereference(schema); + } + validate(instance) { + return validate3(instance, this.schema, this.draft, this.lookup, this.shortCircuit); + } + addSchema(schema, id) { + if (id) { + schema = { ...schema, $id: id }; + } + dereference(schema, this.lookup); + } + }; + } +}); + +// node_modules/@cfworker/json-schema/dist/esm/index.js +var init_esm2 = __esm({ + "node_modules/@cfworker/json-schema/dist/esm/index.js"() { + init_deep_compare_strict(); + init_dereference(); + init_format(); + init_pointer(); + init_types2(); + init_ucs2_length(); + init_validate2(); + init_validator(); + } +}); + +// node_modules/@langchain/core/dist/utils/types/zod.js +function isZodSchemaV4(schema) { + if (typeof schema !== "object" || schema === null) { + return false; + } + const obj = schema; + if (!("_zod" in obj)) { + return false; + } + const zod = obj._zod; + return typeof zod === "object" && zod !== null && "def" in zod; +} +function isZodSchemaV3(schema) { + if (typeof schema !== "object" || schema === null) { + return false; + } + const obj = schema; + if (!("_def" in obj) || "_zod" in obj) { + return false; + } + const def = obj._def; + return typeof def === "object" && def != null && "typeName" in def; +} +function isZodSchema(schema) { + if (isZodSchemaV4(schema)) { + console.warn("[WARNING] Attempting to use Zod 4 schema in a context where Zod 3 schema is expected. This may cause unexpected behavior."); + } + return isZodSchemaV3(schema); +} +function isInteropZodSchema(input) { + if (!input) { + return false; + } + if (typeof input !== "object") { + return false; + } + if (Array.isArray(input)) { + return false; + } + if (isZodSchemaV4(input) || isZodSchemaV3(input)) { + return true; + } + return false; +} +async function interopSafeParseAsync(schema, input) { + if (isZodSchemaV4(schema)) { + try { + const data = await parseAsync(schema, input); + return { + success: true, + data + }; + } catch (error) { + return { + success: false, + error + }; + } + } + if (isZodSchemaV3(schema)) { + return schema.safeParse(input); + } + throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType"); +} +async function interopParseAsync(schema, input) { + if (isZodSchemaV4(schema)) { + return parse2(schema, input); + } + if (isZodSchemaV3(schema)) { + return schema.parse(input); + } + throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType"); +} +function interopSafeParse(schema, input) { + if (isZodSchemaV4(schema)) { + try { + const data = parse2(schema, input); + return { + success: true, + data + }; + } catch (error) { + return { + success: false, + error + }; + } + } + if (isZodSchemaV3(schema)) { + return schema.safeParse(input); + } + throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType"); +} +function interopParse(schema, input) { + if (isZodSchemaV4(schema)) { + return parse2(schema, input); + } + if (isZodSchemaV3(schema)) { + return schema.parse(input); + } + throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType"); +} +function getSchemaDescription(schema) { + if (isZodSchemaV4(schema)) { + return globalRegistry.get(schema)?.description; + } + if (isZodSchemaV3(schema)) { + return schema.description; + } + if ("description" in schema && typeof schema.description === "string") { + return schema.description; + } + return void 0; +} +function isShapelessZodSchema(schema) { + if (!isInteropZodSchema(schema)) { + return false; + } + if (isZodSchemaV3(schema)) { + const def = schema._def; + if (def.typeName === "ZodObject") { + const obj = schema; + return !obj.shape || Object.keys(obj.shape).length === 0; + } + if (def.typeName === "ZodRecord") { + return true; + } + } + if (isZodSchemaV4(schema)) { + const def = schema._zod.def; + if (def.type === "object") { + const obj = schema; + return !obj.shape || Object.keys(obj.shape).length === 0; + } + if (def.type === "record") { + return true; + } + } + if (typeof schema === "object" && schema !== null && !("shape" in schema)) { + return true; + } + return false; +} +function isSimpleStringZodSchema(schema) { + if (!isInteropZodSchema(schema)) { + return false; + } + if (isZodSchemaV3(schema)) { + const def = schema._def; + return def.typeName === "ZodString"; + } + if (isZodSchemaV4(schema)) { + const def = schema._zod.def; + return def.type === "string"; + } + return false; +} +function isZodObjectV3(obj) { + if (typeof obj === "object" && obj !== null && "_def" in obj && typeof obj._def === "object" && obj._def !== null && "typeName" in obj._def && obj._def.typeName === "ZodObject") { + return true; + } + return false; +} +function isZodObjectV4(obj) { + if (!isZodSchemaV4(obj)) + return false; + if (typeof obj === "object" && obj !== null && "_zod" in obj && typeof obj._zod === "object" && obj._zod !== null && "def" in obj._zod && typeof obj._zod.def === "object" && obj._zod.def !== null && "type" in obj._zod.def && obj._zod.def.type === "object") { + return true; + } + return false; +} +function isZodArrayV4(obj) { + if (!isZodSchemaV4(obj)) + return false; + if (typeof obj === "object" && obj !== null && "_zod" in obj && typeof obj._zod === "object" && obj._zod !== null && "def" in obj._zod && typeof obj._zod.def === "object" && obj._zod.def !== null && "type" in obj._zod.def && obj._zod.def.type === "array") { + return true; + } + return false; +} +function isInteropZodObject(obj) { + if (isZodObjectV3(obj)) + return true; + if (isZodObjectV4(obj)) + return true; + return false; +} +function getInteropZodObjectShape(schema) { + if (isZodSchemaV3(schema)) { + return schema.shape; + } + if (isZodSchemaV4(schema)) { + return schema._zod.def.shape; + } + throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject"); +} +function extendInteropZodObject(schema, extension) { + if (isZodSchemaV3(schema)) { + return schema.extend(extension); + } + if (isZodSchemaV4(schema)) { + return util_exports.extend(schema, extension); + } + throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject"); +} +function interopZodObjectPartial(schema) { + if (isZodSchemaV3(schema)) { + return schema.partial(); + } + if (isZodSchemaV4(schema)) { + return util_exports.partial($ZodOptional, schema, void 0); + } + throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject"); +} +function interopZodObjectStrict(schema, recursive = false) { + if (isZodSchemaV3(schema)) { + return schema.strict(); + } + if (isZodObjectV4(schema)) { + const outputShape = schema._zod.def.shape; + if (recursive) { + for (const [key, keySchema] of Object.entries(schema._zod.def.shape)) { + if (isZodObjectV4(keySchema)) { + const outputSchema = interopZodObjectStrict(keySchema, recursive); + outputShape[key] = outputSchema; + } else if (isZodArrayV4(keySchema)) { + let elementSchema = keySchema._zod.def.element; + if (isZodObjectV4(elementSchema)) { + elementSchema = interopZodObjectStrict(elementSchema, recursive); + } + outputShape[key] = clone(keySchema, { + ...keySchema._zod.def, + element: elementSchema + }); + } else { + outputShape[key] = keySchema; + } + const meta2 = globalRegistry.get(keySchema); + if (meta2) + globalRegistry.add(outputShape[key], meta2); + } + } + const modifiedSchema = clone(schema, { + ...schema._zod.def, + shape: outputShape, + catchall: _never($ZodNever) + }); + const meta = globalRegistry.get(schema); + if (meta) + globalRegistry.add(modifiedSchema, meta); + return modifiedSchema; + } + throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject"); +} +function interopZodObjectPassthrough(schema, recursive = false) { + if (isZodObjectV3(schema)) { + return schema.passthrough(); + } + if (isZodObjectV4(schema)) { + const outputShape = schema._zod.def.shape; + if (recursive) { + for (const [key, keySchema] of Object.entries(schema._zod.def.shape)) { + if (isZodObjectV4(keySchema)) { + const outputSchema = interopZodObjectPassthrough(keySchema, recursive); + outputShape[key] = outputSchema; + } else if (isZodArrayV4(keySchema)) { + let elementSchema = keySchema._zod.def.element; + if (isZodObjectV4(elementSchema)) { + elementSchema = interopZodObjectPassthrough(elementSchema, recursive); + } + outputShape[key] = clone(keySchema, { + ...keySchema._zod.def, + element: elementSchema + }); + } else { + outputShape[key] = keySchema; + } + const meta2 = globalRegistry.get(keySchema); + if (meta2) + globalRegistry.add(outputShape[key], meta2); + } + } + const modifiedSchema = clone(schema, { + ...schema._zod.def, + shape: outputShape, + catchall: _unknown($ZodUnknown) + }); + const meta = globalRegistry.get(schema); + if (meta) + globalRegistry.add(modifiedSchema, meta); + return modifiedSchema; + } + throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject"); +} +function getInteropZodDefaultGetter(schema) { + if (isZodSchemaV3(schema)) { + try { + const defaultValue = schema.parse(void 0); + return () => defaultValue; + } catch { + return void 0; + } + } + if (isZodSchemaV4(schema)) { + try { + const defaultValue = parse2(schema, void 0); + return () => defaultValue; + } catch { + return void 0; + } + } + return void 0; +} +function isZodTransformV3(schema) { + return isZodSchemaV3(schema) && "typeName" in schema._def && schema._def.typeName === "ZodEffects"; +} +function isZodTransformV4(schema) { + return isZodSchemaV4(schema) && schema._zod.def.type === "pipe"; +} +function interopZodTransformInputSchema(schema, recursive = false) { + if (isZodSchemaV3(schema)) { + if (isZodTransformV3(schema)) { + return interopZodTransformInputSchema(schema._def.schema, recursive); + } + return schema; + } + if (isZodSchemaV4(schema)) { + let outputSchema = schema; + if (isZodTransformV4(schema)) { + outputSchema = interopZodTransformInputSchema(schema._zod.def.in, recursive); + } + if (recursive) { + if (isZodObjectV4(outputSchema)) { + const outputShape = outputSchema._zod.def.shape; + for (const [key, keySchema] of Object.entries(outputSchema._zod.def.shape)) { + outputShape[key] = interopZodTransformInputSchema(keySchema, recursive); + } + outputSchema = clone(outputSchema, { + ...outputSchema._zod.def, + shape: outputShape + }); + } else if (isZodArrayV4(outputSchema)) { + const elementSchema = interopZodTransformInputSchema(outputSchema._zod.def.element, recursive); + outputSchema = clone(outputSchema, { + ...outputSchema._zod.def, + element: elementSchema + }); + } + } + const meta = globalRegistry.get(schema); + if (meta) + globalRegistry.add(outputSchema, meta); + return outputSchema; + } + throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType"); +} +var init_zod2 = __esm({ + "node_modules/@langchain/core/dist/utils/types/zod.js"() { + init_core3(); + } +}); + +// node_modules/@langchain/core/dist/utils/json_schema.js +var json_schema_exports2 = {}; +__export(json_schema_exports2, { + Validator: () => Validator, + deepCompareStrict: () => deepCompareStrict, + toJsonSchema: () => toJsonSchema, + validatesOnlyStrings: () => validatesOnlyStrings +}); +function toJsonSchema(schema) { + if (isZodSchemaV4(schema)) { + const inputSchema = interopZodTransformInputSchema(schema, true); + if (isZodObjectV4(inputSchema)) { + const strictSchema = interopZodObjectStrict(inputSchema, true); + return toJSONSchema(strictSchema); + } else { + return toJSONSchema(schema); + } + } + if (isZodSchemaV3(schema)) { + return zodToJsonSchema(schema); + } + return schema; +} +function validatesOnlyStrings(schema) { + if (!schema || typeof schema !== "object" || Object.keys(schema).length === 0 || Array.isArray(schema)) { + return false; + } + if ("type" in schema) { + if (typeof schema.type === "string") { + return schema.type === "string"; + } + if (Array.isArray(schema.type)) { + return schema.type.every((t) => t === "string"); + } + return false; + } + if ("enum" in schema) { + return Array.isArray(schema.enum) && schema.enum.length > 0 && schema.enum.every((val) => typeof val === "string"); + } + if ("const" in schema) { + return typeof schema.const === "string"; + } + if ("allOf" in schema && Array.isArray(schema.allOf)) { + return schema.allOf.some((subschema) => validatesOnlyStrings(subschema)); + } + if ("anyOf" in schema && Array.isArray(schema.anyOf) || "oneOf" in schema && Array.isArray(schema.oneOf)) { + const subschemas = "anyOf" in schema ? schema.anyOf : schema.oneOf; + return subschemas.length > 0 && subschemas.every((subschema) => validatesOnlyStrings(subschema)); + } + if ("not" in schema) { + return false; + } + if ("$ref" in schema && typeof schema.$ref === "string") { + const ref = schema.$ref; + const resolved = dereference(schema); + if (resolved[ref]) { + return validatesOnlyStrings(resolved[ref]); + } + return false; + } + return false; +} +var init_json_schema2 = __esm({ + "node_modules/@langchain/core/dist/utils/json_schema.js"() { + init_core3(); + init_esm(); + init_esm2(); + init_zod2(); + init_esm2(); + } +}); + +// node_modules/@langchain/core/dist/runnables/graph.js +function nodeDataStr(id, data) { + if (id !== void 0 && !validate_default(id)) { + return id; + } else if (isRunnableInterface(data)) { + try { + let dataStr = data.getName(); + dataStr = dataStr.startsWith("Runnable") ? dataStr.slice("Runnable".length) : dataStr; + return dataStr; + } catch (error) { + return data.getName(); + } + } else { + return data.name ?? "UnknownSchema"; + } +} +function nodeDataJson(node) { + if (isRunnableInterface(node.data)) { + return { + type: "runnable", + data: { + id: node.data.lc_id, + name: node.data.getName() + } + }; + } else { + return { + type: "schema", + data: { ...toJsonSchema(node.data.schema), title: node.data.name } + }; + } +} +function _firstNode(graph, exclude = []) { + const targets = new Set(graph.edges.filter((edge) => !exclude.includes(edge.source)).map((edge) => edge.target)); + const found = []; + for (const node of Object.values(graph.nodes)) { + if (!exclude.includes(node.id) && !targets.has(node.id)) { + found.push(node); + } + } + return found.length === 1 ? found[0] : void 0; +} +function _lastNode(graph, exclude = []) { + const sources = new Set(graph.edges.filter((edge) => !exclude.includes(edge.target)).map((edge) => edge.source)); + const found = []; + for (const node of Object.values(graph.nodes)) { + if (!exclude.includes(node.id) && !sources.has(node.id)) { + found.push(node); + } + } + return found.length === 1 ? found[0] : void 0; +} +var Graph; +var init_graph = __esm({ + "node_modules/@langchain/core/dist/runnables/graph.js"() { + init_esm_browser(); + init_utils3(); + init_graph_mermaid(); + init_json_schema2(); + Graph = class _Graph { + constructor(params) { + Object.defineProperty(this, "nodes", { + enumerable: true, + configurable: true, + writable: true, + value: {} + }); + Object.defineProperty(this, "edges", { + enumerable: true, + configurable: true, + writable: true, + value: [] + }); + this.nodes = params?.nodes ?? this.nodes; + this.edges = params?.edges ?? this.edges; + } + // Convert the graph to a JSON-serializable format. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + toJSON() { + const stableNodeIds = {}; + Object.values(this.nodes).forEach((node, i) => { + stableNodeIds[node.id] = validate_default(node.id) ? i : node.id; + }); + return { + nodes: Object.values(this.nodes).map((node) => ({ + id: stableNodeIds[node.id], + ...nodeDataJson(node) + })), + edges: this.edges.map((edge) => { + const item = { + source: stableNodeIds[edge.source], + target: stableNodeIds[edge.target] + }; + if (typeof edge.data !== "undefined") { + item.data = edge.data; + } + if (typeof edge.conditional !== "undefined") { + item.conditional = edge.conditional; + } + return item; + }) + }; + } + addNode(data, id, metadata) { + if (id !== void 0 && this.nodes[id] !== void 0) { + throw new Error(`Node with id ${id} already exists`); + } + const nodeId = id ?? v4_default(); + const node = { + id: nodeId, + data, + name: nodeDataStr(id, data), + metadata + }; + this.nodes[nodeId] = node; + return node; + } + removeNode(node) { + delete this.nodes[node.id]; + this.edges = this.edges.filter((edge) => edge.source !== node.id && edge.target !== node.id); + } + addEdge(source, target, data, conditional) { + if (this.nodes[source.id] === void 0) { + throw new Error(`Source node ${source.id} not in graph`); + } + if (this.nodes[target.id] === void 0) { + throw new Error(`Target node ${target.id} not in graph`); + } + const edge = { + source: source.id, + target: target.id, + data, + conditional + }; + this.edges.push(edge); + return edge; + } + firstNode() { + return _firstNode(this); + } + lastNode() { + return _lastNode(this); + } + /** + * Add all nodes and edges from another graph. + * Note this doesn't check for duplicates, nor does it connect the graphs. + */ + extend(graph, prefix = "") { + let finalPrefix = prefix; + const nodeIds = Object.values(graph.nodes).map((node) => node.id); + if (nodeIds.every(validate_default)) { + finalPrefix = ""; + } + const prefixed = (id) => { + return finalPrefix ? `${finalPrefix}:${id}` : id; + }; + Object.entries(graph.nodes).forEach(([key, value]) => { + this.nodes[prefixed(key)] = { ...value, id: prefixed(key) }; + }); + const newEdges = graph.edges.map((edge) => { + return { + ...edge, + source: prefixed(edge.source), + target: prefixed(edge.target) + }; + }); + this.edges = [...this.edges, ...newEdges]; + const first = graph.firstNode(); + const last2 = graph.lastNode(); + return [ + first ? { id: prefixed(first.id), data: first.data } : void 0, + last2 ? { id: prefixed(last2.id), data: last2.data } : void 0 + ]; + } + trimFirstNode() { + const firstNode = this.firstNode(); + if (firstNode && _firstNode(this, [firstNode.id])) { + this.removeNode(firstNode); + } + } + trimLastNode() { + const lastNode = this.lastNode(); + if (lastNode && _lastNode(this, [lastNode.id])) { + this.removeNode(lastNode); + } + } + /** + * Return a new graph with all nodes re-identified, + * using their unique, readable names where possible. + */ + reid() { + const nodeLabels = Object.fromEntries(Object.values(this.nodes).map((node) => [node.id, node.name])); + const nodeLabelCounts = /* @__PURE__ */ new Map(); + Object.values(nodeLabels).forEach((label) => { + nodeLabelCounts.set(label, (nodeLabelCounts.get(label) || 0) + 1); + }); + const getNodeId = (nodeId) => { + const label = nodeLabels[nodeId]; + if (validate_default(nodeId) && nodeLabelCounts.get(label) === 1) { + return label; + } else { + return nodeId; + } + }; + return new _Graph({ + nodes: Object.fromEntries(Object.entries(this.nodes).map(([id, node]) => [ + getNodeId(id), + { ...node, id: getNodeId(id) } + ])), + edges: this.edges.map((edge) => ({ + ...edge, + source: getNodeId(edge.source), + target: getNodeId(edge.target) + })) + }); + } + drawMermaid(params) { + const { withStyles, curveStyle, nodeColors = { + default: "fill:#f2f0ff,line-height:1.2", + first: "fill-opacity:0", + last: "fill:#bfb6fc" + }, wrapLabelNWords } = params ?? {}; + const graph = this.reid(); + const firstNode = graph.firstNode(); + const lastNode = graph.lastNode(); + return drawMermaid(graph.nodes, graph.edges, { + firstNode: firstNode?.id, + lastNode: lastNode?.id, + withStyles, + curveStyle, + nodeColors, + wrapLabelNWords + }); + } + async drawMermaidPng(params) { + const mermaidSyntax = this.drawMermaid(params); + return drawMermaidPng(mermaidSyntax, { + backgroundColor: params?.backgroundColor + }); + } + }; + } +}); + +// node_modules/@langchain/core/dist/runnables/wrappers.js +function convertToHttpEventStream(stream) { + const encoder2 = new TextEncoder(); + const finalStream = new ReadableStream({ + async start(controller) { + for await (const chunk of stream) { + controller.enqueue(encoder2.encode(`event: data +data: ${JSON.stringify(chunk)} + +`)); + } + controller.enqueue(encoder2.encode("event: end\n\n")); + controller.close(); + } + }); + return IterableReadableStream.fromReadableStream(finalStream); +} +var init_wrappers = __esm({ + "node_modules/@langchain/core/dist/runnables/wrappers.js"() { + init_stream(); + } +}); + +// node_modules/@langchain/core/dist/runnables/iter.js +function isIterableIterator(thing) { + return typeof thing === "object" && thing !== null && typeof thing[Symbol.iterator] === "function" && // avoid detecting array/set as iterator + typeof thing.next === "function"; +} +function isAsyncIterable(thing) { + return typeof thing === "object" && thing !== null && typeof thing[Symbol.asyncIterator] === "function"; +} +function* consumeIteratorInContext(context, iter) { + while (true) { + const { value, done } = AsyncLocalStorageProviderSingleton2.runWithConfig(pickRunnableConfigKeys(context), iter.next.bind(iter), true); + if (done) { + break; + } else { + yield value; + } + } +} +async function* consumeAsyncIterableInContext(context, iter) { + const iterator = iter[Symbol.asyncIterator](); + while (true) { + const { value, done } = await AsyncLocalStorageProviderSingleton2.runWithConfig(pickRunnableConfigKeys(context), iterator.next.bind(iter), true); + if (done) { + break; + } else { + yield value; + } + } +} +var isIterator; +var init_iter = __esm({ + "node_modules/@langchain/core/dist/runnables/iter.js"() { + init_singletons(); + init_config(); + isIterator = (x) => x != null && typeof x === "object" && "next" in x && typeof x.next === "function"; + } +}); + +// node_modules/@langchain/core/dist/runnables/base.js +function _coerceToDict3(value, defaultKey) { + return value && !Array.isArray(value) && // eslint-disable-next-line no-instanceof/no-instanceof + !(value instanceof Date) && typeof value === "object" ? value : { [defaultKey]: value }; +} +function assertNonTraceableFunction(func) { + if (isTraceableFunction(func)) { + throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen."); + } +} +function _coerceToRunnable(coerceable) { + if (typeof coerceable === "function") { + return new RunnableLambda({ func: coerceable }); + } else if (Runnable.isRunnable(coerceable)) { + return coerceable; + } else if (!Array.isArray(coerceable) && typeof coerceable === "object") { + const runnables = {}; + for (const [key, value] of Object.entries(coerceable)) { + runnables[key] = _coerceToRunnable(value); + } + return new RunnableMap({ + steps: runnables + }); + } else { + throw new Error(`Expected a Runnable, function or object. +Instead got an unsupported type.`); + } +} +function convertRunnableToTool(runnable, fields) { + const name = fields.name ?? runnable.getName(); + const description = fields.description ?? getSchemaDescription(fields.schema); + if (isSimpleStringZodSchema(fields.schema)) { + return new RunnableToolLike({ + name, + description, + schema: external_exports.object({ input: external_exports.string() }).transform((input) => input.input), + bound: runnable + }); + } + return new RunnableToolLike({ + name, + description, + schema: fields.schema, + bound: runnable + }); +} +var import_p_retry3, Runnable, RunnableBinding, RunnableEach, RunnableRetry, RunnableSequence, RunnableMap, RunnableTraceable, RunnableLambda, RunnableParallel, RunnableWithFallbacks, RunnableAssign, RunnablePick, RunnableToolLike; +var init_base4 = __esm({ + "node_modules/@langchain/core/dist/runnables/base.js"() { + init_v3(); + import_p_retry3 = __toESM(require_p_retry(), 1); + init_esm_browser(); + init_traceable2(); + init_log_stream(); + init_event_stream(); + init_serializable(); + init_stream(); + init_signal(); + init_config(); + init_async_caller2(); + init_root_listener(); + init_utils3(); + init_singletons(); + init_graph(); + init_wrappers(); + init_iter(); + init_utils(); + init_zod2(); + Runnable = class extends Serializable { + constructor() { + super(...arguments); + Object.defineProperty(this, "lc_runnable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + } + getName(suffix) { + const name = ( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + this.name ?? this.constructor.lc_name() ?? this.constructor.name + ); + return suffix ? `${name}${suffix}` : name; + } + /** + * Bind arguments to a Runnable, returning a new Runnable. + * @param kwargs + * @returns A new RunnableBinding that, when invoked, will apply the bound args. + * + * @deprecated Use {@link withConfig} instead. This will be removed in the next breaking release. + */ + bind(kwargs) { + return new RunnableBinding({ bound: this, kwargs, config: {} }); + } + /** + * Return a new Runnable that maps a list of inputs to a list of outputs, + * by calling invoke() with each input. + * + * @deprecated This will be removed in the next breaking release. + */ + map() { + return new RunnableEach({ bound: this }); + } + /** + * Add retry logic to an existing runnable. + * @param fields.stopAfterAttempt The number of attempts to retry. + * @param fields.onFailedAttempt A function that is called when a retry fails. + * @returns A new RunnableRetry that, when invoked, will retry according to the parameters. + */ + withRetry(fields) { + return new RunnableRetry({ + bound: this, + kwargs: {}, + config: {}, + maxAttemptNumber: fields?.stopAfterAttempt, + ...fields + }); + } + /** + * Bind config to a Runnable, returning a new Runnable. + * @param config New configuration parameters to attach to the new runnable. + * @returns A new RunnableBinding with a config matching what's passed. + */ + withConfig(config2) { + return new RunnableBinding({ + bound: this, + config: config2, + kwargs: {} + }); + } + /** + * Create a new runnable from the current one that will try invoking + * other passed fallback runnables if the initial invocation fails. + * @param fields.fallbacks Other runnables to call if the runnable errors. + * @returns A new RunnableWithFallbacks. + */ + withFallbacks(fields) { + const fallbacks = Array.isArray(fields) ? fields : fields.fallbacks; + return new RunnableWithFallbacks({ + runnable: this, + fallbacks + }); + } + _getOptionsList(options, length = 0) { + if (Array.isArray(options) && options.length !== length) { + throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${options.length} options for ${length} inputs`); + } + if (Array.isArray(options)) { + return options.map(ensureConfig); + } + if (length > 1 && !Array.isArray(options) && options.runId) { + console.warn("Provided runId will be used only for the first element of the batch."); + const subsequent = Object.fromEntries(Object.entries(options).filter(([key]) => key !== "runId")); + return Array.from({ length }, (_, i) => ensureConfig(i === 0 ? options : subsequent)); + } + return Array.from({ length }, () => ensureConfig(options)); + } + async batch(inputs, options, batchOptions) { + const configList = this._getOptionsList(options ?? {}, inputs.length); + const maxConcurrency = configList[0]?.maxConcurrency ?? batchOptions?.maxConcurrency; + const caller2 = new AsyncCaller2({ + maxConcurrency, + onFailedAttempt: (e) => { + throw e; + } + }); + const batchCalls = inputs.map((input, i) => caller2.call(async () => { + try { + const result = await this.invoke(input, configList[i]); + return result; + } catch (e) { + if (batchOptions?.returnExceptions) { + return e; + } + throw e; + } + })); + return Promise.all(batchCalls); + } + /** + * Default streaming implementation. + * Subclasses should override this method if they support streaming output. + * @param input + * @param options + */ + async *_streamIterator(input, options) { + yield this.invoke(input, options); + } + /** + * Stream output in chunks. + * @param input + * @param options + * @returns A readable stream that is also an iterable. + */ + async stream(input, options) { + const config2 = ensureConfig(options); + const wrappedGenerator = new AsyncGeneratorWithSetup({ + generator: this._streamIterator(input, config2), + config: config2 + }); + await wrappedGenerator.setup; + return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); + } + _separateRunnableConfigFromCallOptions(options) { + let runnableConfig; + if (options === void 0) { + runnableConfig = ensureConfig(options); + } else { + runnableConfig = ensureConfig({ + callbacks: options.callbacks, + tags: options.tags, + metadata: options.metadata, + runName: options.runName, + configurable: options.configurable, + recursionLimit: options.recursionLimit, + maxConcurrency: options.maxConcurrency, + runId: options.runId, + timeout: options.timeout, + signal: options.signal + }); + } + const callOptions = { ...options }; + delete callOptions.callbacks; + delete callOptions.tags; + delete callOptions.metadata; + delete callOptions.runName; + delete callOptions.configurable; + delete callOptions.recursionLimit; + delete callOptions.maxConcurrency; + delete callOptions.runId; + delete callOptions.timeout; + delete callOptions.signal; + return [runnableConfig, callOptions]; + } + async _callWithConfig(func, input, options) { + const config2 = ensureConfig(options); + const callbackManager_ = await getCallbackManagerForConfig(config2); + const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict3(input, "input"), config2.runId, config2?.runType, void 0, void 0, config2?.runName ?? this.getName()); + delete config2.runId; + let output; + try { + const promise = func.call(this, input, config2, runManager); + output = await raceWithSignal(promise, options?.signal); + } catch (e) { + await runManager?.handleChainError(e); + throw e; + } + await runManager?.handleChainEnd(_coerceToDict3(output, "output")); + return output; + } + /** + * Internal method that handles batching and configuration for a runnable + * It takes a function, input values, and optional configuration, and + * returns a promise that resolves to the output values. + * @param func The function to be executed for each input value. + * @param input The input values to be processed. + * @param config Optional configuration for the function execution. + * @returns A promise that resolves to the output values. + */ + async _batchWithConfig(func, inputs, options, batchOptions) { + const optionsList = this._getOptionsList(options ?? {}, inputs.length); + const callbackManagers = await Promise.all(optionsList.map(getCallbackManagerForConfig)); + const runManagers = await Promise.all(callbackManagers.map(async (callbackManager, i) => { + const handleStartRes = await callbackManager?.handleChainStart(this.toJSON(), _coerceToDict3(inputs[i], "input"), optionsList[i].runId, optionsList[i].runType, void 0, void 0, optionsList[i].runName ?? this.getName()); + delete optionsList[i].runId; + return handleStartRes; + })); + let outputs; + try { + const promise = func.call(this, inputs, optionsList, runManagers, batchOptions); + outputs = await raceWithSignal(promise, optionsList?.[0]?.signal); + } catch (e) { + await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(e))); + throw e; + } + await Promise.all(runManagers.map((runManager) => runManager?.handleChainEnd(_coerceToDict3(outputs, "output")))); + return outputs; + } + /** @internal */ + _concatOutputChunks(first, second) { + return concat(first, second); + } + /** + * Helper method to transform an Iterator of Input values into an Iterator of + * Output values, with callbacks. + * Use this to implement `stream()` or `transform()` in Runnable subclasses. + */ + async *_transformStreamWithConfig(inputGenerator, transformer, options) { + let finalInput; + let finalInputSupported = true; + let finalOutput; + let finalOutputSupported = true; + const config2 = ensureConfig(options); + const callbackManager_ = await getCallbackManagerForConfig(config2); + const outerThis = this; + async function* wrapInputForTracing() { + for await (const chunk of inputGenerator) { + if (finalInputSupported) { + if (finalInput === void 0) { + finalInput = chunk; + } else { + try { + finalInput = outerThis._concatOutputChunks( + finalInput, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + chunk + ); + } catch { + finalInput = void 0; + finalInputSupported = false; + } + } + } + yield chunk; + } + } + let runManager; + try { + const pipe = await pipeGeneratorWithSetup(transformer.bind(this), wrapInputForTracing(), async () => callbackManager_?.handleChainStart(this.toJSON(), { input: "" }, config2.runId, config2.runType, void 0, void 0, config2.runName ?? this.getName()), options?.signal, config2); + delete config2.runId; + runManager = pipe.setup; + const streamEventsHandler = runManager?.handlers.find(isStreamEventsHandler); + let iterator = pipe.output; + if (streamEventsHandler !== void 0 && runManager !== void 0) { + iterator = streamEventsHandler.tapOutputIterable(runManager.runId, iterator); + } + const streamLogHandler = runManager?.handlers.find(isLogStreamHandler); + if (streamLogHandler !== void 0 && runManager !== void 0) { + iterator = streamLogHandler.tapOutputIterable(runManager.runId, iterator); + } + for await (const chunk of iterator) { + yield chunk; + if (finalOutputSupported) { + if (finalOutput === void 0) { + finalOutput = chunk; + } else { + try { + finalOutput = this._concatOutputChunks( + finalOutput, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + chunk + ); + } catch { + finalOutput = void 0; + finalOutputSupported = false; + } + } + } + } + } catch (e) { + await runManager?.handleChainError(e, void 0, void 0, void 0, { + inputs: _coerceToDict3(finalInput, "input") + }); + throw e; + } + await runManager?.handleChainEnd(finalOutput ?? {}, void 0, void 0, void 0, { inputs: _coerceToDict3(finalInput, "input") }); + } + getGraph(_) { + const graph = new Graph(); + const inputNode = graph.addNode({ + name: `${this.getName()}Input`, + schema: external_exports.any() + }); + const runnableNode = graph.addNode(this); + const outputNode = graph.addNode({ + name: `${this.getName()}Output`, + schema: external_exports.any() + }); + graph.addEdge(inputNode, runnableNode); + graph.addEdge(runnableNode, outputNode); + return graph; + } + /** + * Create a new runnable sequence that runs each individual runnable in series, + * piping the output of one runnable into another runnable or runnable-like. + * @param coerceable A runnable, function, or object whose values are functions or runnables. + * @returns A new runnable sequence. + */ + pipe(coerceable) { + return new RunnableSequence({ + first: this, + last: _coerceToRunnable(coerceable) + }); + } + /** + * Pick keys from the dict output of this runnable. Returns a new runnable. + */ + pick(keys) { + return this.pipe(new RunnablePick(keys)); + } + /** + * Assigns new fields to the dict output of this runnable. Returns a new runnable. + */ + assign(mapping) { + return this.pipe( + // eslint-disable-next-line @typescript-eslint/no-use-before-define + new RunnableAssign( + // eslint-disable-next-line @typescript-eslint/no-use-before-define + new RunnableMap({ steps: mapping }) + ) + ); + } + /** + * Default implementation of transform, which buffers input and then calls stream. + * Subclasses should override this method if they can start producing output while + * input is still being generated. + * @param generator + * @param options + */ + async *transform(generator, options) { + let finalChunk; + for await (const chunk of generator) { + if (finalChunk === void 0) { + finalChunk = chunk; + } else { + finalChunk = this._concatOutputChunks(finalChunk, chunk); + } + } + yield* this._streamIterator(finalChunk, ensureConfig(options)); + } + /** + * Stream all output from a runnable, as reported to the callback system. + * This includes all inner runs of LLMs, Retrievers, Tools, etc. + * Output is streamed as Log objects, which include a list of + * jsonpatch ops that describe how the state of the run has changed in each + * step, and the final state of the run. + * The jsonpatch ops can be applied in order to construct state. + * @param input + * @param options + * @param streamOptions + */ + async *streamLog(input, options, streamOptions) { + const logStreamCallbackHandler = new LogStreamCallbackHandler({ + ...streamOptions, + autoClose: false, + _schemaFormat: "original" + }); + const config2 = ensureConfig(options); + yield* this._streamLog(input, logStreamCallbackHandler, config2); + } + async *_streamLog(input, logStreamCallbackHandler, config2) { + const { callbacks } = config2; + if (callbacks === void 0) { + config2.callbacks = [logStreamCallbackHandler]; + } else if (Array.isArray(callbacks)) { + config2.callbacks = callbacks.concat([logStreamCallbackHandler]); + } else { + const copiedCallbacks = callbacks.copy(); + copiedCallbacks.addHandler(logStreamCallbackHandler, true); + config2.callbacks = copiedCallbacks; + } + const runnableStreamPromise = this.stream(input, config2); + async function consumeRunnableStream() { + try { + const runnableStream = await runnableStreamPromise; + for await (const chunk of runnableStream) { + const patch = new RunLogPatch({ + ops: [ + { + op: "add", + path: "/streamed_output/-", + value: chunk + } + ] + }); + await logStreamCallbackHandler.writer.write(patch); + } + } finally { + await logStreamCallbackHandler.writer.close(); + } + } + const runnableStreamConsumePromise = consumeRunnableStream(); + try { + for await (const log of logStreamCallbackHandler) { + yield log; + } + } finally { + await runnableStreamConsumePromise; + } + } + streamEvents(input, options, streamOptions) { + let stream; + if (options.version === "v1") { + stream = this._streamEventsV1(input, options, streamOptions); + } else if (options.version === "v2") { + stream = this._streamEventsV2(input, options, streamOptions); + } else { + throw new Error(`Only versions "v1" and "v2" of the schema are currently supported.`); + } + if (options.encoding === "text/event-stream") { + return convertToHttpEventStream(stream); + } else { + return IterableReadableStream.fromAsyncGenerator(stream); + } + } + async *_streamEventsV2(input, options, streamOptions) { + const eventStreamer = new EventStreamCallbackHandler({ + ...streamOptions, + autoClose: false + }); + const config2 = ensureConfig(options); + const runId = config2.runId ?? v4_default(); + config2.runId = runId; + const callbacks = config2.callbacks; + if (callbacks === void 0) { + config2.callbacks = [eventStreamer]; + } else if (Array.isArray(callbacks)) { + config2.callbacks = callbacks.concat(eventStreamer); + } else { + const copiedCallbacks = callbacks.copy(); + copiedCallbacks.addHandler(eventStreamer, true); + config2.callbacks = copiedCallbacks; + } + const abortController = new AbortController(); + const outerThis = this; + async function consumeRunnableStream() { + let signal; + let listener = null; + try { + if (options?.signal) { + if ("any" in AbortSignal) { + signal = AbortSignal.any([ + abortController.signal, + options.signal + ]); + } else { + signal = options.signal; + listener = () => { + abortController.abort(); + }; + options.signal.addEventListener("abort", listener, { once: true }); + } + } else { + signal = abortController.signal; + } + const runnableStream = await outerThis.stream(input, { + ...config2, + signal + }); + const tappedStream = eventStreamer.tapOutputIterable(runId, runnableStream); + for await (const _ of tappedStream) { + if (abortController.signal.aborted) + break; + } + } finally { + await eventStreamer.finish(); + if (signal && listener) { + signal.removeEventListener("abort", listener); + } + } + } + const runnableStreamConsumePromise = consumeRunnableStream(); + let firstEventSent = false; + let firstEventRunId; + try { + for await (const event of eventStreamer) { + if (!firstEventSent) { + event.data.input = input; + firstEventSent = true; + firstEventRunId = event.run_id; + yield event; + continue; + } + if (event.run_id === firstEventRunId && event.event.endsWith("_end")) { + if (event.data?.input) { + delete event.data.input; + } + } + yield event; + } + } finally { + abortController.abort(); + await runnableStreamConsumePromise; + } + } + async *_streamEventsV1(input, options, streamOptions) { + let runLog; + let hasEncounteredStartEvent = false; + const config2 = ensureConfig(options); + const rootTags = config2.tags ?? []; + const rootMetadata = config2.metadata ?? {}; + const rootName = config2.runName ?? this.getName(); + const logStreamCallbackHandler = new LogStreamCallbackHandler({ + ...streamOptions, + autoClose: false, + _schemaFormat: "streaming_events" + }); + const rootEventFilter = new _RootEventFilter({ + ...streamOptions + }); + const logStream = this._streamLog(input, logStreamCallbackHandler, config2); + for await (const log of logStream) { + if (!runLog) { + runLog = RunLog.fromRunLogPatch(log); + } else { + runLog = runLog.concat(log); + } + if (runLog.state === void 0) { + throw new Error(`Internal error: "streamEvents" state is missing. Please open a bug report.`); + } + if (!hasEncounteredStartEvent) { + hasEncounteredStartEvent = true; + const state3 = { ...runLog.state }; + const event = { + run_id: state3.id, + event: `on_${state3.type}_start`, + name: rootName, + tags: rootTags, + metadata: rootMetadata, + data: { + input + } + }; + if (rootEventFilter.includeEvent(event, state3.type)) { + yield event; + } + } + const paths = log.ops.filter((op) => op.path.startsWith("/logs/")).map((op) => op.path.split("/")[2]); + const dedupedPaths = [...new Set(paths)]; + for (const path of dedupedPaths) { + let eventType; + let data = {}; + const logEntry = runLog.state.logs[path]; + if (logEntry.end_time === void 0) { + if (logEntry.streamed_output.length > 0) { + eventType = "stream"; + } else { + eventType = "start"; + } + } else { + eventType = "end"; + } + if (eventType === "start") { + if (logEntry.inputs !== void 0) { + data.input = logEntry.inputs; + } + } else if (eventType === "end") { + if (logEntry.inputs !== void 0) { + data.input = logEntry.inputs; + } + data.output = logEntry.final_output; + } else if (eventType === "stream") { + const chunkCount = logEntry.streamed_output.length; + if (chunkCount !== 1) { + throw new Error(`Expected exactly one chunk of streamed output, got ${chunkCount} instead. Encountered in: "${logEntry.name}"`); + } + data = { chunk: logEntry.streamed_output[0] }; + logEntry.streamed_output = []; + } + yield { + event: `on_${logEntry.type}_${eventType}`, + name: logEntry.name, + run_id: logEntry.id, + tags: logEntry.tags, + metadata: logEntry.metadata, + data + }; + } + const { state: state2 } = runLog; + if (state2.streamed_output.length > 0) { + const chunkCount = state2.streamed_output.length; + if (chunkCount !== 1) { + throw new Error(`Expected exactly one chunk of streamed output, got ${chunkCount} instead. Encountered in: "${state2.name}"`); + } + const data = { chunk: state2.streamed_output[0] }; + state2.streamed_output = []; + const event = { + event: `on_${state2.type}_stream`, + run_id: state2.id, + tags: rootTags, + metadata: rootMetadata, + name: rootName, + data + }; + if (rootEventFilter.includeEvent(event, state2.type)) { + yield event; + } + } + } + const state = runLog?.state; + if (state !== void 0) { + const event = { + event: `on_${state.type}_end`, + name: rootName, + run_id: state.id, + tags: rootTags, + metadata: rootMetadata, + data: { + output: state.final_output + } + }; + if (rootEventFilter.includeEvent(event, state.type)) + yield event; + } + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + static isRunnable(thing) { + return isRunnableInterface(thing); + } + /** + * Bind lifecycle listeners to a Runnable, returning a new Runnable. + * The Run object contains information about the run, including its id, + * type, input, output, error, startTime, endTime, and any tags or metadata + * added to the run. + * + * @param {Object} params - The object containing the callback functions. + * @param {(run: Run) => void} params.onStart - Called before the runnable starts running, with the Run object. + * @param {(run: Run) => void} params.onEnd - Called after the runnable finishes running, with the Run object. + * @param {(run: Run) => void} params.onError - Called if the runnable throws an error, with the Run object. + */ + withListeners({ onStart, onEnd, onError }) { + return new RunnableBinding({ + bound: this, + config: {}, + configFactories: [ + (config2) => ({ + callbacks: [ + new RootListenersTracer({ + config: config2, + onStart, + onEnd, + onError + }) + ] + }) + ] + }); + } + /** + * Convert a runnable to a tool. Return a new instance of `RunnableToolLike` + * which contains the runnable, name, description and schema. + * + * @template {T extends RunInput = RunInput} RunInput - The input type of the runnable. Should be the same as the `RunInput` type of the runnable. + * + * @param fields + * @param {string | undefined} [fields.name] The name of the tool. If not provided, it will default to the name of the runnable. + * @param {string | undefined} [fields.description] The description of the tool. Falls back to the description on the Zod schema if not provided, or undefined if neither are provided. + * @param {z.ZodType} [fields.schema] The Zod schema for the input of the tool. Infers the Zod type from the input type of the runnable. + * @returns {RunnableToolLike, RunOutput>} An instance of `RunnableToolLike` which is a runnable that can be used as a tool. + */ + asTool(fields) { + return convertRunnableToTool(this, fields); + } + }; + RunnableBinding = class _RunnableBinding extends Runnable { + static lc_name() { + return "RunnableBinding"; + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain_core", "runnables"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "bound", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "config", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "kwargs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "configFactories", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.bound = fields.bound; + this.kwargs = fields.kwargs; + this.config = fields.config; + this.configFactories = fields.configFactories; + } + getName(suffix) { + return this.bound.getName(suffix); + } + async _mergeConfig(...options) { + const config2 = mergeConfigs(this.config, ...options); + return mergeConfigs(config2, ...this.configFactories ? await Promise.all(this.configFactories.map(async (configFactory) => await configFactory(config2))) : []); + } + /** + * Binds the runnable with the specified arguments. + * @param kwargs The arguments to bind the runnable with. + * @returns A new instance of the `RunnableBinding` class that is bound with the specified arguments. + * + * @deprecated Use {@link withConfig} instead. This will be removed in the next breaking release. + */ + bind(kwargs) { + return new this.constructor({ + bound: this.bound, + kwargs: { ...this.kwargs, ...kwargs }, + config: this.config + }); + } + withConfig(config2) { + return new this.constructor({ + bound: this.bound, + kwargs: this.kwargs, + config: { ...this.config, ...config2 } + }); + } + withRetry(fields) { + return new RunnableRetry({ + bound: this.bound, + kwargs: this.kwargs, + config: this.config, + maxAttemptNumber: fields?.stopAfterAttempt, + ...fields + }); + } + async invoke(input, options) { + return this.bound.invoke(input, await this._mergeConfig(ensureConfig(options), this.kwargs)); + } + async batch(inputs, options, batchOptions) { + const mergedOptions = Array.isArray(options) ? await Promise.all(options.map(async (individualOption) => this._mergeConfig(ensureConfig(individualOption), this.kwargs))) : await this._mergeConfig(ensureConfig(options), this.kwargs); + return this.bound.batch(inputs, mergedOptions, batchOptions); + } + /** @internal */ + _concatOutputChunks(first, second) { + return this.bound._concatOutputChunks(first, second); + } + async *_streamIterator(input, options) { + yield* this.bound._streamIterator(input, await this._mergeConfig(ensureConfig(options), this.kwargs)); + } + async stream(input, options) { + return this.bound.stream(input, await this._mergeConfig(ensureConfig(options), this.kwargs)); + } + async *transform(generator, options) { + yield* this.bound.transform(generator, await this._mergeConfig(ensureConfig(options), this.kwargs)); + } + streamEvents(input, options, streamOptions) { + const outerThis = this; + const generator = async function* () { + yield* outerThis.bound.streamEvents(input, { + ...await outerThis._mergeConfig(ensureConfig(options), outerThis.kwargs), + version: options.version + }, streamOptions); + }; + return IterableReadableStream.fromAsyncGenerator(generator()); + } + static isRunnableBinding(thing) { + return thing.bound && Runnable.isRunnable(thing.bound); + } + /** + * Bind lifecycle listeners to a Runnable, returning a new Runnable. + * The Run object contains information about the run, including its id, + * type, input, output, error, startTime, endTime, and any tags or metadata + * added to the run. + * + * @param {Object} params - The object containing the callback functions. + * @param {(run: Run) => void} params.onStart - Called before the runnable starts running, with the Run object. + * @param {(run: Run) => void} params.onEnd - Called after the runnable finishes running, with the Run object. + * @param {(run: Run) => void} params.onError - Called if the runnable throws an error, with the Run object. + */ + withListeners({ onStart, onEnd, onError }) { + return new _RunnableBinding({ + bound: this.bound, + kwargs: this.kwargs, + config: this.config, + configFactories: [ + (config2) => ({ + callbacks: [ + new RootListenersTracer({ + config: config2, + onStart, + onEnd, + onError + }) + ] + }) + ] + }); + } + }; + RunnableEach = class _RunnableEach extends Runnable { + static lc_name() { + return "RunnableEach"; + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain_core", "runnables"] + }); + Object.defineProperty(this, "bound", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.bound = fields.bound; + } + /** + * Binds the runnable with the specified arguments. + * @param kwargs The arguments to bind the runnable with. + * @returns A new instance of the `RunnableEach` class that is bound with the specified arguments. + * + * @deprecated Use {@link withConfig} instead. This will be removed in the next breaking release. + */ + bind(kwargs) { + return new _RunnableEach({ + bound: this.bound.bind(kwargs) + }); + } + /** + * Invokes the runnable with the specified input and configuration. + * @param input The input to invoke the runnable with. + * @param config The configuration to invoke the runnable with. + * @returns A promise that resolves to the output of the runnable. + */ + async invoke(inputs, config2) { + return this._callWithConfig(this._invoke.bind(this), inputs, config2); + } + /** + * A helper method that is used to invoke the runnable with the specified input and configuration. + * @param input The input to invoke the runnable with. + * @param config The configuration to invoke the runnable with. + * @returns A promise that resolves to the output of the runnable. + */ + async _invoke(inputs, config2, runManager) { + return this.bound.batch(inputs, patchConfig(config2, { callbacks: runManager?.getChild() })); + } + /** + * Bind lifecycle listeners to a Runnable, returning a new Runnable. + * The Run object contains information about the run, including its id, + * type, input, output, error, startTime, endTime, and any tags or metadata + * added to the run. + * + * @param {Object} params - The object containing the callback functions. + * @param {(run: Run) => void} params.onStart - Called before the runnable starts running, with the Run object. + * @param {(run: Run) => void} params.onEnd - Called after the runnable finishes running, with the Run object. + * @param {(run: Run) => void} params.onError - Called if the runnable throws an error, with the Run object. + */ + withListeners({ onStart, onEnd, onError }) { + return new _RunnableEach({ + bound: this.bound.withListeners({ onStart, onEnd, onError }) + }); + } + }; + RunnableRetry = class extends RunnableBinding { + static lc_name() { + return "RunnableRetry"; + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain_core", "runnables"] + }); + Object.defineProperty(this, "maxAttemptNumber", { + enumerable: true, + configurable: true, + writable: true, + value: 3 + }); + Object.defineProperty(this, "onFailedAttempt", { + enumerable: true, + configurable: true, + writable: true, + value: () => { + } + }); + this.maxAttemptNumber = fields.maxAttemptNumber ?? this.maxAttemptNumber; + this.onFailedAttempt = fields.onFailedAttempt ?? this.onFailedAttempt; + } + _patchConfigForRetry(attempt, config2, runManager) { + const tag = attempt > 1 ? `retry:attempt:${attempt}` : void 0; + return patchConfig(config2, { callbacks: runManager?.getChild(tag) }); + } + async _invoke(input, config2, runManager) { + return (0, import_p_retry3.default)((attemptNumber) => super.invoke(input, this._patchConfigForRetry(attemptNumber, config2, runManager)), { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + onFailedAttempt: (error) => this.onFailedAttempt(error, input), + retries: Math.max(this.maxAttemptNumber - 1, 0), + randomize: true + }); + } + /** + * Method that invokes the runnable with the specified input, run manager, + * and config. It handles the retry logic by catching any errors and + * recursively invoking itself with the updated config for the next retry + * attempt. + * @param input The input for the runnable. + * @param runManager The run manager for the runnable. + * @param config The config for the runnable. + * @returns A promise that resolves to the output of the runnable. + */ + async invoke(input, config2) { + return this._callWithConfig(this._invoke.bind(this), input, config2); + } + async _batch(inputs, configs, runManagers, batchOptions) { + const resultsMap = {}; + try { + await (0, import_p_retry3.default)(async (attemptNumber) => { + const remainingIndexes = inputs.map((_, i) => i).filter((i) => resultsMap[i.toString()] === void 0 || // eslint-disable-next-line no-instanceof/no-instanceof + resultsMap[i.toString()] instanceof Error); + const remainingInputs = remainingIndexes.map((i) => inputs[i]); + const patchedConfigs = remainingIndexes.map((i) => this._patchConfigForRetry(attemptNumber, configs?.[i], runManagers?.[i])); + const results = await super.batch(remainingInputs, patchedConfigs, { + ...batchOptions, + returnExceptions: true + }); + let firstException; + for (let i = 0; i < results.length; i += 1) { + const result = results[i]; + const resultMapIndex = remainingIndexes[i]; + if (result instanceof Error) { + if (firstException === void 0) { + firstException = result; + firstException.input = remainingInputs[i]; + } + } + resultsMap[resultMapIndex.toString()] = result; + } + if (firstException) { + throw firstException; + } + return results; + }, { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + onFailedAttempt: (error) => this.onFailedAttempt(error, error.input), + retries: Math.max(this.maxAttemptNumber - 1, 0), + randomize: true + }); + } catch (e) { + if (batchOptions?.returnExceptions !== true) { + throw e; + } + } + return Object.keys(resultsMap).sort((a, b) => parseInt(a, 10) - parseInt(b, 10)).map((key) => resultsMap[parseInt(key, 10)]); + } + async batch(inputs, options, batchOptions) { + return this._batchWithConfig(this._batch.bind(this), inputs, options, batchOptions); + } + }; + RunnableSequence = class _RunnableSequence extends Runnable { + static lc_name() { + return "RunnableSequence"; + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "first", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "middle", { + enumerable: true, + configurable: true, + writable: true, + value: [] + }); + Object.defineProperty(this, "last", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "omitSequenceTags", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain_core", "runnables"] + }); + this.first = fields.first; + this.middle = fields.middle ?? this.middle; + this.last = fields.last; + this.name = fields.name; + this.omitSequenceTags = fields.omitSequenceTags ?? this.omitSequenceTags; + } + get steps() { + return [this.first, ...this.middle, this.last]; + } + async invoke(input, options) { + const config2 = ensureConfig(options); + const callbackManager_ = await getCallbackManagerForConfig(config2); + const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict3(input, "input"), config2.runId, void 0, void 0, void 0, config2?.runName); + delete config2.runId; + let nextStepInput = input; + let finalOutput; + try { + const initialSteps = [this.first, ...this.middle]; + for (let i = 0; i < initialSteps.length; i += 1) { + const step = initialSteps[i]; + const promise = step.invoke(nextStepInput, patchConfig(config2, { + callbacks: runManager?.getChild(this.omitSequenceTags ? void 0 : `seq:step:${i + 1}`) + })); + nextStepInput = await raceWithSignal(promise, options?.signal); + } + if (options?.signal?.aborted) { + throw new Error("Aborted"); + } + finalOutput = await this.last.invoke(nextStepInput, patchConfig(config2, { + callbacks: runManager?.getChild(this.omitSequenceTags ? void 0 : `seq:step:${this.steps.length}`) + })); + } catch (e) { + await runManager?.handleChainError(e); + throw e; + } + await runManager?.handleChainEnd(_coerceToDict3(finalOutput, "output")); + return finalOutput; + } + async batch(inputs, options, batchOptions) { + const configList = this._getOptionsList(options ?? {}, inputs.length); + const callbackManagers = await Promise.all(configList.map(getCallbackManagerForConfig)); + const runManagers = await Promise.all(callbackManagers.map(async (callbackManager, i) => { + const handleStartRes = await callbackManager?.handleChainStart(this.toJSON(), _coerceToDict3(inputs[i], "input"), configList[i].runId, void 0, void 0, void 0, configList[i].runName); + delete configList[i].runId; + return handleStartRes; + })); + let nextStepInputs = inputs; + try { + for (let i = 0; i < this.steps.length; i += 1) { + const step = this.steps[i]; + const promise = step.batch(nextStepInputs, runManagers.map((runManager, j) => { + const childRunManager = runManager?.getChild(this.omitSequenceTags ? void 0 : `seq:step:${i + 1}`); + return patchConfig(configList[j], { callbacks: childRunManager }); + }), batchOptions); + nextStepInputs = await raceWithSignal(promise, configList[0]?.signal); + } + } catch (e) { + await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(e))); + throw e; + } + await Promise.all(runManagers.map((runManager) => runManager?.handleChainEnd(_coerceToDict3(nextStepInputs, "output")))); + return nextStepInputs; + } + /** @internal */ + _concatOutputChunks(first, second) { + return this.last._concatOutputChunks(first, second); + } + async *_streamIterator(input, options) { + const callbackManager_ = await getCallbackManagerForConfig(options); + const { runId, ...otherOptions } = options ?? {}; + const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict3(input, "input"), runId, void 0, void 0, void 0, otherOptions?.runName); + const steps = [this.first, ...this.middle, this.last]; + let concatSupported = true; + let finalOutput; + async function* inputGenerator() { + yield input; + } + try { + let finalGenerator = steps[0].transform(inputGenerator(), patchConfig(otherOptions, { + callbacks: runManager?.getChild(this.omitSequenceTags ? void 0 : `seq:step:1`) + })); + for (let i = 1; i < steps.length; i += 1) { + const step = steps[i]; + finalGenerator = await step.transform(finalGenerator, patchConfig(otherOptions, { + callbacks: runManager?.getChild(this.omitSequenceTags ? void 0 : `seq:step:${i + 1}`) + })); + } + for await (const chunk of finalGenerator) { + options?.signal?.throwIfAborted(); + yield chunk; + if (concatSupported) { + if (finalOutput === void 0) { + finalOutput = chunk; + } else { + try { + finalOutput = this._concatOutputChunks(finalOutput, chunk); + } catch (e) { + finalOutput = void 0; + concatSupported = false; + } + } + } + } + } catch (e) { + await runManager?.handleChainError(e); + throw e; + } + await runManager?.handleChainEnd(_coerceToDict3(finalOutput, "output")); + } + getGraph(config2) { + const graph = new Graph(); + let currentLastNode = null; + this.steps.forEach((step, index2) => { + const stepGraph = step.getGraph(config2); + if (index2 !== 0) { + stepGraph.trimFirstNode(); + } + if (index2 !== this.steps.length - 1) { + stepGraph.trimLastNode(); + } + graph.extend(stepGraph); + const stepFirstNode = stepGraph.firstNode(); + if (!stepFirstNode) { + throw new Error(`Runnable ${step} has no first node`); + } + if (currentLastNode) { + graph.addEdge(currentLastNode, stepFirstNode); + } + currentLastNode = stepGraph.lastNode(); + }); + return graph; + } + pipe(coerceable) { + if (_RunnableSequence.isRunnableSequence(coerceable)) { + return new _RunnableSequence({ + first: this.first, + middle: this.middle.concat([ + this.last, + coerceable.first, + ...coerceable.middle + ]), + last: coerceable.last, + name: this.name ?? coerceable.name + }); + } else { + return new _RunnableSequence({ + first: this.first, + middle: [...this.middle, this.last], + last: _coerceToRunnable(coerceable), + name: this.name + }); + } + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + static isRunnableSequence(thing) { + return Array.isArray(thing.middle) && Runnable.isRunnable(thing); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + static from([first, ...runnables], nameOrFields) { + let extra = {}; + if (typeof nameOrFields === "string") { + extra.name = nameOrFields; + } else if (nameOrFields !== void 0) { + extra = nameOrFields; + } + return new _RunnableSequence({ + ...extra, + first: _coerceToRunnable(first), + middle: runnables.slice(0, -1).map(_coerceToRunnable), + last: _coerceToRunnable(runnables[runnables.length - 1]) + }); + } + }; + RunnableMap = class _RunnableMap extends Runnable { + static lc_name() { + return "RunnableMap"; + } + getStepsKeys() { + return Object.keys(this.steps); + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain_core", "runnables"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "steps", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.steps = {}; + for (const [key, value] of Object.entries(fields.steps)) { + this.steps[key] = _coerceToRunnable(value); + } + } + static from(steps) { + return new _RunnableMap({ steps }); + } + async invoke(input, options) { + const config2 = ensureConfig(options); + const callbackManager_ = await getCallbackManagerForConfig(config2); + const runManager = await callbackManager_?.handleChainStart(this.toJSON(), { + input + }, config2.runId, void 0, void 0, void 0, config2?.runName); + delete config2.runId; + const output = {}; + try { + const promises = Object.entries(this.steps).map(async ([key, runnable]) => { + output[key] = await runnable.invoke(input, patchConfig(config2, { + callbacks: runManager?.getChild(`map:key:${key}`) + })); + }); + await raceWithSignal(Promise.all(promises), options?.signal); + } catch (e) { + await runManager?.handleChainError(e); + throw e; + } + await runManager?.handleChainEnd(output); + return output; + } + async *_transform(generator, runManager, options) { + const steps = { ...this.steps }; + const inputCopies = atee(generator, Object.keys(steps).length); + const tasks = new Map(Object.entries(steps).map(([key, runnable], i) => { + const gen = runnable.transform(inputCopies[i], patchConfig(options, { + callbacks: runManager?.getChild(`map:key:${key}`) + })); + return [key, gen.next().then((result) => ({ key, gen, result }))]; + })); + while (tasks.size) { + const promise = Promise.race(tasks.values()); + const { key, result, gen } = await raceWithSignal(promise, options?.signal); + tasks.delete(key); + if (!result.done) { + yield { [key]: result.value }; + tasks.set(key, gen.next().then((result2) => ({ key, gen, result: result2 }))); + } + } + } + transform(generator, options) { + return this._transformStreamWithConfig(generator, this._transform.bind(this), options); + } + async stream(input, options) { + async function* generator() { + yield input; + } + const config2 = ensureConfig(options); + const wrappedGenerator = new AsyncGeneratorWithSetup({ + generator: this.transform(generator(), config2), + config: config2 + }); + await wrappedGenerator.setup; + return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); + } + }; + RunnableTraceable = class _RunnableTraceable extends Runnable { + constructor(fields) { + super(fields); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain_core", "runnables"] + }); + Object.defineProperty(this, "func", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + if (!isTraceableFunction(fields.func)) { + throw new Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function"); + } + this.func = fields.func; + } + async invoke(input, options) { + const [config2] = this._getOptionsList(options ?? {}, 1); + const callbacks = await getCallbackManagerForConfig(config2); + const promise = this.func(patchConfig(config2, { callbacks }), input); + return raceWithSignal(promise, config2?.signal); + } + async *_streamIterator(input, options) { + const [config2] = this._getOptionsList(options ?? {}, 1); + const result = await this.invoke(input, options); + if (isAsyncIterable(result)) { + for await (const item of result) { + config2?.signal?.throwIfAborted(); + yield item; + } + return; + } + if (isIterator(result)) { + while (true) { + config2?.signal?.throwIfAborted(); + const state = result.next(); + if (state.done) + break; + yield state.value; + } + return; + } + yield result; + } + static from(func) { + return new _RunnableTraceable({ func }); + } + }; + RunnableLambda = class _RunnableLambda extends Runnable { + static lc_name() { + return "RunnableLambda"; + } + constructor(fields) { + if (isTraceableFunction(fields.func)) { + return RunnableTraceable.from(fields.func); + } + super(fields); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain_core", "runnables"] + }); + Object.defineProperty(this, "func", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + assertNonTraceableFunction(fields.func); + this.func = fields.func; + } + static from(func) { + return new _RunnableLambda({ + func + }); + } + async _invoke(input, config2, runManager) { + return new Promise((resolve, reject) => { + const childConfig = patchConfig(config2, { + callbacks: runManager?.getChild(), + recursionLimit: (config2?.recursionLimit ?? DEFAULT_RECURSION_LIMIT) - 1 + }); + void AsyncLocalStorageProviderSingleton2.runWithConfig(pickRunnableConfigKeys(childConfig), async () => { + try { + let output = await this.func(input, { + ...childConfig + }); + if (output && Runnable.isRunnable(output)) { + if (config2?.recursionLimit === 0) { + throw new Error("Recursion limit reached."); + } + output = await output.invoke(input, { + ...childConfig, + recursionLimit: (childConfig.recursionLimit ?? DEFAULT_RECURSION_LIMIT) - 1 + }); + } else if (isAsyncIterable(output)) { + let finalOutput; + for await (const chunk of consumeAsyncIterableInContext(childConfig, output)) { + config2?.signal?.throwIfAborted(); + if (finalOutput === void 0) { + finalOutput = chunk; + } else { + try { + finalOutput = this._concatOutputChunks( + finalOutput, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + chunk + ); + } catch (e) { + finalOutput = chunk; + } + } + } + output = finalOutput; + } else if (isIterableIterator(output)) { + let finalOutput; + for (const chunk of consumeIteratorInContext(childConfig, output)) { + config2?.signal?.throwIfAborted(); + if (finalOutput === void 0) { + finalOutput = chunk; + } else { + try { + finalOutput = this._concatOutputChunks( + finalOutput, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + chunk + ); + } catch (e) { + finalOutput = chunk; + } + } + } + output = finalOutput; + } + resolve(output); + } catch (e) { + reject(e); + } + }); + }); + } + async invoke(input, options) { + return this._callWithConfig(this._invoke.bind(this), input, options); + } + async *_transform(generator, runManager, config2) { + let finalChunk; + for await (const chunk of generator) { + if (finalChunk === void 0) { + finalChunk = chunk; + } else { + try { + finalChunk = this._concatOutputChunks(finalChunk, chunk); + } catch (e) { + finalChunk = chunk; + } + } + } + const childConfig = patchConfig(config2, { + callbacks: runManager?.getChild(), + recursionLimit: (config2?.recursionLimit ?? DEFAULT_RECURSION_LIMIT) - 1 + }); + const output = await new Promise((resolve, reject) => { + void AsyncLocalStorageProviderSingleton2.runWithConfig(pickRunnableConfigKeys(childConfig), async () => { + try { + const res = await this.func(finalChunk, { + ...childConfig, + config: childConfig + }); + resolve(res); + } catch (e) { + reject(e); + } + }); + }); + if (output && Runnable.isRunnable(output)) { + if (config2?.recursionLimit === 0) { + throw new Error("Recursion limit reached."); + } + const stream = await output.stream(finalChunk, childConfig); + for await (const chunk of stream) { + yield chunk; + } + } else if (isAsyncIterable(output)) { + for await (const chunk of consumeAsyncIterableInContext(childConfig, output)) { + config2?.signal?.throwIfAborted(); + yield chunk; + } + } else if (isIterableIterator(output)) { + for (const chunk of consumeIteratorInContext(childConfig, output)) { + config2?.signal?.throwIfAborted(); + yield chunk; + } + } else { + yield output; + } + } + transform(generator, options) { + return this._transformStreamWithConfig(generator, this._transform.bind(this), options); + } + async stream(input, options) { + async function* generator() { + yield input; + } + const config2 = ensureConfig(options); + const wrappedGenerator = new AsyncGeneratorWithSetup({ + generator: this.transform(generator(), config2), + config: config2 + }); + await wrappedGenerator.setup; + return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); + } + }; + RunnableParallel = class extends RunnableMap { + }; + RunnableWithFallbacks = class extends Runnable { + static lc_name() { + return "RunnableWithFallbacks"; + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain_core", "runnables"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "runnable", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "fallbacks", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.runnable = fields.runnable; + this.fallbacks = fields.fallbacks; + } + *runnables() { + yield this.runnable; + for (const fallback of this.fallbacks) { + yield fallback; + } + } + async invoke(input, options) { + const config2 = ensureConfig(options); + const callbackManager_ = await getCallbackManagerForConfig(config2); + const { runId, ...otherConfigFields } = config2; + const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict3(input, "input"), runId, void 0, void 0, void 0, otherConfigFields?.runName); + const childConfig = patchConfig(otherConfigFields, { + callbacks: runManager?.getChild() + }); + const res = await AsyncLocalStorageProviderSingleton2.runWithConfig(childConfig, async () => { + let firstError; + for (const runnable of this.runnables()) { + config2?.signal?.throwIfAborted(); + try { + const output = await runnable.invoke(input, childConfig); + await runManager?.handleChainEnd(_coerceToDict3(output, "output")); + return output; + } catch (e) { + if (firstError === void 0) { + firstError = e; + } + } + } + if (firstError === void 0) { + throw new Error("No error stored at end of fallback."); + } + await runManager?.handleChainError(firstError); + throw firstError; + }); + return res; + } + async *_streamIterator(input, options) { + const config2 = ensureConfig(options); + const callbackManager_ = await getCallbackManagerForConfig(config2); + const { runId, ...otherConfigFields } = config2; + const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict3(input, "input"), runId, void 0, void 0, void 0, otherConfigFields?.runName); + let firstError; + let stream; + for (const runnable of this.runnables()) { + config2?.signal?.throwIfAborted(); + const childConfig = patchConfig(otherConfigFields, { + callbacks: runManager?.getChild() + }); + try { + const originalStream = await runnable.stream(input, childConfig); + stream = consumeAsyncIterableInContext(childConfig, originalStream); + break; + } catch (e) { + if (firstError === void 0) { + firstError = e; + } + } + } + if (stream === void 0) { + const error = firstError ?? new Error("No error stored at end of fallback."); + await runManager?.handleChainError(error); + throw error; + } + let output; + try { + for await (const chunk of stream) { + yield chunk; + try { + output = output === void 0 ? output : this._concatOutputChunks(output, chunk); + } catch (e) { + output = void 0; + } + } + } catch (e) { + await runManager?.handleChainError(e); + throw e; + } + await runManager?.handleChainEnd(_coerceToDict3(output, "output")); + } + async batch(inputs, options, batchOptions) { + if (batchOptions?.returnExceptions) { + throw new Error("Not implemented."); + } + const configList = this._getOptionsList(options ?? {}, inputs.length); + const callbackManagers = await Promise.all(configList.map((config2) => getCallbackManagerForConfig(config2))); + const runManagers = await Promise.all(callbackManagers.map(async (callbackManager, i) => { + const handleStartRes = await callbackManager?.handleChainStart(this.toJSON(), _coerceToDict3(inputs[i], "input"), configList[i].runId, void 0, void 0, void 0, configList[i].runName); + delete configList[i].runId; + return handleStartRes; + })); + let firstError; + for (const runnable of this.runnables()) { + configList[0].signal?.throwIfAborted(); + try { + const outputs = await runnable.batch(inputs, runManagers.map((runManager, j) => patchConfig(configList[j], { + callbacks: runManager?.getChild() + })), batchOptions); + await Promise.all(runManagers.map((runManager, i) => runManager?.handleChainEnd(_coerceToDict3(outputs[i], "output")))); + return outputs; + } catch (e) { + if (firstError === void 0) { + firstError = e; + } + } + } + if (!firstError) { + throw new Error("No error stored at end of fallbacks."); + } + await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(firstError))); + throw firstError; + } + }; + RunnableAssign = class extends Runnable { + static lc_name() { + return "RunnableAssign"; + } + constructor(fields) { + if (fields instanceof RunnableMap) { + fields = { mapper: fields }; + } + super(fields); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain_core", "runnables"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "mapper", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.mapper = fields.mapper; + } + async invoke(input, options) { + const mapperResult = await this.mapper.invoke(input, options); + return { + ...input, + ...mapperResult + }; + } + async *_transform(generator, runManager, options) { + const mapperKeys = this.mapper.getStepsKeys(); + const [forPassthrough, forMapper] = atee(generator); + const mapperOutput = this.mapper.transform(forMapper, patchConfig(options, { callbacks: runManager?.getChild() })); + const firstMapperChunkPromise = mapperOutput.next(); + for await (const chunk of forPassthrough) { + if (typeof chunk !== "object" || Array.isArray(chunk)) { + throw new Error(`RunnableAssign can only be used with objects as input, got ${typeof chunk}`); + } + const filtered = Object.fromEntries(Object.entries(chunk).filter(([key]) => !mapperKeys.includes(key))); + if (Object.keys(filtered).length > 0) { + yield filtered; + } + } + yield (await firstMapperChunkPromise).value; + for await (const chunk of mapperOutput) { + yield chunk; + } + } + transform(generator, options) { + return this._transformStreamWithConfig(generator, this._transform.bind(this), options); + } + async stream(input, options) { + async function* generator() { + yield input; + } + const config2 = ensureConfig(options); + const wrappedGenerator = new AsyncGeneratorWithSetup({ + generator: this.transform(generator(), config2), + config: config2 + }); + await wrappedGenerator.setup; + return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); + } + }; + RunnablePick = class extends Runnable { + static lc_name() { + return "RunnablePick"; + } + constructor(fields) { + if (typeof fields === "string" || Array.isArray(fields)) { + fields = { keys: fields }; + } + super(fields); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain_core", "runnables"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "keys", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.keys = fields.keys; + } + async _pick(input) { + if (typeof this.keys === "string") { + return input[this.keys]; + } else { + const picked = this.keys.map((key) => [key, input[key]]).filter((v) => v[1] !== void 0); + return picked.length === 0 ? void 0 : Object.fromEntries(picked); + } + } + async invoke(input, options) { + return this._callWithConfig(this._pick.bind(this), input, options); + } + async *_transform(generator) { + for await (const chunk of generator) { + const picked = await this._pick(chunk); + if (picked !== void 0) { + yield picked; + } + } + } + transform(generator, options) { + return this._transformStreamWithConfig(generator, this._transform.bind(this), options); + } + async stream(input, options) { + async function* generator() { + yield input; + } + const config2 = ensureConfig(options); + const wrappedGenerator = new AsyncGeneratorWithSetup({ + generator: this.transform(generator(), config2), + config: config2 + }); + await wrappedGenerator.setup; + return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); + } + }; + RunnableToolLike = class extends RunnableBinding { + constructor(fields) { + const sequence = RunnableSequence.from([ + RunnableLambda.from(async (input) => { + let toolInput; + if (_isToolCall(input)) { + try { + toolInput = await interopParseAsync(this.schema, input.args); + } catch (e) { + throw new ToolInputParsingException(`Received tool input did not match expected schema`, JSON.stringify(input.args)); + } + } else { + toolInput = input; + } + return toolInput; + }).withConfig({ runName: `${fields.name}:parse_input` }), + fields.bound + ]).withConfig({ runName: fields.name }); + super({ + bound: sequence, + config: fields.config ?? {} + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "description", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "schema", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.name = fields.name; + this.description = fields.description; + this.schema = fields.schema; + } + static lc_name() { + return "RunnableToolLike"; + } + }; + } +}); + +// node_modules/@langchain/core/dist/messages/modifier.js +var RemoveMessage; +var init_modifier = __esm({ + "node_modules/@langchain/core/dist/messages/modifier.js"() { + init_base(); + RemoveMessage = class extends BaseMessage { + constructor(fields) { + super({ + ...fields, + content: "" + }); + Object.defineProperty(this, "id", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.id = fields.id; + } + _getType() { + return "remove"; + } + get _printableFields() { + return { + ...super._printableFields, + id: this.id + }; + } + }; + } +}); + +// node_modules/@langchain/core/dist/messages/transformers.js +function filterMessages(messagesOrOptions, options) { + if (Array.isArray(messagesOrOptions)) { + return _filterMessages(messagesOrOptions, options); + } + return RunnableLambda.from((input) => { + return _filterMessages(input, messagesOrOptions); + }); +} +function _filterMessages(messages, options = {}) { + const { includeNames, excludeNames, includeTypes, excludeTypes, includeIds, excludeIds } = options; + const filtered = []; + for (const msg of messages) { + if (excludeNames && msg.name && excludeNames.includes(msg.name)) { + continue; + } else if (excludeTypes && _isMessageType(msg, excludeTypes)) { + continue; + } else if (excludeIds && msg.id && excludeIds.includes(msg.id)) { + continue; + } + if (!(includeTypes || includeIds || includeNames)) { + filtered.push(msg); + } else if (includeNames && msg.name && includeNames.some((iName) => iName === msg.name)) { + filtered.push(msg); + } else if (includeTypes && _isMessageType(msg, includeTypes)) { + filtered.push(msg); + } else if (includeIds && msg.id && includeIds.some((id) => id === msg.id)) { + filtered.push(msg); + } + } + return filtered; +} +function mergeMessageRuns(messages) { + if (Array.isArray(messages)) { + return _mergeMessageRuns(messages); + } + return RunnableLambda.from(_mergeMessageRuns); +} +function _mergeMessageRuns(messages) { + if (!messages.length) { + return []; + } + const merged = []; + for (const msg of messages) { + const curr = msg; + const last2 = merged.pop(); + if (!last2) { + merged.push(curr); + } else if (curr.getType() === "tool" || !(curr.getType() === last2.getType())) { + merged.push(last2, curr); + } else { + const lastChunk = convertToChunk(last2); + const currChunk = convertToChunk(curr); + const mergedChunks = lastChunk.concat(currChunk); + if (typeof lastChunk.content === "string" && typeof currChunk.content === "string") { + mergedChunks.content = `${lastChunk.content} +${currChunk.content}`; + } + merged.push(_chunkToMsg(mergedChunks)); + } + } + return merged; +} +function trimMessages(messagesOrOptions, options) { + if (Array.isArray(messagesOrOptions)) { + const messages = messagesOrOptions; + if (!options) { + throw new Error("Options parameter is required when providing messages."); + } + return _trimMessagesHelper(messages, options); + } else { + const trimmerOptions = messagesOrOptions; + return RunnableLambda.from((input) => _trimMessagesHelper(input, trimmerOptions)).withConfig({ + runName: "trim_messages" + }); + } +} +async function _trimMessagesHelper(messages, options) { + const { maxTokens, tokenCounter, strategy = "last", allowPartial = false, endOn, startOn, includeSystem = false, textSplitter } = options; + if (startOn && strategy === "first") { + throw new Error("`startOn` should only be specified if `strategy` is 'last'."); + } + if (includeSystem && strategy === "first") { + throw new Error("`includeSystem` should only be specified if `strategy` is 'last'."); + } + let listTokenCounter; + if ("getNumTokens" in tokenCounter) { + listTokenCounter = async (msgs) => { + const tokenCounts = await Promise.all(msgs.map((msg) => tokenCounter.getNumTokens(msg.content))); + return tokenCounts.reduce((sum, count) => sum + count, 0); + }; + } else { + listTokenCounter = async (msgs) => tokenCounter(msgs); + } + let textSplitterFunc = defaultTextSplitter; + if (textSplitter) { + if ("splitText" in textSplitter) { + textSplitterFunc = textSplitter.splitText; + } else { + textSplitterFunc = async (text) => textSplitter(text); + } + } + if (strategy === "first") { + return _firstMaxTokens(messages, { + maxTokens, + tokenCounter: listTokenCounter, + textSplitter: textSplitterFunc, + partialStrategy: allowPartial ? "first" : void 0, + endOn + }); + } else if (strategy === "last") { + return _lastMaxTokens(messages, { + maxTokens, + tokenCounter: listTokenCounter, + textSplitter: textSplitterFunc, + allowPartial, + includeSystem, + startOn, + endOn + }); + } else { + throw new Error(`Unrecognized strategy: '${strategy}'. Must be one of 'first' or 'last'.`); + } +} +async function _firstMaxTokens(messages, options) { + const { maxTokens, tokenCounter, textSplitter, partialStrategy, endOn } = options; + let messagesCopy = [...messages]; + let idx = 0; + for (let i = 0; i < messagesCopy.length; i += 1) { + const remainingMessages = i > 0 ? messagesCopy.slice(0, -i) : messagesCopy; + if (await tokenCounter(remainingMessages) <= maxTokens) { + idx = messagesCopy.length - i; + break; + } + } + if (idx < messagesCopy.length - 1 && partialStrategy) { + let includedPartial = false; + if (Array.isArray(messagesCopy[idx].content)) { + const excluded = messagesCopy[idx]; + if (typeof excluded.content === "string") { + throw new Error("Expected content to be an array."); + } + const numBlock = excluded.content.length; + const reversedContent = partialStrategy === "last" ? [...excluded.content].reverse() : excluded.content; + for (let i = 1; i <= numBlock; i += 1) { + const partialContent = partialStrategy === "first" ? reversedContent.slice(0, i) : reversedContent.slice(-i); + const fields = Object.fromEntries(Object.entries(excluded).filter(([k]) => k !== "type" && !k.startsWith("lc_"))); + const updatedMessage = _switchTypeToMessage(excluded.getType(), { + ...fields, + content: partialContent + }); + const slicedMessages = [...messagesCopy.slice(0, idx), updatedMessage]; + if (await tokenCounter(slicedMessages) <= maxTokens) { + messagesCopy = slicedMessages; + idx += 1; + includedPartial = true; + } else { + break; + } + } + if (includedPartial && partialStrategy === "last") { + excluded.content = [...reversedContent].reverse(); + } + } + if (!includedPartial) { + const excluded = messagesCopy[idx]; + let text; + if (Array.isArray(excluded.content) && excluded.content.some((block) => typeof block === "string" || block.type === "text")) { + const textBlock = excluded.content.find((block) => block.type === "text" && block.text); + text = textBlock?.text; + } else if (typeof excluded.content === "string") { + text = excluded.content; + } + if (text) { + const splitTexts = await textSplitter(text); + const numSplits = splitTexts.length; + if (partialStrategy === "last") { + splitTexts.reverse(); + } + for (let _ = 0; _ < numSplits - 1; _ += 1) { + splitTexts.pop(); + excluded.content = splitTexts.join(""); + if (await tokenCounter([...messagesCopy.slice(0, idx), excluded]) <= maxTokens) { + if (partialStrategy === "last") { + excluded.content = [...splitTexts].reverse().join(""); + } + messagesCopy = [...messagesCopy.slice(0, idx), excluded]; + idx += 1; + break; + } + } + } + } + } + if (endOn) { + const endOnArr = Array.isArray(endOn) ? endOn : [endOn]; + while (idx > 0 && !_isMessageType(messagesCopy[idx - 1], endOnArr)) { + idx -= 1; + } + } + return messagesCopy.slice(0, idx); +} +async function _lastMaxTokens(messages, options) { + const { allowPartial = false, includeSystem = false, endOn, startOn, ...rest } = options; + let messagesCopy = messages.map((message) => { + const fields = Object.fromEntries(Object.entries(message).filter(([k]) => k !== "type" && !k.startsWith("lc_"))); + return _switchTypeToMessage(message.getType(), fields, isBaseMessageChunk(message)); + }); + if (endOn) { + const endOnArr = Array.isArray(endOn) ? endOn : [endOn]; + while (messagesCopy.length > 0 && !_isMessageType(messagesCopy[messagesCopy.length - 1], endOnArr)) { + messagesCopy = messagesCopy.slice(0, -1); + } + } + const swappedSystem = includeSystem && messagesCopy[0]?.getType() === "system"; + let reversed_ = swappedSystem ? messagesCopy.slice(0, 1).concat(messagesCopy.slice(1).reverse()) : messagesCopy.reverse(); + reversed_ = await _firstMaxTokens(reversed_, { + ...rest, + partialStrategy: allowPartial ? "last" : void 0, + endOn: startOn + }); + if (swappedSystem) { + return [reversed_[0], ...reversed_.slice(1).reverse()]; + } else { + return reversed_.reverse(); + } +} +function _switchTypeToMessage(messageType, fields, returnChunk) { + let chunk; + let msg; + switch (messageType) { + case "human": + if (returnChunk) { + chunk = new HumanMessageChunk(fields); + } else { + msg = new HumanMessage(fields); + } + break; + case "ai": + if (returnChunk) { + let aiChunkFields = { + ...fields + }; + if ("tool_calls" in aiChunkFields) { + aiChunkFields = { + ...aiChunkFields, + tool_call_chunks: aiChunkFields.tool_calls?.map((tc) => ({ + ...tc, + type: "tool_call_chunk", + index: void 0, + args: JSON.stringify(tc.args) + })) + }; + } + chunk = new AIMessageChunk(aiChunkFields); + } else { + msg = new AIMessage(fields); + } + break; + case "system": + if (returnChunk) { + chunk = new SystemMessageChunk(fields); + } else { + msg = new SystemMessage(fields); + } + break; + case "developer": + if (returnChunk) { + chunk = new SystemMessageChunk({ + ...fields, + additional_kwargs: { + ...fields.additional_kwargs, + __openai_role__: "developer" + } + }); + } else { + msg = new SystemMessage({ + ...fields, + additional_kwargs: { + ...fields.additional_kwargs, + __openai_role__: "developer" + } + }); + } + break; + case "tool": + if ("tool_call_id" in fields) { + if (returnChunk) { + chunk = new ToolMessageChunk(fields); + } else { + msg = new ToolMessage(fields); + } + } else { + throw new Error("Can not convert ToolMessage to ToolMessageChunk if 'tool_call_id' field is not defined."); + } + break; + case "function": + if (returnChunk) { + chunk = new FunctionMessageChunk(fields); + } else { + if (!fields.name) { + throw new Error("FunctionMessage must have a 'name' field"); + } + msg = new FunctionMessage(fields); + } + break; + case "generic": + if ("role" in fields) { + if (returnChunk) { + chunk = new ChatMessageChunk(fields); + } else { + msg = new ChatMessage(fields); + } + } else { + throw new Error("Can not convert ChatMessage to ChatMessageChunk if 'role' field is not defined."); + } + break; + default: + throw new Error(`Unrecognized message type ${messageType}`); + } + if (returnChunk && chunk) { + return chunk; + } + if (msg) { + return msg; + } + throw new Error(`Unrecognized message type ${messageType}`); +} +function _chunkToMsg(chunk) { + const chunkType = chunk.getType(); + let msg; + const fields = Object.fromEntries(Object.entries(chunk).filter(([k]) => !["type", "tool_call_chunks"].includes(k) && !k.startsWith("lc_"))); + if (chunkType in _MSG_CHUNK_MAP) { + msg = _switchTypeToMessage(chunkType, fields); + } + if (!msg) { + throw new Error(`Unrecognized message chunk class ${chunkType}. Supported classes are ${Object.keys(_MSG_CHUNK_MAP)}`); + } + return msg; +} +function defaultTextSplitter(text) { + const splits = text.split("\n"); + return Promise.resolve([ + ...splits.slice(0, -1).map((s) => `${s} +`), + splits[splits.length - 1] + ]); +} +var _isMessageType, _MSG_CHUNK_MAP; +var init_transformers = __esm({ + "node_modules/@langchain/core/dist/messages/transformers.js"() { + init_base4(); + init_ai(); + init_base(); + init_chat(); + init_function(); + init_human(); + init_modifier(); + init_system(); + init_tool(); + init_utils2(); + _isMessageType = (msg, types) => { + const typesAsStrings = [ + ...new Set(types?.map((t) => { + if (typeof t === "string") { + return t; + } + const instantiatedMsgClass = new t({}); + if (!("getType" in instantiatedMsgClass) || typeof instantiatedMsgClass.getType !== "function") { + throw new Error("Invalid type provided."); + } + return instantiatedMsgClass.getType(); + })) + ]; + const msgType = msg.getType(); + return typesAsStrings.some((t) => t === msgType); + }; + _MSG_CHUNK_MAP = { + human: { + message: HumanMessage, + messageChunk: HumanMessageChunk + }, + ai: { + message: AIMessage, + messageChunk: AIMessageChunk + }, + system: { + message: SystemMessage, + messageChunk: SystemMessageChunk + }, + developer: { + message: SystemMessage, + messageChunk: SystemMessageChunk + }, + tool: { + message: ToolMessage, + messageChunk: ToolMessageChunk + }, + function: { + message: FunctionMessage, + messageChunk: FunctionMessageChunk + }, + generic: { + message: ChatMessage, + messageChunk: ChatMessageChunk + }, + remove: { + message: RemoveMessage, + messageChunk: RemoveMessage + // RemoveMessage does not have a chunk class. + } + }; + } +}); + +// node_modules/@langchain/core/dist/messages/index.js +var messages_exports = {}; +__export(messages_exports, { + AIMessage: () => AIMessage, + AIMessageChunk: () => AIMessageChunk, + BaseMessage: () => BaseMessage, + BaseMessageChunk: () => BaseMessageChunk, + ChatMessage: () => ChatMessage, + ChatMessageChunk: () => ChatMessageChunk, + FunctionMessage: () => FunctionMessage, + FunctionMessageChunk: () => FunctionMessageChunk, + HumanMessage: () => HumanMessage, + HumanMessageChunk: () => HumanMessageChunk, + RemoveMessage: () => RemoveMessage, + SystemMessage: () => SystemMessage, + SystemMessageChunk: () => SystemMessageChunk, + ToolMessage: () => ToolMessage, + ToolMessageChunk: () => ToolMessageChunk, + _isMessageFieldWithRole: () => _isMessageFieldWithRole, + _mergeDicts: () => _mergeDicts, + _mergeLists: () => _mergeLists, + _mergeObj: () => _mergeObj, + _mergeStatus: () => _mergeStatus, + coerceMessageLikeToMessage: () => coerceMessageLikeToMessage, + convertToChunk: () => convertToChunk, + convertToOpenAIImageBlock: () => convertToOpenAIImageBlock, + convertToProviderContentBlock: () => convertToProviderContentBlock, + defaultTextSplitter: () => defaultTextSplitter, + filterMessages: () => filterMessages, + getBufferString: () => getBufferString, + isAIMessage: () => isAIMessage, + isAIMessageChunk: () => isAIMessageChunk, + isBase64ContentBlock: () => isBase64ContentBlock, + isBaseMessage: () => isBaseMessage, + isBaseMessageChunk: () => isBaseMessageChunk, + isChatMessage: () => isChatMessage, + isChatMessageChunk: () => isChatMessageChunk, + isDataContentBlock: () => isDataContentBlock, + isFunctionMessage: () => isFunctionMessage, + isFunctionMessageChunk: () => isFunctionMessageChunk, + isHumanMessage: () => isHumanMessage, + isHumanMessageChunk: () => isHumanMessageChunk, + isIDContentBlock: () => isIDContentBlock, + isOpenAIToolCallArray: () => isOpenAIToolCallArray, + isPlainTextContentBlock: () => isPlainTextContentBlock, + isSystemMessage: () => isSystemMessage, + isSystemMessageChunk: () => isSystemMessageChunk, + isToolMessage: () => isToolMessage, + isToolMessageChunk: () => isToolMessageChunk, + isURLContentBlock: () => isURLContentBlock, + mapChatMessagesToStoredMessages: () => mapChatMessagesToStoredMessages, + mapStoredMessageToChatMessage: () => mapStoredMessageToChatMessage, + mapStoredMessagesToChatMessages: () => mapStoredMessagesToChatMessages, + mergeContent: () => mergeContent, + mergeMessageRuns: () => mergeMessageRuns, + parseBase64DataUrl: () => parseBase64DataUrl, + parseMimeType: () => parseMimeType, + trimMessages: () => trimMessages +}); +var init_messages2 = __esm({ + "node_modules/@langchain/core/dist/messages/index.js"() { + init_ai(); + init_base(); + init_chat(); + init_function(); + init_human(); + init_system(); + init_utils2(); + init_transformers(); + init_modifier(); + init_content_blocks(); + init_tool(); + } +}); + +// node_modules/@langchain/core/dist/prompt_values.js +var prompt_values_exports = {}; +__export(prompt_values_exports, { + BasePromptValue: () => BasePromptValue, + ChatPromptValue: () => ChatPromptValue, + ImagePromptValue: () => ImagePromptValue, + StringPromptValue: () => StringPromptValue +}); +var BasePromptValue, StringPromptValue, ChatPromptValue, ImagePromptValue; +var init_prompt_values = __esm({ + "node_modules/@langchain/core/dist/prompt_values.js"() { + init_serializable(); + init_human(); + init_utils2(); + BasePromptValue = class extends Serializable { + }; + StringPromptValue = class extends BasePromptValue { + static lc_name() { + return "StringPromptValue"; + } + constructor(value) { + super({ value }); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain_core", "prompt_values"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "value", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.value = value; + } + toString() { + return this.value; + } + toChatMessages() { + return [new HumanMessage(this.value)]; + } + }; + ChatPromptValue = class extends BasePromptValue { + static lc_name() { + return "ChatPromptValue"; + } + constructor(fields) { + if (Array.isArray(fields)) { + fields = { messages: fields }; + } + super(fields); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain_core", "prompt_values"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "messages", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.messages = fields.messages; + } + toString() { + return getBufferString(this.messages); + } + toChatMessages() { + return this.messages; + } + }; + ImagePromptValue = class extends BasePromptValue { + static lc_name() { + return "ImagePromptValue"; + } + constructor(fields) { + if (!("imageUrl" in fields)) { + fields = { imageUrl: fields }; + } + super(fields); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain_core", "prompt_values"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "imageUrl", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "value", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.imageUrl = fields.imageUrl; + } + toString() { + return this.imageUrl.url; + } + toChatMessages() { + return [ + new HumanMessage({ + content: [ + { + type: "image_url", + image_url: { + detail: this.imageUrl.detail, + url: this.imageUrl.url + } + } + ] + }) + ]; + } + }; + } +}); + +// node_modules/base64-js/index.js +var require_base64_js = __commonJS({ + "node_modules/base64-js/index.js"(exports) { + "use strict"; + exports.byteLength = byteLength; + exports.toByteArray = toByteArray; + exports.fromByteArray = fromByteArray; + var lookup3 = []; + var revLookup = []; + var Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array; + var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + for (i = 0, len = code.length; i < len; ++i) { + lookup3[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; + } + var i; + var len; + revLookup["-".charCodeAt(0)] = 62; + revLookup["_".charCodeAt(0)] = 63; + function getLens(b64) { + var len2 = b64.length; + if (len2 % 4 > 0) { + throw new Error("Invalid string. Length must be a multiple of 4"); + } + var validLen = b64.indexOf("="); + if (validLen === -1) validLen = len2; + var placeHoldersLen = validLen === len2 ? 0 : 4 - validLen % 4; + return [validLen, placeHoldersLen]; + } + function byteLength(b64) { + var lens = getLens(b64); + var validLen = lens[0]; + var placeHoldersLen = lens[1]; + return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; + } + function _byteLength(b64, validLen, placeHoldersLen) { + return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; + } + function toByteArray(b64) { + var tmp; + var lens = getLens(b64); + var validLen = lens[0]; + var placeHoldersLen = lens[1]; + var arr3 = new Arr(_byteLength(b64, validLen, placeHoldersLen)); + var curByte = 0; + var len2 = placeHoldersLen > 0 ? validLen - 4 : validLen; + var i2; + for (i2 = 0; i2 < len2; i2 += 4) { + tmp = revLookup[b64.charCodeAt(i2)] << 18 | revLookup[b64.charCodeAt(i2 + 1)] << 12 | revLookup[b64.charCodeAt(i2 + 2)] << 6 | revLookup[b64.charCodeAt(i2 + 3)]; + arr3[curByte++] = tmp >> 16 & 255; + arr3[curByte++] = tmp >> 8 & 255; + arr3[curByte++] = tmp & 255; + } + if (placeHoldersLen === 2) { + tmp = revLookup[b64.charCodeAt(i2)] << 2 | revLookup[b64.charCodeAt(i2 + 1)] >> 4; + arr3[curByte++] = tmp & 255; + } + if (placeHoldersLen === 1) { + tmp = revLookup[b64.charCodeAt(i2)] << 10 | revLookup[b64.charCodeAt(i2 + 1)] << 4 | revLookup[b64.charCodeAt(i2 + 2)] >> 2; + arr3[curByte++] = tmp >> 8 & 255; + arr3[curByte++] = tmp & 255; + } + return arr3; + } + function tripletToBase64(num) { + return lookup3[num >> 18 & 63] + lookup3[num >> 12 & 63] + lookup3[num >> 6 & 63] + lookup3[num & 63]; + } + function encodeChunk(uint8, start, end) { + var tmp; + var output = []; + for (var i2 = start; i2 < end; i2 += 3) { + tmp = (uint8[i2] << 16 & 16711680) + (uint8[i2 + 1] << 8 & 65280) + (uint8[i2 + 2] & 255); + output.push(tripletToBase64(tmp)); + } + return output.join(""); + } + function fromByteArray(uint8) { + var tmp; + var len2 = uint8.length; + var extraBytes = len2 % 3; + var parts = []; + var maxChunkLength = 16383; + for (var i2 = 0, len22 = len2 - extraBytes; i2 < len22; i2 += maxChunkLength) { + parts.push(encodeChunk(uint8, i2, i2 + maxChunkLength > len22 ? len22 : i2 + maxChunkLength)); + } + if (extraBytes === 1) { + tmp = uint8[len2 - 1]; + parts.push( + lookup3[tmp >> 2] + lookup3[tmp << 4 & 63] + "==" + ); + } else if (extraBytes === 2) { + tmp = (uint8[len2 - 2] << 8) + uint8[len2 - 1]; + parts.push( + lookup3[tmp >> 10] + lookup3[tmp >> 4 & 63] + lookup3[tmp << 2 & 63] + "=" + ); + } + return parts.join(""); + } + } +}); + +// node_modules/@langchain/core/dist/prompts/string.js +var BaseStringPromptTemplate; +var init_string2 = __esm({ + "node_modules/@langchain/core/dist/prompts/string.js"() { + init_prompt_values(); + init_base5(); + BaseStringPromptTemplate = class extends BasePromptTemplate { + /** + * Formats the prompt given the input values and returns a formatted + * prompt value. + * @param values The input values to format the prompt. + * @returns A Promise that resolves to a formatted prompt value. + */ + async formatPromptValue(values) { + const formattedPrompt = await this.format(values); + return new StringPromptValue(formattedPrompt); + } + }; + } +}); + +// node_modules/mustache/mustache.mjs +function isFunction(object) { + return typeof object === "function"; +} +function typeStr(obj) { + return isArray(obj) ? "array" : typeof obj; +} +function escapeRegExp(string) { + return string.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&"); +} +function hasProperty(obj, propName) { + return obj != null && typeof obj === "object" && propName in obj; +} +function primitiveHasOwnProperty(primitive, propName) { + return primitive != null && typeof primitive !== "object" && primitive.hasOwnProperty && primitive.hasOwnProperty(propName); +} +function testRegExp(re, string) { + return regExpTest.call(re, string); +} +function isWhitespace(string) { + return !testRegExp(nonSpaceRe, string); +} +function escapeHtml(string) { + return String(string).replace(/[&<>"'`=\/]/g, function fromEntityMap(s) { + return entityMap[s]; + }); +} +function parseTemplate(template, tags) { + if (!template) + return []; + var lineHasNonSpace = false; + var sections = []; + var tokens = []; + var spaces = []; + var hasTag = false; + var nonSpace = false; + var indentation = ""; + var tagIndex = 0; + function stripSpace() { + if (hasTag && !nonSpace) { + while (spaces.length) + delete tokens[spaces.pop()]; + } else { + spaces = []; + } + hasTag = false; + nonSpace = false; + } + var openingTagRe, closingTagRe, closingCurlyRe; + function compileTags(tagsToCompile) { + if (typeof tagsToCompile === "string") + tagsToCompile = tagsToCompile.split(spaceRe, 2); + if (!isArray(tagsToCompile) || tagsToCompile.length !== 2) + throw new Error("Invalid tags: " + tagsToCompile); + openingTagRe = new RegExp(escapeRegExp(tagsToCompile[0]) + "\\s*"); + closingTagRe = new RegExp("\\s*" + escapeRegExp(tagsToCompile[1])); + closingCurlyRe = new RegExp("\\s*" + escapeRegExp("}" + tagsToCompile[1])); + } + compileTags(tags || mustache.tags); + var scanner = new Scanner(template); + var start, type, value, chr, token, openSection; + while (!scanner.eos()) { + start = scanner.pos; + value = scanner.scanUntil(openingTagRe); + if (value) { + for (var i = 0, valueLength = value.length; i < valueLength; ++i) { + chr = value.charAt(i); + if (isWhitespace(chr)) { + spaces.push(tokens.length); + indentation += chr; + } else { + nonSpace = true; + lineHasNonSpace = true; + indentation += " "; + } + tokens.push(["text", chr, start, start + 1]); + start += 1; + if (chr === "\n") { + stripSpace(); + indentation = ""; + tagIndex = 0; + lineHasNonSpace = false; + } + } + } + if (!scanner.scan(openingTagRe)) + break; + hasTag = true; + type = scanner.scan(tagRe) || "name"; + scanner.scan(whiteRe); + if (type === "=") { + value = scanner.scanUntil(equalsRe); + scanner.scan(equalsRe); + scanner.scanUntil(closingTagRe); + } else if (type === "{") { + value = scanner.scanUntil(closingCurlyRe); + scanner.scan(curlyRe); + scanner.scanUntil(closingTagRe); + type = "&"; + } else { + value = scanner.scanUntil(closingTagRe); + } + if (!scanner.scan(closingTagRe)) + throw new Error("Unclosed tag at " + scanner.pos); + if (type == ">") { + token = [type, value, start, scanner.pos, indentation, tagIndex, lineHasNonSpace]; + } else { + token = [type, value, start, scanner.pos]; + } + tagIndex++; + tokens.push(token); + if (type === "#" || type === "^") { + sections.push(token); + } else if (type === "/") { + openSection = sections.pop(); + if (!openSection) + throw new Error('Unopened section "' + value + '" at ' + start); + if (openSection[1] !== value) + throw new Error('Unclosed section "' + openSection[1] + '" at ' + start); + } else if (type === "name" || type === "{" || type === "&") { + nonSpace = true; + } else if (type === "=") { + compileTags(value); + } + } + stripSpace(); + openSection = sections.pop(); + if (openSection) + throw new Error('Unclosed section "' + openSection[1] + '" at ' + scanner.pos); + return nestTokens(squashTokens(tokens)); +} +function squashTokens(tokens) { + var squashedTokens = []; + var token, lastToken; + for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) { + token = tokens[i]; + if (token) { + if (token[0] === "text" && lastToken && lastToken[0] === "text") { + lastToken[1] += token[1]; + lastToken[3] = token[3]; + } else { + squashedTokens.push(token); + lastToken = token; + } + } + } + return squashedTokens; +} +function nestTokens(tokens) { + var nestedTokens = []; + var collector = nestedTokens; + var sections = []; + var token, section; + for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) { + token = tokens[i]; + switch (token[0]) { + case "#": + case "^": + collector.push(token); + sections.push(token); + collector = token[4] = []; + break; + case "/": + section = sections.pop(); + section[5] = token[2]; + collector = sections.length > 0 ? sections[sections.length - 1][4] : nestedTokens; + break; + default: + collector.push(token); + } + } + return nestedTokens; +} +function Scanner(string) { + this.string = string; + this.tail = string; + this.pos = 0; +} +function Context(view2, parentContext) { + this.view = view2; + this.cache = { ".": this.view }; + this.parent = parentContext; +} +function Writer() { + this.templateCache = { + _cache: {}, + set: function set(key, value) { + this._cache[key] = value; + }, + get: function get(key) { + return this._cache[key]; + }, + clear: function clear() { + this._cache = {}; + } + }; +} +var objectToString, isArray, regExpTest, nonSpaceRe, entityMap, whiteRe, spaceRe, equalsRe, curlyRe, tagRe, mustache, defaultWriter, mustache_default; +var init_mustache = __esm({ + "node_modules/mustache/mustache.mjs"() { + objectToString = Object.prototype.toString; + isArray = Array.isArray || function isArrayPolyfill(object) { + return objectToString.call(object) === "[object Array]"; + }; + regExpTest = RegExp.prototype.test; + nonSpaceRe = /\S/; + entityMap = { + "&": "&", + "<": "<", + ">": ">", + '"': """, + "'": "'", + "/": "/", + "`": "`", + "=": "=" + }; + whiteRe = /\s*/; + spaceRe = /\s+/; + equalsRe = /\s*=/; + curlyRe = /\s*\}/; + tagRe = /#|\^|\/|>|\{|&|=|!/; + Scanner.prototype.eos = function eos() { + return this.tail === ""; + }; + Scanner.prototype.scan = function scan(re) { + var match = this.tail.match(re); + if (!match || match.index !== 0) + return ""; + var string = match[0]; + this.tail = this.tail.substring(string.length); + this.pos += string.length; + return string; + }; + Scanner.prototype.scanUntil = function scanUntil(re) { + var index2 = this.tail.search(re), match; + switch (index2) { + case -1: + match = this.tail; + this.tail = ""; + break; + case 0: + match = ""; + break; + default: + match = this.tail.substring(0, index2); + this.tail = this.tail.substring(index2); + } + this.pos += match.length; + return match; + }; + Context.prototype.push = function push(view2) { + return new Context(view2, this); + }; + Context.prototype.lookup = function lookup(name) { + var cache2 = this.cache; + var value; + if (cache2.hasOwnProperty(name)) { + value = cache2[name]; + } else { + var context = this, intermediateValue, names, index2, lookupHit = false; + while (context) { + if (name.indexOf(".") > 0) { + intermediateValue = context.view; + names = name.split("."); + index2 = 0; + while (intermediateValue != null && index2 < names.length) { + if (index2 === names.length - 1) + lookupHit = hasProperty(intermediateValue, names[index2]) || primitiveHasOwnProperty(intermediateValue, names[index2]); + intermediateValue = intermediateValue[names[index2++]]; + } + } else { + intermediateValue = context.view[name]; + lookupHit = hasProperty(context.view, name); + } + if (lookupHit) { + value = intermediateValue; + break; + } + context = context.parent; + } + cache2[name] = value; + } + if (isFunction(value)) + value = value.call(this.view); + return value; + }; + Writer.prototype.clearCache = function clearCache() { + if (typeof this.templateCache !== "undefined") { + this.templateCache.clear(); + } + }; + Writer.prototype.parse = function parse3(template, tags) { + var cache2 = this.templateCache; + var cacheKey = template + ":" + (tags || mustache.tags).join(":"); + var isCacheEnabled = typeof cache2 !== "undefined"; + var tokens = isCacheEnabled ? cache2.get(cacheKey) : void 0; + if (tokens == void 0) { + tokens = parseTemplate(template, tags); + isCacheEnabled && cache2.set(cacheKey, tokens); + } + return tokens; + }; + Writer.prototype.render = function render(template, view2, partials, config2) { + var tags = this.getConfigTags(config2); + var tokens = this.parse(template, tags); + var context = view2 instanceof Context ? view2 : new Context(view2, void 0); + return this.renderTokens(tokens, context, partials, template, config2); + }; + Writer.prototype.renderTokens = function renderTokens(tokens, context, partials, originalTemplate, config2) { + var buffer = ""; + var token, symbol, value; + for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) { + value = void 0; + token = tokens[i]; + symbol = token[0]; + if (symbol === "#") value = this.renderSection(token, context, partials, originalTemplate, config2); + else if (symbol === "^") value = this.renderInverted(token, context, partials, originalTemplate, config2); + else if (symbol === ">") value = this.renderPartial(token, context, partials, config2); + else if (symbol === "&") value = this.unescapedValue(token, context); + else if (symbol === "name") value = this.escapedValue(token, context, config2); + else if (symbol === "text") value = this.rawValue(token); + if (value !== void 0) + buffer += value; + } + return buffer; + }; + Writer.prototype.renderSection = function renderSection(token, context, partials, originalTemplate, config2) { + var self2 = this; + var buffer = ""; + var value = context.lookup(token[1]); + function subRender(template) { + return self2.render(template, context, partials, config2); + } + if (!value) return; + if (isArray(value)) { + for (var j = 0, valueLength = value.length; j < valueLength; ++j) { + buffer += this.renderTokens(token[4], context.push(value[j]), partials, originalTemplate, config2); + } + } else if (typeof value === "object" || typeof value === "string" || typeof value === "number") { + buffer += this.renderTokens(token[4], context.push(value), partials, originalTemplate, config2); + } else if (isFunction(value)) { + if (typeof originalTemplate !== "string") + throw new Error("Cannot use higher-order sections without the original template"); + value = value.call(context.view, originalTemplate.slice(token[3], token[5]), subRender); + if (value != null) + buffer += value; + } else { + buffer += this.renderTokens(token[4], context, partials, originalTemplate, config2); + } + return buffer; + }; + Writer.prototype.renderInverted = function renderInverted(token, context, partials, originalTemplate, config2) { + var value = context.lookup(token[1]); + if (!value || isArray(value) && value.length === 0) + return this.renderTokens(token[4], context, partials, originalTemplate, config2); + }; + Writer.prototype.indentPartial = function indentPartial(partial2, indentation, lineHasNonSpace) { + var filteredIndentation = indentation.replace(/[^ \t]/g, ""); + var partialByNl = partial2.split("\n"); + for (var i = 0; i < partialByNl.length; i++) { + if (partialByNl[i].length && (i > 0 || !lineHasNonSpace)) { + partialByNl[i] = filteredIndentation + partialByNl[i]; + } + } + return partialByNl.join("\n"); + }; + Writer.prototype.renderPartial = function renderPartial(token, context, partials, config2) { + if (!partials) return; + var tags = this.getConfigTags(config2); + var value = isFunction(partials) ? partials(token[1]) : partials[token[1]]; + if (value != null) { + var lineHasNonSpace = token[6]; + var tagIndex = token[5]; + var indentation = token[4]; + var indentedValue = value; + if (tagIndex == 0 && indentation) { + indentedValue = this.indentPartial(value, indentation, lineHasNonSpace); + } + var tokens = this.parse(indentedValue, tags); + return this.renderTokens(tokens, context, partials, indentedValue, config2); + } + }; + Writer.prototype.unescapedValue = function unescapedValue(token, context) { + var value = context.lookup(token[1]); + if (value != null) + return value; + }; + Writer.prototype.escapedValue = function escapedValue(token, context, config2) { + var escape = this.getConfigEscape(config2) || mustache.escape; + var value = context.lookup(token[1]); + if (value != null) + return typeof value === "number" && escape === mustache.escape ? String(value) : escape(value); + }; + Writer.prototype.rawValue = function rawValue(token) { + return token[1]; + }; + Writer.prototype.getConfigTags = function getConfigTags(config2) { + if (isArray(config2)) { + return config2; + } else if (config2 && typeof config2 === "object") { + return config2.tags; + } else { + return void 0; + } + }; + Writer.prototype.getConfigEscape = function getConfigEscape(config2) { + if (config2 && typeof config2 === "object" && !isArray(config2)) { + return config2.escape; + } else { + return void 0; + } + }; + mustache = { + name: "mustache.js", + version: "4.2.0", + tags: ["{{", "}}"], + clearCache: void 0, + escape: void 0, + parse: void 0, + render: void 0, + Scanner: void 0, + Context: void 0, + Writer: void 0, + /** + * Allows a user to override the default caching strategy, by providing an + * object with set, get and clear methods. This can also be used to disable + * the cache by setting it to the literal `undefined`. + */ + set templateCache(cache2) { + defaultWriter.templateCache = cache2; + }, + /** + * Gets the default or overridden caching object from the default writer. + */ + get templateCache() { + return defaultWriter.templateCache; + } + }; + defaultWriter = new Writer(); + mustache.clearCache = function clearCache2() { + return defaultWriter.clearCache(); + }; + mustache.parse = function parse4(template, tags) { + return defaultWriter.parse(template, tags); + }; + mustache.render = function render2(template, view2, partials, config2) { + if (typeof template !== "string") { + throw new TypeError('Invalid template! Template should be a "string" but "' + typeStr(template) + '" was given as the first argument for mustache#render(template, view, partials)'); + } + return defaultWriter.render(template, view2, partials, config2); + }; + mustache.escape = escapeHtml; + mustache.Scanner = Scanner; + mustache.Context = Context; + mustache.Writer = Writer; + mustache_default = mustache; + } +}); + +// node_modules/@langchain/core/dist/prompts/template.js +function configureMustache() { + mustache_default.escape = (text) => text; +} +var parseFString, mustacheTemplateToNodes, parseMustache, interpolateFString, interpolateMustache, DEFAULT_FORMATTER_MAPPING, DEFAULT_PARSER_MAPPING, renderTemplate, parseTemplate2, checkValidTemplate; +var init_template = __esm({ + "node_modules/@langchain/core/dist/prompts/template.js"() { + init_mustache(); + init_errors(); + parseFString = (template) => { + const chars = template.split(""); + const nodes = []; + const nextBracket = (bracket, start) => { + for (let i2 = start; i2 < chars.length; i2 += 1) { + if (bracket.includes(chars[i2])) { + return i2; + } + } + return -1; + }; + let i = 0; + while (i < chars.length) { + if (chars[i] === "{" && i + 1 < chars.length && chars[i + 1] === "{") { + nodes.push({ type: "literal", text: "{" }); + i += 2; + } else if (chars[i] === "}" && i + 1 < chars.length && chars[i + 1] === "}") { + nodes.push({ type: "literal", text: "}" }); + i += 2; + } else if (chars[i] === "{") { + const j = nextBracket("}", i); + if (j < 0) { + throw new Error("Unclosed '{' in template."); + } + nodes.push({ + type: "variable", + name: chars.slice(i + 1, j).join("") + }); + i = j + 1; + } else if (chars[i] === "}") { + throw new Error("Single '}' in template."); + } else { + const next = nextBracket("{}", i); + const text = (next < 0 ? chars.slice(i) : chars.slice(i, next)).join(""); + nodes.push({ type: "literal", text }); + i = next < 0 ? chars.length : next; + } + } + return nodes; + }; + mustacheTemplateToNodes = (template) => { + const nodes = []; + for (const temp of template) { + if (temp[0] === "name") { + const name = temp[1].includes(".") ? temp[1].split(".")[0] : temp[1]; + nodes.push({ type: "variable", name }); + } else if (["#", "&", "^", ">"].includes(temp[0])) { + nodes.push({ type: "variable", name: temp[1] }); + if (temp[0] === "#" && temp.length > 4 && Array.isArray(temp[4])) { + const nestedNodes = mustacheTemplateToNodes(temp[4]); + nodes.push(...nestedNodes); + } + } else { + nodes.push({ type: "literal", text: temp[1] }); + } + } + return nodes; + }; + parseMustache = (template) => { + configureMustache(); + const parsed = mustache_default.parse(template); + return mustacheTemplateToNodes(parsed); + }; + interpolateFString = (template, values) => { + return parseFString(template).reduce((res, node) => { + if (node.type === "variable") { + if (node.name in values) { + const stringValue = typeof values[node.name] === "string" ? values[node.name] : JSON.stringify(values[node.name]); + return res + stringValue; + } + throw new Error(`(f-string) Missing value for input ${node.name}`); + } + return res + node.text; + }, ""); + }; + interpolateMustache = (template, values) => { + configureMustache(); + return mustache_default.render(template, values); + }; + DEFAULT_FORMATTER_MAPPING = { + "f-string": interpolateFString, + mustache: interpolateMustache + }; + DEFAULT_PARSER_MAPPING = { + "f-string": parseFString, + mustache: parseMustache + }; + renderTemplate = (template, templateFormat, inputValues) => { + try { + return DEFAULT_FORMATTER_MAPPING[templateFormat](template, inputValues); + } catch (e) { + const error = addLangChainErrorFields(e, "INVALID_PROMPT_INPUT"); + throw error; + } + }; + parseTemplate2 = (template, templateFormat) => DEFAULT_PARSER_MAPPING[templateFormat](template); + checkValidTemplate = (template, templateFormat, inputVariables) => { + if (!(templateFormat in DEFAULT_FORMATTER_MAPPING)) { + const validFormats = Object.keys(DEFAULT_FORMATTER_MAPPING); + throw new Error(`Invalid template format. Got \`${templateFormat}\`; + should be one of ${validFormats}`); + } + try { + const dummyInputs = inputVariables.reduce((acc, v) => { + acc[v] = "foo"; + return acc; + }, {}); + if (Array.isArray(template)) { + template.forEach((message) => { + if (message.type === "text") { + renderTemplate(message.text, templateFormat, dummyInputs); + } else if (message.type === "image_url") { + if (typeof message.image_url === "string") { + renderTemplate(message.image_url, templateFormat, dummyInputs); + } else { + const imageUrl = message.image_url.url; + renderTemplate(imageUrl, templateFormat, dummyInputs); + } + } else { + throw new Error(`Invalid message template received. ${JSON.stringify(message, null, 2)}`); + } + }); + } else { + renderTemplate(template, templateFormat, dummyInputs); + } + } catch (e) { + throw new Error(`Invalid prompt schema: ${e.message}`); + } + }; + } +}); + +// node_modules/@langchain/core/dist/prompts/prompt.js +var prompt_exports = {}; +__export(prompt_exports, { + PromptTemplate: () => PromptTemplate +}); +var PromptTemplate; +var init_prompt = __esm({ + "node_modules/@langchain/core/dist/prompts/prompt.js"() { + init_string2(); + init_template(); + PromptTemplate = class _PromptTemplate extends BaseStringPromptTemplate { + static lc_name() { + return "PromptTemplate"; + } + constructor(input) { + super(input); + Object.defineProperty(this, "template", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "templateFormat", { + enumerable: true, + configurable: true, + writable: true, + value: "f-string" + }); + Object.defineProperty(this, "validateTemplate", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "additionalContentFields", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + if (input.templateFormat === "mustache" && input.validateTemplate === void 0) { + this.validateTemplate = false; + } + Object.assign(this, input); + if (this.validateTemplate) { + if (this.templateFormat === "mustache") { + throw new Error("Mustache templates cannot be validated."); + } + let totalInputVariables = this.inputVariables; + if (this.partialVariables) { + totalInputVariables = totalInputVariables.concat(Object.keys(this.partialVariables)); + } + checkValidTemplate(this.template, this.templateFormat, totalInputVariables); + } + } + _getPromptType() { + return "prompt"; + } + /** + * Formats the prompt template with the provided values. + * @param values The values to be used to format the prompt template. + * @returns A promise that resolves to a string which is the formatted prompt. + */ + async format(values) { + const allValues = await this.mergePartialAndUserVariables(values); + return renderTemplate(this.template, this.templateFormat, allValues); + } + /** + * Take examples in list format with prefix and suffix to create a prompt. + * + * Intended to be used a a way to dynamically create a prompt from examples. + * + * @param examples - List of examples to use in the prompt. + * @param suffix - String to go after the list of examples. Should generally set up the user's input. + * @param inputVariables - A list of variable names the final prompt template will expect + * @param exampleSeparator - The separator to use in between examples + * @param prefix - String that should go before any examples. Generally includes examples. + * + * @returns The final prompt template generated. + */ + static fromExamples(examples, suffix, inputVariables, exampleSeparator = "\n\n", prefix = "") { + const template = [prefix, ...examples, suffix].join(exampleSeparator); + return new _PromptTemplate({ + inputVariables, + template + }); + } + static fromTemplate(template, options) { + const { templateFormat = "f-string", ...rest } = options ?? {}; + const names = /* @__PURE__ */ new Set(); + parseTemplate2(template, templateFormat).forEach((node) => { + if (node.type === "variable") { + names.add(node.name); + } + }); + return new _PromptTemplate({ + // Rely on extracted types + // eslint-disable-next-line @typescript-eslint/no-explicit-any + inputVariables: [...names], + templateFormat, + template, + ...rest + }); + } + /** + * Partially applies values to the prompt template. + * @param values The values to be partially applied to the prompt template. + * @returns A new instance of PromptTemplate with the partially applied values. + */ + async partial(values) { + const newInputVariables = this.inputVariables.filter((iv) => !(iv in values)); + const newPartialVariables = { + ...this.partialVariables ?? {}, + ...values + }; + const promptDict = { + ...this, + inputVariables: newInputVariables, + partialVariables: newPartialVariables + }; + return new _PromptTemplate(promptDict); + } + serialize() { + if (this.outputParser !== void 0) { + throw new Error("Cannot serialize a prompt template with an output parser"); + } + return { + _type: this._getPromptType(), + input_variables: this.inputVariables, + template: this.template, + template_format: this.templateFormat + }; + } + static async deserialize(data) { + if (!data.template) { + throw new Error("Prompt template must have a template"); + } + const res = new _PromptTemplate({ + inputVariables: data.input_variables, + template: data.template, + templateFormat: data.template_format + }); + return res; + } + }; + } +}); + +// node_modules/@langchain/core/dist/prompts/image.js +var ImagePromptTemplate; +var init_image = __esm({ + "node_modules/@langchain/core/dist/prompts/image.js"() { + init_prompt_values(); + init_base5(); + init_template(); + ImagePromptTemplate = class _ImagePromptTemplate extends BasePromptTemplate { + static lc_name() { + return "ImagePromptTemplate"; + } + constructor(input) { + super(input); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain_core", "prompts", "image"] + }); + Object.defineProperty(this, "template", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "templateFormat", { + enumerable: true, + configurable: true, + writable: true, + value: "f-string" + }); + Object.defineProperty(this, "validateTemplate", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "additionalContentFields", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.template = input.template; + this.templateFormat = input.templateFormat ?? this.templateFormat; + this.validateTemplate = input.validateTemplate ?? this.validateTemplate; + this.additionalContentFields = input.additionalContentFields; + if (this.validateTemplate) { + let totalInputVariables = this.inputVariables; + if (this.partialVariables) { + totalInputVariables = totalInputVariables.concat(Object.keys(this.partialVariables)); + } + checkValidTemplate([ + { type: "image_url", image_url: this.template } + ], this.templateFormat, totalInputVariables); + } + } + _getPromptType() { + return "prompt"; + } + /** + * Partially applies values to the prompt template. + * @param values The values to be partially applied to the prompt template. + * @returns A new instance of ImagePromptTemplate with the partially applied values. + */ + async partial(values) { + const newInputVariables = this.inputVariables.filter((iv) => !(iv in values)); + const newPartialVariables = { + ...this.partialVariables ?? {}, + ...values + }; + const promptDict = { + ...this, + inputVariables: newInputVariables, + partialVariables: newPartialVariables + }; + return new _ImagePromptTemplate(promptDict); + } + /** + * Formats the prompt template with the provided values. + * @param values The values to be used to format the prompt template. + * @returns A promise that resolves to a string which is the formatted prompt. + */ + async format(values) { + const formatted = {}; + for (const [key, value] of Object.entries(this.template)) { + if (typeof value === "string") { + formatted[key] = renderTemplate(value, this.templateFormat, values); + } else { + formatted[key] = value; + } + } + const url = values.url || formatted.url; + const detail = values.detail || formatted.detail; + if (!url) { + throw new Error("Must provide either an image URL."); + } + if (typeof url !== "string") { + throw new Error("url must be a string."); + } + const output = { url }; + if (detail) { + output.detail = detail; + } + return output; + } + /** + * Formats the prompt given the input values and returns a formatted + * prompt value. + * @param values The input values to format the prompt. + * @returns A Promise that resolves to a formatted prompt value. + */ + async formatPromptValue(values) { + const formattedPrompt = await this.format(values); + return new ImagePromptValue(formattedPrompt); + } + }; + } +}); + +// node_modules/@langchain/core/dist/prompts/dict.js +function _getInputVariables(template, templateFormat) { + const inputVariables = []; + for (const v of Object.values(template)) { + if (typeof v === "string") { + parseTemplate2(v, templateFormat).forEach((t) => { + if (t.type === "variable") { + inputVariables.push(t.name); + } + }); + } else if (Array.isArray(v)) { + for (const x of v) { + if (typeof x === "string") { + parseTemplate2(x, templateFormat).forEach((t) => { + if (t.type === "variable") { + inputVariables.push(t.name); + } + }); + } else if (typeof x === "object") { + inputVariables.push(..._getInputVariables(x, templateFormat)); + } + } + } else if (typeof v === "object" && v !== null) { + inputVariables.push(..._getInputVariables(v, templateFormat)); + } + } + return Array.from(new Set(inputVariables)); +} +function _insertInputVariables(template, inputs, templateFormat) { + const formatted = {}; + for (const [k, v] of Object.entries(template)) { + if (typeof v === "string") { + formatted[k] = renderTemplate(v, templateFormat, inputs); + } else if (Array.isArray(v)) { + const formattedV = []; + for (const x of v) { + if (typeof x === "string") { + formattedV.push(renderTemplate(x, templateFormat, inputs)); + } else if (typeof x === "object") { + formattedV.push(_insertInputVariables(x, inputs, templateFormat)); + } + } + formatted[k] = formattedV; + } else if (typeof v === "object" && v !== null) { + formatted[k] = _insertInputVariables(v, inputs, templateFormat); + } else { + formatted[k] = v; + } + } + return formatted; +} +var DictPromptTemplate; +var init_dict = __esm({ + "node_modules/@langchain/core/dist/prompts/dict.js"() { + init_base4(); + init_template(); + DictPromptTemplate = class extends Runnable { + static lc_name() { + return "DictPromptTemplate"; + } + constructor(fields) { + const templateFormat = fields.templateFormat ?? "f-string"; + const inputVariables = _getInputVariables(fields.template, templateFormat); + super({ inputVariables, ...fields }); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain_core", "prompts", "dict"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "template", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "templateFormat", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "inputVariables", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.template = fields.template; + this.templateFormat = templateFormat; + this.inputVariables = inputVariables; + } + async format(values) { + return _insertInputVariables(this.template, values, this.templateFormat); + } + async invoke(values) { + return await this._callWithConfig(this.format.bind(this), values, { + runType: "prompt" + }); + } + }; + } +}); + +// node_modules/@langchain/core/dist/prompts/chat.js +function isTextTemplateParam(param) { + if (param === null || typeof param !== "object" || Array.isArray(param)) { + return false; + } + return Object.keys(param).length === 1 && "text" in param && typeof param.text === "string"; +} +function isImageTemplateParam(param) { + if (param === null || typeof param !== "object" || Array.isArray(param)) { + return false; + } + return "image_url" in param && (typeof param.image_url === "string" || typeof param.image_url === "object" && param.image_url !== null && "url" in param.image_url && typeof param.image_url.url === "string"); +} +function _isBaseMessagePromptTemplate(baseMessagePromptTemplateLike) { + return typeof baseMessagePromptTemplateLike.formatMessages === "function"; +} +function _coerceMessagePromptTemplateLike(messagePromptTemplateLike, extra) { + if (_isBaseMessagePromptTemplate(messagePromptTemplateLike) || isBaseMessage(messagePromptTemplateLike)) { + return messagePromptTemplateLike; + } + if (Array.isArray(messagePromptTemplateLike) && messagePromptTemplateLike[0] === "placeholder") { + const messageContent = messagePromptTemplateLike[1]; + if (extra?.templateFormat === "mustache" && typeof messageContent === "string" && messageContent.slice(0, 2) === "{{" && messageContent.slice(-2) === "}}") { + const variableName = messageContent.slice(2, -2); + return new MessagesPlaceholder({ variableName, optional: true }); + } else if (typeof messageContent === "string" && messageContent[0] === "{" && messageContent[messageContent.length - 1] === "}") { + const variableName = messageContent.slice(1, -1); + return new MessagesPlaceholder({ variableName, optional: true }); + } + throw new Error(`Invalid placeholder template for format ${extra?.templateFormat ?? `"f-string"`}: "${messagePromptTemplateLike[1]}". Expected a variable name surrounded by ${extra?.templateFormat === "mustache" ? "double" : "single"} curly braces.`); + } + const message = coerceMessageLikeToMessage(messagePromptTemplateLike); + let templateData; + if (typeof message.content === "string") { + templateData = message.content; + } else { + templateData = message.content.map((item) => { + if ("text" in item) { + return { ...item, text: item.text }; + } else if ("image_url" in item) { + return { ...item, image_url: item.image_url }; + } else { + return item; + } + }); + } + if (message._getType() === "human") { + return HumanMessagePromptTemplate.fromTemplate(templateData, extra); + } else if (message._getType() === "ai") { + return AIMessagePromptTemplate.fromTemplate(templateData, extra); + } else if (message._getType() === "system") { + return SystemMessagePromptTemplate.fromTemplate(templateData, extra); + } else if (ChatMessage.isInstance(message)) { + return ChatMessagePromptTemplate.fromTemplate(message.content, message.role, extra); + } else { + throw new Error(`Could not coerce message prompt template from input. Received message type: "${message._getType()}".`); + } +} +function isMessagesPlaceholder(x) { + return x.constructor.lc_name() === "MessagesPlaceholder"; +} +var BaseMessagePromptTemplate, MessagesPlaceholder, BaseMessageStringPromptTemplate, BaseChatPromptTemplate, ChatMessagePromptTemplate, _StringImageMessagePromptTemplate, HumanMessagePromptTemplate, AIMessagePromptTemplate, SystemMessagePromptTemplate, ChatPromptTemplate; +var init_chat2 = __esm({ + "node_modules/@langchain/core/dist/prompts/chat.js"() { + init_messages2(); + init_prompt_values(); + init_base4(); + init_string2(); + init_base5(); + init_prompt(); + init_image(); + init_template(); + init_errors(); + init_dict(); + BaseMessagePromptTemplate = class extends Runnable { + constructor() { + super(...arguments); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain_core", "prompts", "chat"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + } + /** + * Calls the formatMessages method with the provided input and options. + * @param input Input for the formatMessages method + * @param options Optional BaseCallbackConfig + * @returns Formatted output messages + */ + async invoke(input, options) { + return this._callWithConfig((input2) => this.formatMessages(input2), input, { ...options, runType: "prompt" }); + } + }; + MessagesPlaceholder = class extends BaseMessagePromptTemplate { + static lc_name() { + return "MessagesPlaceholder"; + } + constructor(fields) { + if (typeof fields === "string") { + fields = { variableName: fields }; + } + super(fields); + Object.defineProperty(this, "variableName", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "optional", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.variableName = fields.variableName; + this.optional = fields.optional ?? false; + } + get inputVariables() { + return [this.variableName]; + } + async formatMessages(values) { + const input = values[this.variableName]; + if (this.optional && !input) { + return []; + } else if (!input) { + const error = new Error(`Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages as an input value. Received: undefined`); + error.name = "InputFormatError"; + throw error; + } + let formattedMessages; + try { + if (Array.isArray(input)) { + formattedMessages = input.map(coerceMessageLikeToMessage); + } else { + formattedMessages = [coerceMessageLikeToMessage(input)]; + } + } catch (e) { + const readableInput = typeof input === "string" ? input : JSON.stringify(input, null, 2); + const error = new Error([ + `Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages or coerceable values as input.`, + `Received value: ${readableInput}`, + `Additional message: ${e.message}` + ].join("\n\n")); + error.name = "InputFormatError"; + error.lc_error_code = e.lc_error_code; + throw error; + } + return formattedMessages; + } + }; + BaseMessageStringPromptTemplate = class extends BaseMessagePromptTemplate { + constructor(fields) { + if (!("prompt" in fields)) { + fields = { prompt: fields }; + } + super(fields); + Object.defineProperty(this, "prompt", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.prompt = fields.prompt; + } + get inputVariables() { + return this.prompt.inputVariables; + } + async formatMessages(values) { + return [await this.format(values)]; + } + }; + BaseChatPromptTemplate = class extends BasePromptTemplate { + constructor(input) { + super(input); + } + async format(values) { + return (await this.formatPromptValue(values)).toString(); + } + async formatPromptValue(values) { + const resultMessages = await this.formatMessages(values); + return new ChatPromptValue(resultMessages); + } + }; + ChatMessagePromptTemplate = class extends BaseMessageStringPromptTemplate { + static lc_name() { + return "ChatMessagePromptTemplate"; + } + constructor(fields, role) { + if (!("prompt" in fields)) { + fields = { prompt: fields, role }; + } + super(fields); + Object.defineProperty(this, "role", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.role = fields.role; + } + async format(values) { + return new ChatMessage(await this.prompt.format(values), this.role); + } + static fromTemplate(template, role, options) { + return new this(PromptTemplate.fromTemplate(template, { + templateFormat: options?.templateFormat + }), role); + } + }; + _StringImageMessagePromptTemplate = class extends BaseMessagePromptTemplate { + static _messageClass() { + throw new Error("Can not invoke _messageClass from inside _StringImageMessagePromptTemplate"); + } + constructor(fields, additionalOptions) { + if (!("prompt" in fields)) { + fields = { prompt: fields }; + } + super(fields); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain_core", "prompts", "chat"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "inputVariables", { + enumerable: true, + configurable: true, + writable: true, + value: [] + }); + Object.defineProperty(this, "additionalOptions", { + enumerable: true, + configurable: true, + writable: true, + value: {} + }); + Object.defineProperty(this, "prompt", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "messageClass", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "chatMessageClass", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.prompt = fields.prompt; + if (Array.isArray(this.prompt)) { + let inputVariables = []; + this.prompt.forEach((prompt) => { + if ("inputVariables" in prompt) { + inputVariables = inputVariables.concat(prompt.inputVariables); + } + }); + this.inputVariables = inputVariables; + } else { + this.inputVariables = this.prompt.inputVariables; + } + this.additionalOptions = additionalOptions ?? this.additionalOptions; + } + createMessage(content) { + const constructor = this.constructor; + if (constructor._messageClass()) { + const MsgClass = constructor._messageClass(); + return new MsgClass({ content }); + } else if (constructor.chatMessageClass) { + const MsgClass = constructor.chatMessageClass(); + return new MsgClass({ + content, + role: this.getRoleFromMessageClass(MsgClass.lc_name()) + }); + } else { + throw new Error("No message class defined"); + } + } + getRoleFromMessageClass(name) { + switch (name) { + case "HumanMessage": + return "human"; + case "AIMessage": + return "ai"; + case "SystemMessage": + return "system"; + case "ChatMessage": + return "chat"; + default: + throw new Error("Invalid message class name"); + } + } + static fromTemplate(template, additionalOptions) { + if (typeof template === "string") { + return new this(PromptTemplate.fromTemplate(template, additionalOptions)); + } + const prompt = []; + for (const item of template) { + if (typeof item === "string") { + prompt.push(PromptTemplate.fromTemplate(item, additionalOptions)); + } else if (item === null) { + } else if (isTextTemplateParam(item)) { + let text = ""; + if (typeof item.text === "string") { + text = item.text ?? ""; + } + const options = { + ...additionalOptions, + additionalContentFields: item + }; + prompt.push(PromptTemplate.fromTemplate(text, options)); + } else if (isImageTemplateParam(item)) { + let imgTemplate = item.image_url ?? ""; + let imgTemplateObject; + let inputVariables = []; + if (typeof imgTemplate === "string") { + let parsedTemplate; + if (additionalOptions?.templateFormat === "mustache") { + parsedTemplate = parseMustache(imgTemplate); + } else { + parsedTemplate = parseFString(imgTemplate); + } + const variables = parsedTemplate.flatMap((item2) => item2.type === "variable" ? [item2.name] : []); + if ((variables?.length ?? 0) > 0) { + if (variables.length > 1) { + throw new Error(`Only one format variable allowed per image template. +Got: ${variables} +From: ${imgTemplate}`); + } + inputVariables = [variables[0]]; + } else { + inputVariables = []; + } + imgTemplate = { url: imgTemplate }; + imgTemplateObject = new ImagePromptTemplate({ + template: imgTemplate, + inputVariables, + templateFormat: additionalOptions?.templateFormat, + additionalContentFields: item + }); + } else if (typeof imgTemplate === "object") { + if ("url" in imgTemplate) { + let parsedTemplate; + if (additionalOptions?.templateFormat === "mustache") { + parsedTemplate = parseMustache(imgTemplate.url); + } else { + parsedTemplate = parseFString(imgTemplate.url); + } + inputVariables = parsedTemplate.flatMap((item2) => item2.type === "variable" ? [item2.name] : []); + } else { + inputVariables = []; + } + imgTemplateObject = new ImagePromptTemplate({ + template: imgTemplate, + inputVariables, + templateFormat: additionalOptions?.templateFormat, + additionalContentFields: item + }); + } else { + throw new Error("Invalid image template"); + } + prompt.push(imgTemplateObject); + } else if (typeof item === "object") { + prompt.push(new DictPromptTemplate({ + template: item, + templateFormat: additionalOptions?.templateFormat + })); + } + } + return new this({ prompt, additionalOptions }); + } + async format(input) { + if (this.prompt instanceof BaseStringPromptTemplate) { + const text = await this.prompt.format(input); + return this.createMessage(text); + } else { + const content = []; + for (const prompt of this.prompt) { + let inputs = {}; + if (!("inputVariables" in prompt)) { + throw new Error(`Prompt ${prompt} does not have inputVariables defined.`); + } + for (const item of prompt.inputVariables) { + if (!inputs) { + inputs = { [item]: input[item] }; + } + inputs = { ...inputs, [item]: input[item] }; + } + if (prompt instanceof BaseStringPromptTemplate) { + const formatted = await prompt.format(inputs); + let additionalContentFields; + if ("additionalContentFields" in prompt) { + additionalContentFields = prompt.additionalContentFields; + } + if (formatted !== "") { + content.push({ + ...additionalContentFields, + type: "text", + text: formatted + }); + } + } else if (prompt instanceof ImagePromptTemplate) { + const formatted = await prompt.format(inputs); + let additionalContentFields; + if ("additionalContentFields" in prompt) { + additionalContentFields = prompt.additionalContentFields; + } + content.push({ + ...additionalContentFields, + type: "image_url", + image_url: formatted + }); + } else if (prompt instanceof DictPromptTemplate) { + const formatted = await prompt.format(inputs); + let additionalContentFields; + if ("additionalContentFields" in prompt) { + additionalContentFields = prompt.additionalContentFields; + } + content.push({ + ...additionalContentFields, + ...formatted + }); + } + } + return this.createMessage(content); + } + } + async formatMessages(values) { + return [await this.format(values)]; + } + }; + HumanMessagePromptTemplate = class extends _StringImageMessagePromptTemplate { + static _messageClass() { + return HumanMessage; + } + static lc_name() { + return "HumanMessagePromptTemplate"; + } + }; + AIMessagePromptTemplate = class extends _StringImageMessagePromptTemplate { + static _messageClass() { + return AIMessage; + } + static lc_name() { + return "AIMessagePromptTemplate"; + } + }; + SystemMessagePromptTemplate = class extends _StringImageMessagePromptTemplate { + static _messageClass() { + return SystemMessage; + } + static lc_name() { + return "SystemMessagePromptTemplate"; + } + }; + ChatPromptTemplate = class _ChatPromptTemplate extends BaseChatPromptTemplate { + static lc_name() { + return "ChatPromptTemplate"; + } + get lc_aliases() { + return { + promptMessages: "messages" + }; + } + constructor(input) { + super(input); + Object.defineProperty(this, "promptMessages", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "validateTemplate", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "templateFormat", { + enumerable: true, + configurable: true, + writable: true, + value: "f-string" + }); + if (input.templateFormat === "mustache" && input.validateTemplate === void 0) { + this.validateTemplate = false; + } + Object.assign(this, input); + if (this.validateTemplate) { + const inputVariablesMessages = /* @__PURE__ */ new Set(); + for (const promptMessage of this.promptMessages) { + if (promptMessage instanceof BaseMessage) + continue; + for (const inputVariable of promptMessage.inputVariables) { + inputVariablesMessages.add(inputVariable); + } + } + const totalInputVariables = this.inputVariables; + const inputVariablesInstance = new Set(this.partialVariables ? totalInputVariables.concat(Object.keys(this.partialVariables)) : totalInputVariables); + const difference = new Set([...inputVariablesInstance].filter((x) => !inputVariablesMessages.has(x))); + if (difference.size > 0) { + throw new Error(`Input variables \`${[ + ...difference + ]}\` are not used in any of the prompt messages.`); + } + const otherDifference = new Set([...inputVariablesMessages].filter((x) => !inputVariablesInstance.has(x))); + if (otherDifference.size > 0) { + throw new Error(`Input variables \`${[ + ...otherDifference + ]}\` are used in prompt messages but not in the prompt template.`); + } + } + } + _getPromptType() { + return "chat"; + } + async _parseImagePrompts(message, inputValues) { + if (typeof message.content === "string") { + return message; + } + const formattedMessageContent = await Promise.all(message.content.map(async (item) => { + if (item.type !== "image_url") { + return item; + } + let imageUrl = ""; + if (typeof item.image_url === "string") { + imageUrl = item.image_url; + } else { + imageUrl = item.image_url.url; + } + const promptTemplatePlaceholder = PromptTemplate.fromTemplate(imageUrl, { + templateFormat: this.templateFormat + }); + const formattedUrl = await promptTemplatePlaceholder.format(inputValues); + if (typeof item.image_url !== "string" && "url" in item.image_url) { + item.image_url.url = formattedUrl; + } else { + item.image_url = formattedUrl; + } + return item; + })); + message.content = formattedMessageContent; + return message; + } + async formatMessages(values) { + const allValues = await this.mergePartialAndUserVariables(values); + let resultMessages = []; + for (const promptMessage of this.promptMessages) { + if (promptMessage instanceof BaseMessage) { + resultMessages.push(await this._parseImagePrompts(promptMessage, allValues)); + } else { + const inputValues = promptMessage.inputVariables.reduce((acc, inputVariable) => { + if (!(inputVariable in allValues) && !(isMessagesPlaceholder(promptMessage) && promptMessage.optional)) { + const error = addLangChainErrorFields(new Error(`Missing value for input variable \`${inputVariable.toString()}\``), "INVALID_PROMPT_INPUT"); + throw error; + } + acc[inputVariable] = allValues[inputVariable]; + return acc; + }, {}); + const message = await promptMessage.formatMessages(inputValues); + resultMessages = resultMessages.concat(message); + } + } + return resultMessages; + } + async partial(values) { + const newInputVariables = this.inputVariables.filter((iv) => !(iv in values)); + const newPartialVariables = { + ...this.partialVariables ?? {}, + ...values + }; + const promptDict = { + ...this, + inputVariables: newInputVariables, + partialVariables: newPartialVariables + }; + return new _ChatPromptTemplate(promptDict); + } + static fromTemplate(template, options) { + const prompt = PromptTemplate.fromTemplate(template, options); + const humanTemplate = new HumanMessagePromptTemplate({ prompt }); + return this.fromMessages([humanTemplate]); + } + /** + * Create a chat model-specific prompt from individual chat messages + * or message-like tuples. + * @param promptMessages Messages to be passed to the chat model + * @returns A new ChatPromptTemplate + */ + static fromMessages(promptMessages, extra) { + const flattenedMessages = promptMessages.reduce((acc, promptMessage) => acc.concat( + // eslint-disable-next-line no-instanceof/no-instanceof + promptMessage instanceof _ChatPromptTemplate ? promptMessage.promptMessages : [ + _coerceMessagePromptTemplateLike(promptMessage, extra) + ] + ), []); + const flattenedPartialVariables = promptMessages.reduce((acc, promptMessage) => ( + // eslint-disable-next-line no-instanceof/no-instanceof + promptMessage instanceof _ChatPromptTemplate ? Object.assign(acc, promptMessage.partialVariables) : acc + ), /* @__PURE__ */ Object.create(null)); + const inputVariables = /* @__PURE__ */ new Set(); + for (const promptMessage of flattenedMessages) { + if (promptMessage instanceof BaseMessage) + continue; + for (const inputVariable of promptMessage.inputVariables) { + if (inputVariable in flattenedPartialVariables) { + continue; + } + inputVariables.add(inputVariable); + } + } + return new this({ + ...extra, + inputVariables: [...inputVariables], + promptMessages: flattenedMessages, + partialVariables: flattenedPartialVariables, + templateFormat: extra?.templateFormat + }); + } + /** @deprecated Renamed to .fromMessages */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + static fromPromptMessages(promptMessages) { + return this.fromMessages(promptMessages); + } + }; + } +}); + +// node_modules/@langchain/core/dist/prompts/few_shot.js +var few_shot_exports = {}; +__export(few_shot_exports, { + FewShotChatMessagePromptTemplate: () => FewShotChatMessagePromptTemplate, + FewShotPromptTemplate: () => FewShotPromptTemplate +}); +var FewShotPromptTemplate, FewShotChatMessagePromptTemplate; +var init_few_shot = __esm({ + "node_modules/@langchain/core/dist/prompts/few_shot.js"() { + init_string2(); + init_template(); + init_prompt(); + init_chat2(); + FewShotPromptTemplate = class _FewShotPromptTemplate extends BaseStringPromptTemplate { + constructor(input) { + super(input); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "examples", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "exampleSelector", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "examplePrompt", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "suffix", { + enumerable: true, + configurable: true, + writable: true, + value: "" + }); + Object.defineProperty(this, "exampleSeparator", { + enumerable: true, + configurable: true, + writable: true, + value: "\n\n" + }); + Object.defineProperty(this, "prefix", { + enumerable: true, + configurable: true, + writable: true, + value: "" + }); + Object.defineProperty(this, "templateFormat", { + enumerable: true, + configurable: true, + writable: true, + value: "f-string" + }); + Object.defineProperty(this, "validateTemplate", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.assign(this, input); + if (this.examples !== void 0 && this.exampleSelector !== void 0) { + throw new Error("Only one of 'examples' and 'example_selector' should be provided"); + } + if (this.examples === void 0 && this.exampleSelector === void 0) { + throw new Error("One of 'examples' and 'example_selector' should be provided"); + } + if (this.validateTemplate) { + let totalInputVariables = this.inputVariables; + if (this.partialVariables) { + totalInputVariables = totalInputVariables.concat(Object.keys(this.partialVariables)); + } + checkValidTemplate(this.prefix + this.suffix, this.templateFormat, totalInputVariables); + } + } + _getPromptType() { + return "few_shot"; + } + static lc_name() { + return "FewShotPromptTemplate"; + } + async getExamples(inputVariables) { + if (this.examples !== void 0) { + return this.examples; + } + if (this.exampleSelector !== void 0) { + return this.exampleSelector.selectExamples(inputVariables); + } + throw new Error("One of 'examples' and 'example_selector' should be provided"); + } + async partial(values) { + const newInputVariables = this.inputVariables.filter((iv) => !(iv in values)); + const newPartialVariables = { + ...this.partialVariables ?? {}, + ...values + }; + const promptDict = { + ...this, + inputVariables: newInputVariables, + partialVariables: newPartialVariables + }; + return new _FewShotPromptTemplate(promptDict); + } + /** + * Formats the prompt with the given values. + * @param values The values to format the prompt with. + * @returns A promise that resolves to a string representing the formatted prompt. + */ + async format(values) { + const allValues = await this.mergePartialAndUserVariables(values); + const examples = await this.getExamples(allValues); + const exampleStrings = await Promise.all(examples.map((example) => this.examplePrompt.format(example))); + const template = [this.prefix, ...exampleStrings, this.suffix].join(this.exampleSeparator); + return renderTemplate(template, this.templateFormat, allValues); + } + serialize() { + if (this.exampleSelector || !this.examples) { + throw new Error("Serializing an example selector is not currently supported"); + } + if (this.outputParser !== void 0) { + throw new Error("Serializing an output parser is not currently supported"); + } + return { + _type: this._getPromptType(), + input_variables: this.inputVariables, + example_prompt: this.examplePrompt.serialize(), + example_separator: this.exampleSeparator, + suffix: this.suffix, + prefix: this.prefix, + template_format: this.templateFormat, + examples: this.examples + }; + } + static async deserialize(data) { + const { example_prompt } = data; + if (!example_prompt) { + throw new Error("Missing example prompt"); + } + const examplePrompt = await PromptTemplate.deserialize(example_prompt); + let examples; + if (Array.isArray(data.examples)) { + examples = data.examples; + } else { + throw new Error("Invalid examples format. Only list or string are supported."); + } + return new _FewShotPromptTemplate({ + inputVariables: data.input_variables, + examplePrompt, + examples, + exampleSeparator: data.example_separator, + prefix: data.prefix, + suffix: data.suffix, + templateFormat: data.template_format + }); + } + }; + FewShotChatMessagePromptTemplate = class _FewShotChatMessagePromptTemplate extends BaseChatPromptTemplate { + _getPromptType() { + return "few_shot_chat"; + } + static lc_name() { + return "FewShotChatMessagePromptTemplate"; + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "examples", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "exampleSelector", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "examplePrompt", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "suffix", { + enumerable: true, + configurable: true, + writable: true, + value: "" + }); + Object.defineProperty(this, "exampleSeparator", { + enumerable: true, + configurable: true, + writable: true, + value: "\n\n" + }); + Object.defineProperty(this, "prefix", { + enumerable: true, + configurable: true, + writable: true, + value: "" + }); + Object.defineProperty(this, "templateFormat", { + enumerable: true, + configurable: true, + writable: true, + value: "f-string" + }); + Object.defineProperty(this, "validateTemplate", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + this.examples = fields.examples; + this.examplePrompt = fields.examplePrompt; + this.exampleSeparator = fields.exampleSeparator ?? "\n\n"; + this.exampleSelector = fields.exampleSelector; + this.prefix = fields.prefix ?? ""; + this.suffix = fields.suffix ?? ""; + this.templateFormat = fields.templateFormat ?? "f-string"; + this.validateTemplate = fields.validateTemplate ?? true; + if (this.examples !== void 0 && this.exampleSelector !== void 0) { + throw new Error("Only one of 'examples' and 'example_selector' should be provided"); + } + if (this.examples === void 0 && this.exampleSelector === void 0) { + throw new Error("One of 'examples' and 'example_selector' should be provided"); + } + if (this.validateTemplate) { + let totalInputVariables = this.inputVariables; + if (this.partialVariables) { + totalInputVariables = totalInputVariables.concat(Object.keys(this.partialVariables)); + } + checkValidTemplate(this.prefix + this.suffix, this.templateFormat, totalInputVariables); + } + } + async getExamples(inputVariables) { + if (this.examples !== void 0) { + return this.examples; + } + if (this.exampleSelector !== void 0) { + return this.exampleSelector.selectExamples(inputVariables); + } + throw new Error("One of 'examples' and 'example_selector' should be provided"); + } + /** + * Formats the list of values and returns a list of formatted messages. + * @param values The values to format the prompt with. + * @returns A promise that resolves to a string representing the formatted prompt. + */ + async formatMessages(values) { + const allValues = await this.mergePartialAndUserVariables(values); + let examples = await this.getExamples(allValues); + examples = examples.map((example) => { + const result = {}; + this.examplePrompt.inputVariables.forEach((inputVariable) => { + result[inputVariable] = example[inputVariable]; + }); + return result; + }); + const messages = []; + for (const example of examples) { + const exampleMessages = await this.examplePrompt.formatMessages(example); + messages.push(...exampleMessages); + } + return messages; + } + /** + * Formats the prompt with the given values. + * @param values The values to format the prompt with. + * @returns A promise that resolves to a string representing the formatted prompt. + */ + async format(values) { + const allValues = await this.mergePartialAndUserVariables(values); + const examples = await this.getExamples(allValues); + const exampleMessages = await Promise.all(examples.map((example) => this.examplePrompt.formatMessages(example))); + const exampleStrings = exampleMessages.flat().map((message) => message.content); + const template = [this.prefix, ...exampleStrings, this.suffix].join(this.exampleSeparator); + return renderTemplate(template, this.templateFormat, allValues); + } + /** + * Partially formats the prompt with the given values. + * @param values The values to partially format the prompt with. + * @returns A promise that resolves to an instance of `FewShotChatMessagePromptTemplate` with the given values partially formatted. + */ + async partial(values) { + const newInputVariables = this.inputVariables.filter((variable) => !(variable in values)); + const newPartialVariables = { + ...this.partialVariables ?? {}, + ...values + }; + const promptDict = { + ...this, + inputVariables: newInputVariables, + partialVariables: newPartialVariables + }; + return new _FewShotChatMessagePromptTemplate(promptDict); + } + }; + } +}); + +// node_modules/@langchain/core/dist/prompts/base.js +var BasePromptTemplate; +var init_base5 = __esm({ + "node_modules/@langchain/core/dist/prompts/base.js"() { + init_base4(); + BasePromptTemplate = class extends Runnable { + get lc_attributes() { + return { + partialVariables: void 0 + // python doesn't support this yet + }; + } + constructor(input) { + super(input); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain_core", "prompts", this._getPromptType()] + }); + Object.defineProperty(this, "inputVariables", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "outputParser", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "partialVariables", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "metadata", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "tags", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + const { inputVariables } = input; + if (inputVariables.includes("stop")) { + throw new Error("Cannot have an input variable named 'stop', as it is used internally, please rename."); + } + Object.assign(this, input); + } + /** + * Merges partial variables and user variables. + * @param userVariables The user variables to merge with the partial variables. + * @returns A Promise that resolves to an object containing the merged variables. + */ + async mergePartialAndUserVariables(userVariables) { + const partialVariables = this.partialVariables ?? {}; + const partialValues = {}; + for (const [key, value] of Object.entries(partialVariables)) { + if (typeof value === "string") { + partialValues[key] = value; + } else { + partialValues[key] = await value(); + } + } + const allKwargs = { + ...partialValues, + ...userVariables + }; + return allKwargs; + } + /** + * Invokes the prompt template with the given input and options. + * @param input The input to invoke the prompt template with. + * @param options Optional configuration for the callback. + * @returns A Promise that resolves to the output of the prompt template. + */ + async invoke(input, options) { + const metadata = { + ...this.metadata, + ...options?.metadata + }; + const tags = [...this.tags ?? [], ...options?.tags ?? []]; + return this._callWithConfig((input2) => this.formatPromptValue(input2), input, { ...options, tags, metadata, runType: "prompt" }); + } + /** + * Return a json-like object representing this prompt template. + * @deprecated + */ + serialize() { + throw new Error("Use .toJSON() instead"); + } + /** + * @deprecated + * Load a prompt template from a json-like object describing it. + * + * @remarks + * Deserializing needs to be async because templates (e.g. {@link FewShotPromptTemplate}) can + * reference remote resources that we read asynchronously with a web + * request. + */ + static async deserialize(data) { + switch (data._type) { + case "prompt": { + const { PromptTemplate: PromptTemplate2 } = await Promise.resolve().then(() => (init_prompt(), prompt_exports)); + return PromptTemplate2.deserialize(data); + } + case void 0: { + const { PromptTemplate: PromptTemplate2 } = await Promise.resolve().then(() => (init_prompt(), prompt_exports)); + return PromptTemplate2.deserialize({ ...data, _type: "prompt" }); + } + case "few_shot": { + const { FewShotPromptTemplate: FewShotPromptTemplate2 } = await Promise.resolve().then(() => (init_few_shot(), few_shot_exports)); + return FewShotPromptTemplate2.deserialize(data); + } + default: + throw new Error(`Invalid prompt type in config: ${data._type}`); + } + } + }; + } +}); + +// node_modules/tslib/tslib.es6.mjs +var tslib_es6_exports = {}; +__export(tslib_es6_exports, { + __addDisposableResource: () => __addDisposableResource, + __assign: () => __assign, + __asyncDelegator: () => __asyncDelegator, + __asyncGenerator: () => __asyncGenerator, + __asyncValues: () => __asyncValues, + __await: () => __await, + __awaiter: () => __awaiter, + __classPrivateFieldGet: () => __classPrivateFieldGet, + __classPrivateFieldIn: () => __classPrivateFieldIn, + __classPrivateFieldSet: () => __classPrivateFieldSet, + __createBinding: () => __createBinding, + __decorate: () => __decorate, + __disposeResources: () => __disposeResources, + __esDecorate: () => __esDecorate, + __exportStar: () => __exportStar, + __extends: () => __extends, + __generator: () => __generator, + __importDefault: () => __importDefault, + __importStar: () => __importStar, + __makeTemplateObject: () => __makeTemplateObject, + __metadata: () => __metadata, + __param: () => __param, + __propKey: () => __propKey, + __read: () => __read, + __rest: () => __rest, + __rewriteRelativeImportExtension: () => __rewriteRelativeImportExtension, + __runInitializers: () => __runInitializers, + __setFunctionName: () => __setFunctionName, + __spread: () => __spread, + __spreadArray: () => __spreadArray, + __spreadArrays: () => __spreadArrays, + __values: () => __values, + default: () => tslib_es6_default +}); +function __extends(d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} +function __rest(s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; +} +function __decorate(decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +} +function __param(paramIndex, decorator) { + return function(target, key) { + decorator(target, key, paramIndex); + }; +} +function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { + function accept(f2) { + if (f2 !== void 0 && typeof f2 !== "function") throw new TypeError("Function expected"); + return f2; + } + var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; + var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; + var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); + var _, done = false; + for (var i = decorators.length - 1; i >= 0; i--) { + var context = {}; + for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; + for (var p in contextIn.access) context.access[p] = contextIn.access[p]; + context.addInitializer = function(f2) { + if (done) throw new TypeError("Cannot add initializers after decoration has completed"); + extraInitializers.push(accept(f2 || null)); + }; + var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); + if (kind === "accessor") { + if (result === void 0) continue; + if (result === null || typeof result !== "object") throw new TypeError("Object expected"); + if (_ = accept(result.get)) descriptor.get = _; + if (_ = accept(result.set)) descriptor.set = _; + if (_ = accept(result.init)) initializers.unshift(_); + } else if (_ = accept(result)) { + if (kind === "field") initializers.unshift(_); + else descriptor[key] = _; + } + } + if (target) Object.defineProperty(target, contextIn.name, descriptor); + done = true; +} +function __runInitializers(thisArg, initializers, value) { + var useValue = arguments.length > 2; + for (var i = 0; i < initializers.length; i++) { + value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); + } + return useValue ? value : void 0; +} +function __propKey(x) { + return typeof x === "symbol" ? x : "".concat(x); +} +function __setFunctionName(f2, name, prefix) { + if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; + return Object.defineProperty(f2, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); +} +function __metadata(metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); +} +function __awaiter(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +} +function __generator(thisArg, body) { + var _ = { label: 0, sent: function() { + if (t[0] & 1) throw t[1]; + return t[1]; + }, trys: [], ops: [] }, f2, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); + return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { + return this; + }), g; + function verb(n2) { + return function(v) { + return step([n2, v]); + }; + } + function step(op) { + if (f2) throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_ = 0)), _) try { + if (f2 = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: + case 1: + t = op; + break; + case 4: + _.label++; + return { value: op[1], done: false }; + case 5: + _.label++; + y = op[1]; + op = [0]; + continue; + case 7: + op = _.ops.pop(); + _.trys.pop(); + continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { + _ = 0; + continue; + } + if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { + _.label = op[1]; + break; + } + if (op[0] === 6 && _.label < t[1]) { + _.label = t[1]; + t = op; + break; + } + if (t && _.label < t[2]) { + _.label = t[2]; + _.ops.push(op); + break; + } + if (t[2]) _.ops.pop(); + _.trys.pop(); + continue; + } + op = body.call(thisArg, _); + } catch (e) { + op = [6, e]; + y = 0; + } finally { + f2 = t = 0; + } + if (op[0] & 5) throw op[1]; + return { value: op[0] ? op[1] : void 0, done: true }; + } +} +function __exportStar(m, o) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); +} +function __values(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function() { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); +} +function __read(o, n2) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n2 === void 0 || n2-- > 0) && !(r = i.next()).done) ar.push(r.value); + } catch (error) { + e = { error }; + } finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } finally { + if (e) throw e.error; + } + } + return ar; +} +function __spread() { + for (var ar = [], i = 0; i < arguments.length; i++) + ar = ar.concat(__read(arguments[i])); + return ar; +} +function __spreadArrays() { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; +} +function __spreadArray(to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); +} +function __await(v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); +} +function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function() { + return this; + }, i; + function awaitReturn(f2) { + return function(v) { + return Promise.resolve(v).then(f2, reject); + }; + } + function verb(n2, f2) { + if (g[n2]) { + i[n2] = function(v) { + return new Promise(function(a, b) { + q.push([n2, v, a, b]) > 1 || resume(n2, v); + }); + }; + if (f2) i[n2] = f2(i[n2]); + } + } + function resume(n2, v) { + try { + step(g[n2](v)); + } catch (e) { + settle(q[0][3], e); + } + } + function step(r) { + r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); + } + function fulfill(value) { + resume("next", value); + } + function reject(value) { + resume("throw", value); + } + function settle(f2, v) { + if (f2(v), q.shift(), q.length) resume(q[0][0], q[0][1]); + } +} +function __asyncDelegator(o) { + var i, p; + return i = {}, verb("next"), verb("throw", function(e) { + throw e; + }), verb("return"), i[Symbol.iterator] = function() { + return this; + }, i; + function verb(n2, f2) { + i[n2] = o[n2] ? function(v) { + return (p = !p) ? { value: __await(o[n2](v)), done: false } : f2 ? f2(v) : v; + } : f2; + } +} +function __asyncValues(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() { + return this; + }, i); + function verb(n2) { + i[n2] = o[n2] && function(v) { + return new Promise(function(resolve, reject) { + v = o[n2](v), settle(resolve, reject, v.done, v.value); + }); + }; + } + function settle(resolve, reject, d, v) { + Promise.resolve(v).then(function(v2) { + resolve({ value: v2, done: d }); + }, reject); + } +} +function __makeTemplateObject(cooked, raw) { + if (Object.defineProperty) { + Object.defineProperty(cooked, "raw", { value: raw }); + } else { + cooked.raw = raw; + } + return cooked; +} +function __importStar(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k = ownKeys2(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + } + __setModuleDefault(result, mod); + return result; +} +function __importDefault(mod) { + return mod && mod.__esModule ? mod : { default: mod }; +} +function __classPrivateFieldGet(receiver, state, kind, f2) { + if (kind === "a" && !f2) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f2 : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f2 : kind === "a" ? f2.call(receiver) : f2 ? f2.value : state.get(receiver); +} +function __classPrivateFieldSet(receiver, state, value, kind, f2) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f2) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f2 : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return kind === "a" ? f2.call(receiver, value) : f2 ? f2.value = value : state.set(receiver, value), value; +} +function __classPrivateFieldIn(state, receiver) { + if (receiver === null || typeof receiver !== "object" && typeof receiver !== "function") throw new TypeError("Cannot use 'in' operator on non-object"); + return typeof state === "function" ? receiver === state : state.has(receiver); +} +function __addDisposableResource(env, value, async) { + if (value !== null && value !== void 0) { + if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); + var dispose, inner; + if (async) { + if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); + dispose = value[Symbol.asyncDispose]; + } + if (dispose === void 0) { + if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); + dispose = value[Symbol.dispose]; + if (async) inner = dispose; + } + if (typeof dispose !== "function") throw new TypeError("Object not disposable."); + if (inner) dispose = function() { + try { + inner.call(this); + } catch (e) { + return Promise.reject(e); + } + }; + env.stack.push({ value, dispose, async }); + } else if (async) { + env.stack.push({ async: true }); + } + return value; +} +function __disposeResources(env) { + function fail(e) { + env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; + env.hasError = true; + } + var r, s = 0; + function next() { + while (r = env.stack.pop()) { + try { + if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next); + if (r.dispose) { + var result = r.dispose.call(r.value); + if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { + fail(e); + return next(); + }); + } else s |= 1; + } catch (e) { + fail(e); + } + } + if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve(); + if (env.hasError) throw env.error; + } + return next(); +} +function __rewriteRelativeImportExtension(path, preserveJsx) { + if (typeof path === "string" && /^\.\.?\//.test(path)) { + return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function(m, tsx, d, ext, cm) { + return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : d + ext + "." + cm.toLowerCase() + "js"; + }); + } + return path; +} +var extendStatics, __assign, __createBinding, __setModuleDefault, ownKeys2, _SuppressedError, tslib_es6_default; +var init_tslib_es6 = __esm({ + "node_modules/tslib/tslib.es6.mjs"() { + extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) { + d2.__proto__ = b2; + } || function(d2, b2) { + for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p]; + }; + return extendStatics(d, b); + }; + __assign = function() { + __assign = Object.assign || function __assign2(t) { + for (var s, i = 1, n2 = arguments.length; i < n2; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); + }; + __createBinding = Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + }); + __setModuleDefault = Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }; + ownKeys2 = function(o) { + ownKeys2 = Object.getOwnPropertyNames || function(o2) { + var ar = []; + for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys2(o); + }; + _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; + }; + tslib_es6_default = { + __extends, + __assign, + __rest, + __decorate, + __param, + __esDecorate, + __runInitializers, + __propKey, + __setFunctionName, + __metadata, + __awaiter, + __generator, + __createBinding, + __exportStar, + __values, + __read, + __spread, + __spreadArrays, + __spreadArray, + __await, + __asyncGenerator, + __asyncDelegator, + __asyncValues, + __makeTemplateObject, + __importStar, + __importDefault, + __classPrivateFieldGet, + __classPrivateFieldSet, + __classPrivateFieldIn, + __addDisposableResource, + __disposeResources, + __rewriteRelativeImportExtension + }; + } +}); + +// node_modules/@supabase/functions-js/dist/main/helper.js +var require_helper = __commonJS({ + "node_modules/@supabase/functions-js/dist/main/helper.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.resolveFetch = void 0; + var resolveFetch = (customFetch) => { + if (customFetch) { + return (...args) => customFetch(...args); + } + return (...args) => fetch(...args); + }; + exports.resolveFetch = resolveFetch; + } +}); + +// node_modules/@supabase/functions-js/dist/main/types.js +var require_types = __commonJS({ + "node_modules/@supabase/functions-js/dist/main/types.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FunctionRegion = exports.FunctionsHttpError = exports.FunctionsRelayError = exports.FunctionsFetchError = exports.FunctionsError = void 0; + var FunctionsError2 = class extends Error { + constructor(message, name = "FunctionsError", context) { + super(message); + this.name = name; + this.context = context; + } + }; + exports.FunctionsError = FunctionsError2; + var FunctionsFetchError2 = class extends FunctionsError2 { + constructor(context) { + super("Failed to send a request to the Edge Function", "FunctionsFetchError", context); + } + }; + exports.FunctionsFetchError = FunctionsFetchError2; + var FunctionsRelayError2 = class extends FunctionsError2 { + constructor(context) { + super("Relay Error invoking the Edge Function", "FunctionsRelayError", context); + } + }; + exports.FunctionsRelayError = FunctionsRelayError2; + var FunctionsHttpError2 = class extends FunctionsError2 { + constructor(context) { + super("Edge Function returned a non-2xx status code", "FunctionsHttpError", context); + } + }; + exports.FunctionsHttpError = FunctionsHttpError2; + var FunctionRegion2; + (function(FunctionRegion3) { + FunctionRegion3["Any"] = "any"; + FunctionRegion3["ApNortheast1"] = "ap-northeast-1"; + FunctionRegion3["ApNortheast2"] = "ap-northeast-2"; + FunctionRegion3["ApSouth1"] = "ap-south-1"; + FunctionRegion3["ApSoutheast1"] = "ap-southeast-1"; + FunctionRegion3["ApSoutheast2"] = "ap-southeast-2"; + FunctionRegion3["CaCentral1"] = "ca-central-1"; + FunctionRegion3["EuCentral1"] = "eu-central-1"; + FunctionRegion3["EuWest1"] = "eu-west-1"; + FunctionRegion3["EuWest2"] = "eu-west-2"; + FunctionRegion3["EuWest3"] = "eu-west-3"; + FunctionRegion3["SaEast1"] = "sa-east-1"; + FunctionRegion3["UsEast1"] = "us-east-1"; + FunctionRegion3["UsWest1"] = "us-west-1"; + FunctionRegion3["UsWest2"] = "us-west-2"; + })(FunctionRegion2 || (exports.FunctionRegion = FunctionRegion2 = {})); + } +}); + +// node_modules/@supabase/functions-js/dist/main/FunctionsClient.js +var require_FunctionsClient = __commonJS({ + "node_modules/@supabase/functions-js/dist/main/FunctionsClient.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FunctionsClient = void 0; + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var helper_1 = require_helper(); + var types_1 = require_types(); + var FunctionsClient = class { + /** + * Creates a new Functions client bound to an Edge Functions URL. + * + * @example + * ```ts + * import { FunctionsClient, FunctionRegion } from '@supabase/functions-js' + * + * const functions = new FunctionsClient('https://xyzcompany.supabase.co/functions/v1', { + * headers: { apikey: 'public-anon-key' }, + * region: FunctionRegion.UsEast1, + * }) + * ``` + */ + constructor(url, { headers = {}, customFetch, region = types_1.FunctionRegion.Any } = {}) { + this.url = url; + this.headers = headers; + this.region = region; + this.fetch = (0, helper_1.resolveFetch)(customFetch); + } + /** + * Updates the authorization header + * @param token - the new jwt token sent in the authorisation header + * @example + * ```ts + * functions.setAuth(session.access_token) + * ``` + */ + setAuth(token) { + this.headers.Authorization = `Bearer ${token}`; + } + /** + * Invokes a function + * @param functionName - The name of the Function to invoke. + * @param options - Options for invoking the Function. + * @example + * ```ts + * const { data, error } = await functions.invoke('hello-world', { + * body: { name: 'Ada' }, + * }) + * ``` + */ + invoke(functionName_1) { + return tslib_1.__awaiter(this, arguments, void 0, function* (functionName, options = {}) { + var _a2; + let timeoutId; + let timeoutController; + try { + const { headers, method, body: functionArgs, signal, timeout } = options; + let _headers = {}; + let { region } = options; + if (!region) { + region = this.region; + } + const url = new URL(`${this.url}/${functionName}`); + if (region && region !== "any") { + _headers["x-region"] = region; + url.searchParams.set("forceFunctionRegion", region); + } + let body; + if (functionArgs && (headers && !Object.prototype.hasOwnProperty.call(headers, "Content-Type") || !headers)) { + if (typeof Blob !== "undefined" && functionArgs instanceof Blob || functionArgs instanceof ArrayBuffer) { + _headers["Content-Type"] = "application/octet-stream"; + body = functionArgs; + } else if (typeof functionArgs === "string") { + _headers["Content-Type"] = "text/plain"; + body = functionArgs; + } else if (typeof FormData !== "undefined" && functionArgs instanceof FormData) { + body = functionArgs; + } else { + _headers["Content-Type"] = "application/json"; + body = JSON.stringify(functionArgs); + } + } else { + body = functionArgs; + } + let effectiveSignal = signal; + if (timeout) { + timeoutController = new AbortController(); + timeoutId = setTimeout(() => timeoutController.abort(), timeout); + if (signal) { + effectiveSignal = timeoutController.signal; + signal.addEventListener("abort", () => timeoutController.abort()); + } else { + effectiveSignal = timeoutController.signal; + } + } + const response = yield this.fetch(url.toString(), { + method: method || "POST", + // headers priority is (high to low): + // 1. invoke-level headers + // 2. client-level headers + // 3. default Content-Type header + headers: Object.assign(Object.assign(Object.assign({}, _headers), this.headers), headers), + body, + signal: effectiveSignal + }).catch((fetchError) => { + throw new types_1.FunctionsFetchError(fetchError); + }); + const isRelayError = response.headers.get("x-relay-error"); + if (isRelayError && isRelayError === "true") { + throw new types_1.FunctionsRelayError(response); + } + if (!response.ok) { + throw new types_1.FunctionsHttpError(response); + } + let responseType = ((_a2 = response.headers.get("Content-Type")) !== null && _a2 !== void 0 ? _a2 : "text/plain").split(";")[0].trim(); + let data; + if (responseType === "application/json") { + data = yield response.json(); + } else if (responseType === "application/octet-stream" || responseType === "application/pdf") { + data = yield response.blob(); + } else if (responseType === "text/event-stream") { + data = response; + } else if (responseType === "multipart/form-data") { + data = yield response.formData(); + } else { + data = yield response.text(); + } + return { data, error: null, response }; + } catch (error) { + return { + data: null, + error, + response: error instanceof types_1.FunctionsHttpError || error instanceof types_1.FunctionsRelayError ? error.context : void 0 + }; + } finally { + if (timeoutId) { + clearTimeout(timeoutId); + } + } + }); + } + }; + exports.FunctionsClient = FunctionsClient; + } +}); + +// node_modules/@supabase/functions-js/dist/main/index.js +var require_main = __commonJS({ + "node_modules/@supabase/functions-js/dist/main/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FunctionRegion = exports.FunctionsRelayError = exports.FunctionsHttpError = exports.FunctionsFetchError = exports.FunctionsError = exports.FunctionsClient = void 0; + var FunctionsClient_1 = require_FunctionsClient(); + Object.defineProperty(exports, "FunctionsClient", { enumerable: true, get: function() { + return FunctionsClient_1.FunctionsClient; + } }); + var types_1 = require_types(); + Object.defineProperty(exports, "FunctionsError", { enumerable: true, get: function() { + return types_1.FunctionsError; + } }); + Object.defineProperty(exports, "FunctionsFetchError", { enumerable: true, get: function() { + return types_1.FunctionsFetchError; + } }); + Object.defineProperty(exports, "FunctionsHttpError", { enumerable: true, get: function() { + return types_1.FunctionsHttpError; + } }); + Object.defineProperty(exports, "FunctionsRelayError", { enumerable: true, get: function() { + return types_1.FunctionsRelayError; + } }); + Object.defineProperty(exports, "FunctionRegion", { enumerable: true, get: function() { + return types_1.FunctionRegion; + } }); + } +}); + +// node_modules/@supabase/postgrest-js/dist/cjs/PostgrestError.js +var require_PostgrestError = __commonJS({ + "node_modules/@supabase/postgrest-js/dist/cjs/PostgrestError.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var PostgrestError2 = class extends Error { + /** + * @example + * ```ts + * import PostgrestError from '@supabase/postgrest-js' + * + * throw new PostgrestError({ + * message: 'Row level security prevented the request', + * details: 'RLS denied the insert', + * hint: 'Check your policies', + * code: 'PGRST301', + * }) + * ``` + */ + constructor(context) { + super(context.message); + this.name = "PostgrestError"; + this.details = context.details; + this.hint = context.hint; + this.code = context.code; + } + }; + exports.default = PostgrestError2; + } +}); + +// node_modules/@supabase/postgrest-js/dist/cjs/PostgrestBuilder.js +var require_PostgrestBuilder = __commonJS({ + "node_modules/@supabase/postgrest-js/dist/cjs/PostgrestBuilder.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var PostgrestError_1 = tslib_1.__importDefault(require_PostgrestError()); + var PostgrestBuilder = class { + /** + * Creates a builder configured for a specific PostgREST request. + * + * @example + * ```ts + * import PostgrestQueryBuilder from '@supabase/postgrest-js' + * + * const builder = new PostgrestQueryBuilder( + * new URL('https://xyzcompany.supabase.co/rest/v1/users'), + * { headers: new Headers({ apikey: 'public-anon-key' }) } + * ) + * ``` + */ + constructor(builder) { + var _a2, _b; + this.shouldThrowOnError = false; + this.method = builder.method; + this.url = builder.url; + this.headers = new Headers(builder.headers); + this.schema = builder.schema; + this.body = builder.body; + this.shouldThrowOnError = (_a2 = builder.shouldThrowOnError) !== null && _a2 !== void 0 ? _a2 : false; + this.signal = builder.signal; + this.isMaybeSingle = (_b = builder.isMaybeSingle) !== null && _b !== void 0 ? _b : false; + if (builder.fetch) { + this.fetch = builder.fetch; + } else { + this.fetch = fetch; + } + } + /** + * If there's an error with the query, throwOnError will reject the promise by + * throwing the error instead of returning it as part of a successful response. + * + * {@link https://github.com/supabase/supabase-js/issues/92} + */ + throwOnError() { + this.shouldThrowOnError = true; + return this; + } + /** + * Set an HTTP header for the request. + */ + setHeader(name, value) { + this.headers = new Headers(this.headers); + this.headers.set(name, value); + return this; + } + then(onfulfilled, onrejected) { + if (this.schema === void 0) { + } else if (["GET", "HEAD"].includes(this.method)) { + this.headers.set("Accept-Profile", this.schema); + } else { + this.headers.set("Content-Profile", this.schema); + } + if (this.method !== "GET" && this.method !== "HEAD") { + this.headers.set("Content-Type", "application/json"); + } + const _fetch = this.fetch; + let res = _fetch(this.url.toString(), { + method: this.method, + headers: this.headers, + body: JSON.stringify(this.body), + signal: this.signal + }).then(async (res2) => { + var _a2, _b, _c, _d; + let error = null; + let data = null; + let count = null; + let status = res2.status; + let statusText = res2.statusText; + if (res2.ok) { + if (this.method !== "HEAD") { + const body = await res2.text(); + if (body === "") { + } else if (this.headers.get("Accept") === "text/csv") { + data = body; + } else if (this.headers.get("Accept") && ((_a2 = this.headers.get("Accept")) === null || _a2 === void 0 ? void 0 : _a2.includes("application/vnd.pgrst.plan+text"))) { + data = body; + } else { + data = JSON.parse(body); + } + } + const countHeader = (_b = this.headers.get("Prefer")) === null || _b === void 0 ? void 0 : _b.match(/count=(exact|planned|estimated)/); + const contentRange = (_c = res2.headers.get("content-range")) === null || _c === void 0 ? void 0 : _c.split("/"); + if (countHeader && contentRange && contentRange.length > 1) { + count = parseInt(contentRange[1]); + } + if (this.isMaybeSingle && this.method === "GET" && Array.isArray(data)) { + if (data.length > 1) { + error = { + // https://github.com/PostgREST/postgrest/blob/a867d79c42419af16c18c3fb019eba8df992626f/src/PostgREST/Error.hs#L553 + code: "PGRST116", + details: `Results contain ${data.length} rows, application/vnd.pgrst.object+json requires 1 row`, + hint: null, + message: "JSON object requested, multiple (or no) rows returned" + }; + data = null; + count = null; + status = 406; + statusText = "Not Acceptable"; + } else if (data.length === 1) { + data = data[0]; + } else { + data = null; + } + } + } else { + const body = await res2.text(); + try { + error = JSON.parse(body); + if (Array.isArray(error) && res2.status === 404) { + data = []; + error = null; + status = 200; + statusText = "OK"; + } + } catch (_e) { + if (res2.status === 404 && body === "") { + status = 204; + statusText = "No Content"; + } else { + error = { + message: body + }; + } + } + if (error && this.isMaybeSingle && ((_d = error === null || error === void 0 ? void 0 : error.details) === null || _d === void 0 ? void 0 : _d.includes("0 rows"))) { + error = null; + status = 200; + statusText = "OK"; + } + if (error && this.shouldThrowOnError) { + throw new PostgrestError_1.default(error); + } + } + const postgrestResponse = { + error, + data, + count, + status, + statusText + }; + return postgrestResponse; + }); + if (!this.shouldThrowOnError) { + res = res.catch((fetchError) => { + var _a2, _b, _c, _d, _e, _f; + let errorDetails = ""; + const cause = fetchError === null || fetchError === void 0 ? void 0 : fetchError.cause; + if (cause) { + const causeMessage = (_a2 = cause === null || cause === void 0 ? void 0 : cause.message) !== null && _a2 !== void 0 ? _a2 : ""; + const causeCode = (_b = cause === null || cause === void 0 ? void 0 : cause.code) !== null && _b !== void 0 ? _b : ""; + errorDetails = `${(_c = fetchError === null || fetchError === void 0 ? void 0 : fetchError.name) !== null && _c !== void 0 ? _c : "FetchError"}: ${fetchError === null || fetchError === void 0 ? void 0 : fetchError.message}`; + errorDetails += ` + +Caused by: ${(_d = cause === null || cause === void 0 ? void 0 : cause.name) !== null && _d !== void 0 ? _d : "Error"}: ${causeMessage}`; + if (causeCode) { + errorDetails += ` (${causeCode})`; + } + if (cause === null || cause === void 0 ? void 0 : cause.stack) { + errorDetails += ` +${cause.stack}`; + } + } else { + errorDetails = (_e = fetchError === null || fetchError === void 0 ? void 0 : fetchError.stack) !== null && _e !== void 0 ? _e : ""; + } + return { + error: { + message: `${(_f = fetchError === null || fetchError === void 0 ? void 0 : fetchError.name) !== null && _f !== void 0 ? _f : "FetchError"}: ${fetchError === null || fetchError === void 0 ? void 0 : fetchError.message}`, + details: errorDetails, + hint: "", + code: "" + }, + data: null, + count: null, + status: 0, + statusText: "" + }; + }); + } + return res.then(onfulfilled, onrejected); + } + /** + * Override the type of the returned `data`. + * + * @typeParam NewResult - The new result type to override with + * @deprecated Use overrideTypes() method at the end of your call chain instead + */ + returns() { + return this; + } + /** + * Override the type of the returned `data` field in the response. + * + * @typeParam NewResult - The new type to cast the response data to + * @typeParam Options - Optional type configuration (defaults to { merge: true }) + * @typeParam Options.merge - When true, merges the new type with existing return type. When false, replaces the existing types entirely (defaults to true) + * @example + * ```typescript + * // Merge with existing types (default behavior) + * const query = supabase + * .from('users') + * .select() + * .overrideTypes<{ custom_field: string }>() + * + * // Replace existing types completely + * const replaceQuery = supabase + * .from('users') + * .select() + * .overrideTypes<{ id: number; name: string }, { merge: false }>() + * ``` + * @returns A PostgrestBuilder instance with the new type + */ + overrideTypes() { + return this; + } + }; + exports.default = PostgrestBuilder; + } +}); + +// node_modules/@supabase/postgrest-js/dist/cjs/PostgrestTransformBuilder.js +var require_PostgrestTransformBuilder = __commonJS({ + "node_modules/@supabase/postgrest-js/dist/cjs/PostgrestTransformBuilder.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var PostgrestBuilder_1 = tslib_1.__importDefault(require_PostgrestBuilder()); + var PostgrestTransformBuilder = class extends PostgrestBuilder_1.default { + /** + * Perform a SELECT on the query result. + * + * By default, `.insert()`, `.update()`, `.upsert()`, and `.delete()` do not + * return modified rows. By calling this method, modified rows are returned in + * `data`. + * + * @param columns - The columns to retrieve, separated by commas + */ + select(columns) { + let quoted = false; + const cleanedColumns = (columns !== null && columns !== void 0 ? columns : "*").split("").map((c) => { + if (/\s/.test(c) && !quoted) { + return ""; + } + if (c === '"') { + quoted = !quoted; + } + return c; + }).join(""); + this.url.searchParams.set("select", cleanedColumns); + this.headers.append("Prefer", "return=representation"); + return this; + } + /** + * Order the query result by `column`. + * + * You can call this method multiple times to order by multiple columns. + * + * You can order referenced tables, but it only affects the ordering of the + * parent table if you use `!inner` in the query. + * + * @param column - The column to order by + * @param options - Named parameters + * @param options.ascending - If `true`, the result will be in ascending order + * @param options.nullsFirst - If `true`, `null`s appear first. If `false`, + * `null`s appear last. + * @param options.referencedTable - Set this to order a referenced table by + * its columns + * @param options.foreignTable - Deprecated, use `options.referencedTable` + * instead + */ + order(column, { ascending = true, nullsFirst, foreignTable, referencedTable = foreignTable } = {}) { + const key = referencedTable ? `${referencedTable}.order` : "order"; + const existingOrder = this.url.searchParams.get(key); + this.url.searchParams.set(key, `${existingOrder ? `${existingOrder},` : ""}${column}.${ascending ? "asc" : "desc"}${nullsFirst === void 0 ? "" : nullsFirst ? ".nullsfirst" : ".nullslast"}`); + return this; + } + /** + * Limit the query result by `count`. + * + * @param count - The maximum number of rows to return + * @param options - Named parameters + * @param options.referencedTable - Set this to limit rows of referenced + * tables instead of the parent table + * @param options.foreignTable - Deprecated, use `options.referencedTable` + * instead + */ + limit(count, { foreignTable, referencedTable = foreignTable } = {}) { + const key = typeof referencedTable === "undefined" ? "limit" : `${referencedTable}.limit`; + this.url.searchParams.set(key, `${count}`); + return this; + } + /** + * Limit the query result by starting at an offset `from` and ending at the offset `to`. + * Only records within this range are returned. + * This respects the query order and if there is no order clause the range could behave unexpectedly. + * The `from` and `to` values are 0-based and inclusive: `range(1, 3)` will include the second, third + * and fourth rows of the query. + * + * @param from - The starting index from which to limit the result + * @param to - The last index to which to limit the result + * @param options - Named parameters + * @param options.referencedTable - Set this to limit rows of referenced + * tables instead of the parent table + * @param options.foreignTable - Deprecated, use `options.referencedTable` + * instead + */ + range(from, to, { foreignTable, referencedTable = foreignTable } = {}) { + const keyOffset = typeof referencedTable === "undefined" ? "offset" : `${referencedTable}.offset`; + const keyLimit = typeof referencedTable === "undefined" ? "limit" : `${referencedTable}.limit`; + this.url.searchParams.set(keyOffset, `${from}`); + this.url.searchParams.set(keyLimit, `${to - from + 1}`); + return this; + } + /** + * Set the AbortSignal for the fetch request. + * + * @param signal - The AbortSignal to use for the fetch request + */ + abortSignal(signal) { + this.signal = signal; + return this; + } + /** + * Return `data` as a single object instead of an array of objects. + * + * Query result must be one row (e.g. using `.limit(1)`), otherwise this + * returns an error. + */ + single() { + this.headers.set("Accept", "application/vnd.pgrst.object+json"); + return this; + } + /** + * Return `data` as a single object instead of an array of objects. + * + * Query result must be zero or one row (e.g. using `.limit(1)`), otherwise + * this returns an error. + */ + maybeSingle() { + if (this.method === "GET") { + this.headers.set("Accept", "application/json"); + } else { + this.headers.set("Accept", "application/vnd.pgrst.object+json"); + } + this.isMaybeSingle = true; + return this; + } + /** + * Return `data` as a string in CSV format. + */ + csv() { + this.headers.set("Accept", "text/csv"); + return this; + } + /** + * Return `data` as an object in [GeoJSON](https://geojson.org) format. + */ + geojson() { + this.headers.set("Accept", "application/geo+json"); + return this; + } + /** + * Return `data` as the EXPLAIN plan for the query. + * + * You need to enable the + * [db_plan_enabled](https://supabase.com/docs/guides/database/debugging-performance#enabling-explain) + * setting before using this method. + * + * @param options - Named parameters + * + * @param options.analyze - If `true`, the query will be executed and the + * actual run time will be returned + * + * @param options.verbose - If `true`, the query identifier will be returned + * and `data` will include the output columns of the query + * + * @param options.settings - If `true`, include information on configuration + * parameters that affect query planning + * + * @param options.buffers - If `true`, include information on buffer usage + * + * @param options.wal - If `true`, include information on WAL record generation + * + * @param options.format - The format of the output, can be `"text"` (default) + * or `"json"` + */ + explain({ analyze = false, verbose = false, settings = false, buffers = false, wal = false, format: format2 = "text" } = {}) { + var _a2; + const options = [ + analyze ? "analyze" : null, + verbose ? "verbose" : null, + settings ? "settings" : null, + buffers ? "buffers" : null, + wal ? "wal" : null + ].filter(Boolean).join("|"); + const forMediatype = (_a2 = this.headers.get("Accept")) !== null && _a2 !== void 0 ? _a2 : "application/json"; + this.headers.set("Accept", `application/vnd.pgrst.plan+${format2}; for="${forMediatype}"; options=${options};`); + if (format2 === "json") { + return this; + } else { + return this; + } + } + /** + * Rollback the query. + * + * `data` will still be returned, but the query is not committed. + */ + rollback() { + this.headers.append("Prefer", "tx=rollback"); + return this; + } + /** + * Override the type of the returned `data`. + * + * @typeParam NewResult - The new result type to override with + * @deprecated Use overrideTypes() method at the end of your call chain instead + */ + returns() { + return this; + } + /** + * Set the maximum number of rows that can be affected by the query. + * Only available in PostgREST v13+ and only works with PATCH and DELETE methods. + * + * @param value - The maximum number of rows that can be affected + */ + maxAffected(value) { + this.headers.append("Prefer", "handling=strict"); + this.headers.append("Prefer", `max-affected=${value}`); + return this; + } + }; + exports.default = PostgrestTransformBuilder; + } +}); + +// node_modules/@supabase/postgrest-js/dist/cjs/PostgrestFilterBuilder.js +var require_PostgrestFilterBuilder = __commonJS({ + "node_modules/@supabase/postgrest-js/dist/cjs/PostgrestFilterBuilder.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var PostgrestTransformBuilder_1 = tslib_1.__importDefault(require_PostgrestTransformBuilder()); + var PostgrestReservedCharsRegexp = new RegExp("[,()]"); + var PostgrestFilterBuilder = class extends PostgrestTransformBuilder_1.default { + /** + * Match only rows where `column` is equal to `value`. + * + * To check if the value of `column` is NULL, you should use `.is()` instead. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + eq(column, value) { + this.url.searchParams.append(column, `eq.${value}`); + return this; + } + /** + * Match only rows where `column` is not equal to `value`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + neq(column, value) { + this.url.searchParams.append(column, `neq.${value}`); + return this; + } + /** + * Match only rows where `column` is greater than `value`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + gt(column, value) { + this.url.searchParams.append(column, `gt.${value}`); + return this; + } + /** + * Match only rows where `column` is greater than or equal to `value`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + gte(column, value) { + this.url.searchParams.append(column, `gte.${value}`); + return this; + } + /** + * Match only rows where `column` is less than `value`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + lt(column, value) { + this.url.searchParams.append(column, `lt.${value}`); + return this; + } + /** + * Match only rows where `column` is less than or equal to `value`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + lte(column, value) { + this.url.searchParams.append(column, `lte.${value}`); + return this; + } + /** + * Match only rows where `column` matches `pattern` case-sensitively. + * + * @param column - The column to filter on + * @param pattern - The pattern to match with + */ + like(column, pattern) { + this.url.searchParams.append(column, `like.${pattern}`); + return this; + } + /** + * Match only rows where `column` matches all of `patterns` case-sensitively. + * + * @param column - The column to filter on + * @param patterns - The patterns to match with + */ + likeAllOf(column, patterns) { + this.url.searchParams.append(column, `like(all).{${patterns.join(",")}}`); + return this; + } + /** + * Match only rows where `column` matches any of `patterns` case-sensitively. + * + * @param column - The column to filter on + * @param patterns - The patterns to match with + */ + likeAnyOf(column, patterns) { + this.url.searchParams.append(column, `like(any).{${patterns.join(",")}}`); + return this; + } + /** + * Match only rows where `column` matches `pattern` case-insensitively. + * + * @param column - The column to filter on + * @param pattern - The pattern to match with + */ + ilike(column, pattern) { + this.url.searchParams.append(column, `ilike.${pattern}`); + return this; + } + /** + * Match only rows where `column` matches all of `patterns` case-insensitively. + * + * @param column - The column to filter on + * @param patterns - The patterns to match with + */ + ilikeAllOf(column, patterns) { + this.url.searchParams.append(column, `ilike(all).{${patterns.join(",")}}`); + return this; + } + /** + * Match only rows where `column` matches any of `patterns` case-insensitively. + * + * @param column - The column to filter on + * @param patterns - The patterns to match with + */ + ilikeAnyOf(column, patterns) { + this.url.searchParams.append(column, `ilike(any).{${patterns.join(",")}}`); + return this; + } + /** + * Match only rows where `column` matches the PostgreSQL regex `pattern` + * case-sensitively (using the `~` operator). + * + * @param column - The column to filter on + * @param pattern - The PostgreSQL regular expression pattern to match with + */ + regexMatch(column, pattern) { + this.url.searchParams.append(column, `match.${pattern}`); + return this; + } + /** + * Match only rows where `column` matches the PostgreSQL regex `pattern` + * case-insensitively (using the `~*` operator). + * + * @param column - The column to filter on + * @param pattern - The PostgreSQL regular expression pattern to match with + */ + regexIMatch(column, pattern) { + this.url.searchParams.append(column, `imatch.${pattern}`); + return this; + } + /** + * Match only rows where `column` IS `value`. + * + * For non-boolean columns, this is only relevant for checking if the value of + * `column` is NULL by setting `value` to `null`. + * + * For boolean columns, you can also set `value` to `true` or `false` and it + * will behave the same way as `.eq()`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + is(column, value) { + this.url.searchParams.append(column, `is.${value}`); + return this; + } + /** + * Match only rows where `column` IS DISTINCT FROM `value`. + * + * Unlike `.neq()`, this treats `NULL` as a comparable value. Two `NULL` values + * are considered equal (not distinct), and comparing `NULL` with any non-NULL + * value returns true (distinct). + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + isDistinct(column, value) { + this.url.searchParams.append(column, `isdistinct.${value}`); + return this; + } + /** + * Match only rows where `column` is included in the `values` array. + * + * @param column - The column to filter on + * @param values - The values array to filter with + */ + in(column, values) { + const cleanedValues = Array.from(new Set(values)).map((s) => { + if (typeof s === "string" && PostgrestReservedCharsRegexp.test(s)) + return `"${s}"`; + else + return `${s}`; + }).join(","); + this.url.searchParams.append(column, `in.(${cleanedValues})`); + return this; + } + /** + * Only relevant for jsonb, array, and range columns. Match only rows where + * `column` contains every element appearing in `value`. + * + * @param column - The jsonb, array, or range column to filter on + * @param value - The jsonb, array, or range value to filter with + */ + contains(column, value) { + if (typeof value === "string") { + this.url.searchParams.append(column, `cs.${value}`); + } else if (Array.isArray(value)) { + this.url.searchParams.append(column, `cs.{${value.join(",")}}`); + } else { + this.url.searchParams.append(column, `cs.${JSON.stringify(value)}`); + } + return this; + } + /** + * Only relevant for jsonb, array, and range columns. Match only rows where + * every element appearing in `column` is contained by `value`. + * + * @param column - The jsonb, array, or range column to filter on + * @param value - The jsonb, array, or range value to filter with + */ + containedBy(column, value) { + if (typeof value === "string") { + this.url.searchParams.append(column, `cd.${value}`); + } else if (Array.isArray(value)) { + this.url.searchParams.append(column, `cd.{${value.join(",")}}`); + } else { + this.url.searchParams.append(column, `cd.${JSON.stringify(value)}`); + } + return this; + } + /** + * Only relevant for range columns. Match only rows where every element in + * `column` is greater than any element in `range`. + * + * @param column - The range column to filter on + * @param range - The range to filter with + */ + rangeGt(column, range) { + this.url.searchParams.append(column, `sr.${range}`); + return this; + } + /** + * Only relevant for range columns. Match only rows where every element in + * `column` is either contained in `range` or greater than any element in + * `range`. + * + * @param column - The range column to filter on + * @param range - The range to filter with + */ + rangeGte(column, range) { + this.url.searchParams.append(column, `nxl.${range}`); + return this; + } + /** + * Only relevant for range columns. Match only rows where every element in + * `column` is less than any element in `range`. + * + * @param column - The range column to filter on + * @param range - The range to filter with + */ + rangeLt(column, range) { + this.url.searchParams.append(column, `sl.${range}`); + return this; + } + /** + * Only relevant for range columns. Match only rows where every element in + * `column` is either contained in `range` or less than any element in + * `range`. + * + * @param column - The range column to filter on + * @param range - The range to filter with + */ + rangeLte(column, range) { + this.url.searchParams.append(column, `nxr.${range}`); + return this; + } + /** + * Only relevant for range columns. Match only rows where `column` is + * mutually exclusive to `range` and there can be no element between the two + * ranges. + * + * @param column - The range column to filter on + * @param range - The range to filter with + */ + rangeAdjacent(column, range) { + this.url.searchParams.append(column, `adj.${range}`); + return this; + } + /** + * Only relevant for array and range columns. Match only rows where + * `column` and `value` have an element in common. + * + * @param column - The array or range column to filter on + * @param value - The array or range value to filter with + */ + overlaps(column, value) { + if (typeof value === "string") { + this.url.searchParams.append(column, `ov.${value}`); + } else { + this.url.searchParams.append(column, `ov.{${value.join(",")}}`); + } + return this; + } + /** + * Only relevant for text and tsvector columns. Match only rows where + * `column` matches the query string in `query`. + * + * @param column - The text or tsvector column to filter on + * @param query - The query text to match with + * @param options - Named parameters + * @param options.config - The text search configuration to use + * @param options.type - Change how the `query` text is interpreted + */ + textSearch(column, query, { config: config2, type } = {}) { + let typePart = ""; + if (type === "plain") { + typePart = "pl"; + } else if (type === "phrase") { + typePart = "ph"; + } else if (type === "websearch") { + typePart = "w"; + } + const configPart = config2 === void 0 ? "" : `(${config2})`; + this.url.searchParams.append(column, `${typePart}fts${configPart}.${query}`); + return this; + } + /** + * Match only rows where each column in `query` keys is equal to its + * associated value. Shorthand for multiple `.eq()`s. + * + * @param query - The object to filter with, with column names as keys mapped + * to their filter values + */ + match(query) { + Object.entries(query).forEach(([column, value]) => { + this.url.searchParams.append(column, `eq.${value}`); + }); + return this; + } + /** + * Match only rows which doesn't satisfy the filter. + * + * Unlike most filters, `opearator` and `value` are used as-is and need to + * follow [PostgREST + * syntax](https://postgrest.org/en/stable/api.html#operators). You also need + * to make sure they are properly sanitized. + * + * @param column - The column to filter on + * @param operator - The operator to be negated to filter with, following + * PostgREST syntax + * @param value - The value to filter with, following PostgREST syntax + */ + not(column, operator, value) { + this.url.searchParams.append(column, `not.${operator}.${value}`); + return this; + } + /** + * Match only rows which satisfy at least one of the filters. + * + * Unlike most filters, `filters` is used as-is and needs to follow [PostgREST + * syntax](https://postgrest.org/en/stable/api.html#operators). You also need + * to make sure it's properly sanitized. + * + * It's currently not possible to do an `.or()` filter across multiple tables. + * + * @param filters - The filters to use, following PostgREST syntax + * @param options - Named parameters + * @param options.referencedTable - Set this to filter on referenced tables + * instead of the parent table + * @param options.foreignTable - Deprecated, use `referencedTable` instead + */ + or(filters, { foreignTable, referencedTable = foreignTable } = {}) { + const key = referencedTable ? `${referencedTable}.or` : "or"; + this.url.searchParams.append(key, `(${filters})`); + return this; + } + /** + * Match only rows which satisfy the filter. This is an escape hatch - you + * should use the specific filter methods wherever possible. + * + * Unlike most filters, `opearator` and `value` are used as-is and need to + * follow [PostgREST + * syntax](https://postgrest.org/en/stable/api.html#operators). You also need + * to make sure they are properly sanitized. + * + * @param column - The column to filter on + * @param operator - The operator to filter with, following PostgREST syntax + * @param value - The value to filter with, following PostgREST syntax + */ + filter(column, operator, value) { + this.url.searchParams.append(column, `${operator}.${value}`); + return this; + } + }; + exports.default = PostgrestFilterBuilder; + } +}); + +// node_modules/@supabase/postgrest-js/dist/cjs/PostgrestQueryBuilder.js +var require_PostgrestQueryBuilder = __commonJS({ + "node_modules/@supabase/postgrest-js/dist/cjs/PostgrestQueryBuilder.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var PostgrestFilterBuilder_1 = tslib_1.__importDefault(require_PostgrestFilterBuilder()); + var PostgrestQueryBuilder = class { + /** + * Creates a query builder scoped to a Postgres table or view. + * + * @example + * ```ts + * import PostgrestQueryBuilder from '@supabase/postgrest-js' + * + * const query = new PostgrestQueryBuilder( + * new URL('https://xyzcompany.supabase.co/rest/v1/users'), + * { headers: { apikey: 'public-anon-key' } } + * ) + * ``` + */ + constructor(url, { headers = {}, schema, fetch: fetch2 }) { + this.url = url; + this.headers = new Headers(headers); + this.schema = schema; + this.fetch = fetch2; + } + /** + * Perform a SELECT query on the table or view. + * + * @param columns - The columns to retrieve, separated by commas. Columns can be renamed when returned with `customName:columnName` + * + * @param options - Named parameters + * + * @param options.head - When set to `true`, `data` will not be returned. + * Useful if you only need the count. + * + * @param options.count - Count algorithm to use to count rows in the table or view. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + select(columns, options) { + const { head = false, count } = options !== null && options !== void 0 ? options : {}; + const method = head ? "HEAD" : "GET"; + let quoted = false; + const cleanedColumns = (columns !== null && columns !== void 0 ? columns : "*").split("").map((c) => { + if (/\s/.test(c) && !quoted) { + return ""; + } + if (c === '"') { + quoted = !quoted; + } + return c; + }).join(""); + this.url.searchParams.set("select", cleanedColumns); + if (count) { + this.headers.append("Prefer", `count=${count}`); + } + return new PostgrestFilterBuilder_1.default({ + method, + url: this.url, + headers: this.headers, + schema: this.schema, + fetch: this.fetch + }); + } + /** + * Perform an INSERT into the table or view. + * + * By default, inserted rows are not returned. To return it, chain the call + * with `.select()`. + * + * @param values - The values to insert. Pass an object to insert a single row + * or an array to insert multiple rows. + * + * @param options - Named parameters + * + * @param options.count - Count algorithm to use to count inserted rows. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + * + * @param options.defaultToNull - Make missing fields default to `null`. + * Otherwise, use the default value for the column. Only applies for bulk + * inserts. + */ + insert(values, { count, defaultToNull = true } = {}) { + var _a2; + const method = "POST"; + if (count) { + this.headers.append("Prefer", `count=${count}`); + } + if (!defaultToNull) { + this.headers.append("Prefer", `missing=default`); + } + if (Array.isArray(values)) { + const columns = values.reduce((acc, x) => acc.concat(Object.keys(x)), []); + if (columns.length > 0) { + const uniqueColumns = [...new Set(columns)].map((column) => `"${column}"`); + this.url.searchParams.set("columns", uniqueColumns.join(",")); + } + } + return new PostgrestFilterBuilder_1.default({ + method, + url: this.url, + headers: this.headers, + schema: this.schema, + body: values, + fetch: (_a2 = this.fetch) !== null && _a2 !== void 0 ? _a2 : fetch + }); + } + /** + * Perform an UPSERT on the table or view. Depending on the column(s) passed + * to `onConflict`, `.upsert()` allows you to perform the equivalent of + * `.insert()` if a row with the corresponding `onConflict` columns doesn't + * exist, or if it does exist, perform an alternative action depending on + * `ignoreDuplicates`. + * + * By default, upserted rows are not returned. To return it, chain the call + * with `.select()`. + * + * @param values - The values to upsert with. Pass an object to upsert a + * single row or an array to upsert multiple rows. + * + * @param options - Named parameters + * + * @param options.onConflict - Comma-separated UNIQUE column(s) to specify how + * duplicate rows are determined. Two rows are duplicates if all the + * `onConflict` columns are equal. + * + * @param options.ignoreDuplicates - If `true`, duplicate rows are ignored. If + * `false`, duplicate rows are merged with existing rows. + * + * @param options.count - Count algorithm to use to count upserted rows. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + * + * @param options.defaultToNull - Make missing fields default to `null`. + * Otherwise, use the default value for the column. This only applies when + * inserting new rows, not when merging with existing rows under + * `ignoreDuplicates: false`. This also only applies when doing bulk upserts. + * + * @example Upsert a single row using a unique key + * ```ts + * // Upserting a single row, overwriting based on the 'username' unique column + * const { data, error } = await supabase + * .from('users') + * .upsert({ username: 'supabot' }, { onConflict: 'username' }) + * + * // Example response: + * // { + * // data: [ + * // { id: 4, message: 'bar', username: 'supabot' } + * // ], + * // error: null + * // } + * ``` + * + * @example Upsert with conflict resolution and exact row counting + * ```ts + * // Upserting and returning exact count + * const { data, error, count } = await supabase + * .from('users') + * .upsert( + * { + * id: 3, + * message: 'foo', + * username: 'supabot' + * }, + * { + * onConflict: 'username', + * count: 'exact' + * } + * ) + * + * // Example response: + * // { + * // data: [ + * // { + * // id: 42, + * // handle: "saoirse", + * // display_name: "Saoirse" + * // } + * // ], + * // count: 1, + * // error: null + * // } + * ``` + */ + upsert(values, { onConflict, ignoreDuplicates = false, count, defaultToNull = true } = {}) { + var _a2; + const method = "POST"; + this.headers.append("Prefer", `resolution=${ignoreDuplicates ? "ignore" : "merge"}-duplicates`); + if (onConflict !== void 0) + this.url.searchParams.set("on_conflict", onConflict); + if (count) { + this.headers.append("Prefer", `count=${count}`); + } + if (!defaultToNull) { + this.headers.append("Prefer", "missing=default"); + } + if (Array.isArray(values)) { + const columns = values.reduce((acc, x) => acc.concat(Object.keys(x)), []); + if (columns.length > 0) { + const uniqueColumns = [...new Set(columns)].map((column) => `"${column}"`); + this.url.searchParams.set("columns", uniqueColumns.join(",")); + } + } + return new PostgrestFilterBuilder_1.default({ + method, + url: this.url, + headers: this.headers, + schema: this.schema, + body: values, + fetch: (_a2 = this.fetch) !== null && _a2 !== void 0 ? _a2 : fetch + }); + } + /** + * Perform an UPDATE on the table or view. + * + * By default, updated rows are not returned. To return it, chain the call + * with `.select()` after filters. + * + * @param values - The values to update with + * + * @param options - Named parameters + * + * @param options.count - Count algorithm to use to count updated rows. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + update(values, { count } = {}) { + var _a2; + const method = "PATCH"; + if (count) { + this.headers.append("Prefer", `count=${count}`); + } + return new PostgrestFilterBuilder_1.default({ + method, + url: this.url, + headers: this.headers, + schema: this.schema, + body: values, + fetch: (_a2 = this.fetch) !== null && _a2 !== void 0 ? _a2 : fetch + }); + } + /** + * Perform a DELETE on the table or view. + * + * By default, deleted rows are not returned. To return it, chain the call + * with `.select()` after filters. + * + * @param options - Named parameters + * + * @param options.count - Count algorithm to use to count deleted rows. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + delete({ count } = {}) { + var _a2; + const method = "DELETE"; + if (count) { + this.headers.append("Prefer", `count=${count}`); + } + return new PostgrestFilterBuilder_1.default({ + method, + url: this.url, + headers: this.headers, + schema: this.schema, + fetch: (_a2 = this.fetch) !== null && _a2 !== void 0 ? _a2 : fetch + }); + } + }; + exports.default = PostgrestQueryBuilder; + } +}); + +// node_modules/@supabase/postgrest-js/dist/cjs/PostgrestClient.js +var require_PostgrestClient = __commonJS({ + "node_modules/@supabase/postgrest-js/dist/cjs/PostgrestClient.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var PostgrestQueryBuilder_1 = tslib_1.__importDefault(require_PostgrestQueryBuilder()); + var PostgrestFilterBuilder_1 = tslib_1.__importDefault(require_PostgrestFilterBuilder()); + var PostgrestClient = class _PostgrestClient { + // TODO: Add back shouldThrowOnError once we figure out the typings + /** + * Creates a PostgREST client. + * + * @param url - URL of the PostgREST endpoint + * @param options - Named parameters + * @param options.headers - Custom headers + * @param options.schema - Postgres schema to switch to + * @param options.fetch - Custom fetch + * @example + * ```ts + * import PostgrestClient from '@supabase/postgrest-js' + * + * const postgrest = new PostgrestClient('https://xyzcompany.supabase.co/rest/v1', { + * headers: { apikey: 'public-anon-key' }, + * schema: 'public', + * }) + * ``` + */ + constructor(url, { headers = {}, schema, fetch: fetch2 } = {}) { + this.url = url; + this.headers = new Headers(headers); + this.schemaName = schema; + this.fetch = fetch2; + } + /** + * Perform a query on a table or a view. + * + * @param relation - The table or view name to query + */ + from(relation) { + if (!relation || typeof relation !== "string" || relation.trim() === "") { + throw new Error("Invalid relation name: relation must be a non-empty string."); + } + const url = new URL(`${this.url}/${relation}`); + return new PostgrestQueryBuilder_1.default(url, { + headers: new Headers(this.headers), + schema: this.schemaName, + fetch: this.fetch + }); + } + /** + * Select a schema to query or perform an function (rpc) call. + * + * The schema needs to be on the list of exposed schemas inside Supabase. + * + * @param schema - The schema to query + */ + schema(schema) { + return new _PostgrestClient(this.url, { + headers: this.headers, + schema, + fetch: this.fetch + }); + } + /** + * Perform a function call. + * + * @param fn - The function name to call + * @param args - The arguments to pass to the function call + * @param options - Named parameters + * @param options.head - When set to `true`, `data` will not be returned. + * Useful if you only need the count. + * @param options.get - When set to `true`, the function will be called with + * read-only access mode. + * @param options.count - Count algorithm to use to count rows returned by the + * function. Only applicable for [set-returning + * functions](https://www.postgresql.org/docs/current/functions-srf.html). + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + * + * @example + * ```ts + * // For cross-schema functions where type inference fails, use overrideTypes: + * const { data } = await supabase + * .schema('schema_b') + * .rpc('function_a', {}) + * .overrideTypes<{ id: string; user_id: string }[]>() + * ``` + */ + rpc(fn, args = {}, { head = false, get = false, count } = {}) { + var _a2; + let method; + const url = new URL(`${this.url}/rpc/${fn}`); + let body; + if (head || get) { + method = head ? "HEAD" : "GET"; + Object.entries(args).filter(([_, value]) => value !== void 0).map(([name, value]) => [name, Array.isArray(value) ? `{${value.join(",")}}` : `${value}`]).forEach(([name, value]) => { + url.searchParams.append(name, value); + }); + } else { + method = "POST"; + body = args; + } + const headers = new Headers(this.headers); + if (count) { + headers.set("Prefer", `count=${count}`); + } + return new PostgrestFilterBuilder_1.default({ + method, + url, + headers, + schema: this.schemaName, + body, + fetch: (_a2 = this.fetch) !== null && _a2 !== void 0 ? _a2 : fetch + }); + } + }; + exports.default = PostgrestClient; + } +}); + +// node_modules/@supabase/postgrest-js/dist/cjs/index.js +var require_cjs = __commonJS({ + "node_modules/@supabase/postgrest-js/dist/cjs/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.PostgrestError = exports.PostgrestBuilder = exports.PostgrestTransformBuilder = exports.PostgrestFilterBuilder = exports.PostgrestQueryBuilder = exports.PostgrestClient = void 0; + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var PostgrestClient_1 = tslib_1.__importDefault(require_PostgrestClient()); + exports.PostgrestClient = PostgrestClient_1.default; + var PostgrestQueryBuilder_1 = tslib_1.__importDefault(require_PostgrestQueryBuilder()); + exports.PostgrestQueryBuilder = PostgrestQueryBuilder_1.default; + var PostgrestFilterBuilder_1 = tslib_1.__importDefault(require_PostgrestFilterBuilder()); + exports.PostgrestFilterBuilder = PostgrestFilterBuilder_1.default; + var PostgrestTransformBuilder_1 = tslib_1.__importDefault(require_PostgrestTransformBuilder()); + exports.PostgrestTransformBuilder = PostgrestTransformBuilder_1.default; + var PostgrestBuilder_1 = tslib_1.__importDefault(require_PostgrestBuilder()); + exports.PostgrestBuilder = PostgrestBuilder_1.default; + var PostgrestError_1 = tslib_1.__importDefault(require_PostgrestError()); + exports.PostgrestError = PostgrestError_1.default; + exports.default = { + PostgrestClient: PostgrestClient_1.default, + PostgrestQueryBuilder: PostgrestQueryBuilder_1.default, + PostgrestFilterBuilder: PostgrestFilterBuilder_1.default, + PostgrestTransformBuilder: PostgrestTransformBuilder_1.default, + PostgrestBuilder: PostgrestBuilder_1.default, + PostgrestError: PostgrestError_1.default + }; + } +}); + +// node_modules/@supabase/realtime-js/dist/main/lib/websocket-factory.js +var require_websocket_factory = __commonJS({ + "node_modules/@supabase/realtime-js/dist/main/lib/websocket-factory.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.WebSocketFactory = void 0; + var WebSocketFactory = class { + /** + * Static-only utility – prevent instantiation. + */ + constructor() { + } + static detectEnvironment() { + var _a2; + if (typeof WebSocket !== "undefined") { + return { type: "native", constructor: WebSocket }; + } + if (typeof globalThis !== "undefined" && typeof globalThis.WebSocket !== "undefined") { + return { type: "native", constructor: globalThis.WebSocket }; + } + if (typeof global !== "undefined" && typeof global.WebSocket !== "undefined") { + return { type: "native", constructor: global.WebSocket }; + } + if (typeof globalThis !== "undefined" && typeof globalThis.WebSocketPair !== "undefined" && typeof globalThis.WebSocket === "undefined") { + return { + type: "cloudflare", + error: "Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.", + workaround: "Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime." + }; + } + if (typeof globalThis !== "undefined" && globalThis.EdgeRuntime || typeof navigator !== "undefined" && ((_a2 = navigator.userAgent) === null || _a2 === void 0 ? void 0 : _a2.includes("Vercel-Edge"))) { + return { + type: "unsupported", + error: "Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.", + workaround: "Use serverless functions or a different deployment target for WebSocket functionality." + }; + } + if (typeof process !== "undefined") { + const processVersions = process["versions"]; + if (processVersions && processVersions["node"]) { + const versionString = processVersions["node"]; + const nodeVersion = parseInt(versionString.replace(/^v/, "").split(".")[0]); + if (nodeVersion >= 22) { + if (typeof globalThis.WebSocket !== "undefined") { + return { type: "native", constructor: globalThis.WebSocket }; + } + return { + type: "unsupported", + error: `Node.js ${nodeVersion} detected but native WebSocket not found.`, + workaround: "Provide a WebSocket implementation via the transport option." + }; + } + return { + type: "unsupported", + error: `Node.js ${nodeVersion} detected without native WebSocket support.`, + workaround: 'For Node.js < 22, install "ws" package and provide it via the transport option:\nimport ws from "ws"\nnew RealtimeClient(url, { transport: ws })' + }; + } + } + return { + type: "unsupported", + error: "Unknown JavaScript runtime without WebSocket support.", + workaround: "Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation." + }; + } + /** + * Returns the best available WebSocket constructor for the current runtime. + * + * @example + * ```ts + * const WS = WebSocketFactory.getWebSocketConstructor() + * const socket = new WS('wss://realtime.supabase.co/socket') + * ``` + */ + static getWebSocketConstructor() { + const env = this.detectEnvironment(); + if (env.constructor) { + return env.constructor; + } + let errorMessage = env.error || "WebSocket not supported in this environment."; + if (env.workaround) { + errorMessage += ` + +Suggested solution: ${env.workaround}`; + } + throw new Error(errorMessage); + } + /** + * Creates a WebSocket using the detected constructor. + * + * @example + * ```ts + * const socket = WebSocketFactory.createWebSocket('wss://realtime.supabase.co/socket') + * ``` + */ + static createWebSocket(url, protocols) { + const WS = this.getWebSocketConstructor(); + return new WS(url, protocols); + } + /** + * Detects whether the runtime can establish WebSocket connections. + * + * @example + * ```ts + * if (!WebSocketFactory.isWebSocketSupported()) { + * console.warn('Falling back to long polling') + * } + * ``` + */ + static isWebSocketSupported() { + try { + const env = this.detectEnvironment(); + return env.type === "native" || env.type === "ws"; + } catch (_a2) { + return false; + } + } + }; + exports.WebSocketFactory = WebSocketFactory; + exports.default = WebSocketFactory; + } +}); + +// node_modules/@supabase/realtime-js/dist/main/lib/version.js +var require_version = __commonJS({ + "node_modules/@supabase/realtime-js/dist/main/lib/version.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.version = void 0; + exports.version = "2.87.1"; + } +}); + +// node_modules/@supabase/realtime-js/dist/main/lib/constants.js +var require_constants2 = __commonJS({ + "node_modules/@supabase/realtime-js/dist/main/lib/constants.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CONNECTION_STATE = exports.TRANSPORTS = exports.CHANNEL_EVENTS = exports.CHANNEL_STATES = exports.SOCKET_STATES = exports.MAX_PUSH_BUFFER_SIZE = exports.WS_CLOSE_NORMAL = exports.DEFAULT_TIMEOUT = exports.VERSION = exports.DEFAULT_VSN = exports.VSN_2_0_0 = exports.VSN_1_0_0 = exports.DEFAULT_VERSION = void 0; + var version_1 = require_version(); + exports.DEFAULT_VERSION = `realtime-js/${version_1.version}`; + exports.VSN_1_0_0 = "1.0.0"; + exports.VSN_2_0_0 = "2.0.0"; + exports.DEFAULT_VSN = exports.VSN_1_0_0; + exports.VERSION = version_1.version; + exports.DEFAULT_TIMEOUT = 1e4; + exports.WS_CLOSE_NORMAL = 1e3; + exports.MAX_PUSH_BUFFER_SIZE = 100; + var SOCKET_STATES; + (function(SOCKET_STATES2) { + SOCKET_STATES2[SOCKET_STATES2["connecting"] = 0] = "connecting"; + SOCKET_STATES2[SOCKET_STATES2["open"] = 1] = "open"; + SOCKET_STATES2[SOCKET_STATES2["closing"] = 2] = "closing"; + SOCKET_STATES2[SOCKET_STATES2["closed"] = 3] = "closed"; + })(SOCKET_STATES || (exports.SOCKET_STATES = SOCKET_STATES = {})); + var CHANNEL_STATES; + (function(CHANNEL_STATES2) { + CHANNEL_STATES2["closed"] = "closed"; + CHANNEL_STATES2["errored"] = "errored"; + CHANNEL_STATES2["joined"] = "joined"; + CHANNEL_STATES2["joining"] = "joining"; + CHANNEL_STATES2["leaving"] = "leaving"; + })(CHANNEL_STATES || (exports.CHANNEL_STATES = CHANNEL_STATES = {})); + var CHANNEL_EVENTS; + (function(CHANNEL_EVENTS2) { + CHANNEL_EVENTS2["close"] = "phx_close"; + CHANNEL_EVENTS2["error"] = "phx_error"; + CHANNEL_EVENTS2["join"] = "phx_join"; + CHANNEL_EVENTS2["reply"] = "phx_reply"; + CHANNEL_EVENTS2["leave"] = "phx_leave"; + CHANNEL_EVENTS2["access_token"] = "access_token"; + })(CHANNEL_EVENTS || (exports.CHANNEL_EVENTS = CHANNEL_EVENTS = {})); + var TRANSPORTS; + (function(TRANSPORTS2) { + TRANSPORTS2["websocket"] = "websocket"; + })(TRANSPORTS || (exports.TRANSPORTS = TRANSPORTS = {})); + var CONNECTION_STATE; + (function(CONNECTION_STATE2) { + CONNECTION_STATE2["Connecting"] = "connecting"; + CONNECTION_STATE2["Open"] = "open"; + CONNECTION_STATE2["Closing"] = "closing"; + CONNECTION_STATE2["Closed"] = "closed"; + })(CONNECTION_STATE || (exports.CONNECTION_STATE = CONNECTION_STATE = {})); + } +}); + +// node_modules/@supabase/realtime-js/dist/main/lib/serializer.js +var require_serializer = __commonJS({ + "node_modules/@supabase/realtime-js/dist/main/lib/serializer.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var Serializer = class { + constructor(allowedMetadataKeys) { + this.HEADER_LENGTH = 1; + this.USER_BROADCAST_PUSH_META_LENGTH = 6; + this.KINDS = { userBroadcastPush: 3, userBroadcast: 4 }; + this.BINARY_ENCODING = 0; + this.JSON_ENCODING = 1; + this.BROADCAST_EVENT = "broadcast"; + this.allowedMetadataKeys = []; + this.allowedMetadataKeys = allowedMetadataKeys !== null && allowedMetadataKeys !== void 0 ? allowedMetadataKeys : []; + } + encode(msg, callback) { + if (msg.event === this.BROADCAST_EVENT && !(msg.payload instanceof ArrayBuffer) && typeof msg.payload.event === "string") { + return callback(this._binaryEncodeUserBroadcastPush(msg)); + } + let payload = [msg.join_ref, msg.ref, msg.topic, msg.event, msg.payload]; + return callback(JSON.stringify(payload)); + } + _binaryEncodeUserBroadcastPush(message) { + var _a2; + if (this._isArrayBuffer((_a2 = message.payload) === null || _a2 === void 0 ? void 0 : _a2.payload)) { + return this._encodeBinaryUserBroadcastPush(message); + } else { + return this._encodeJsonUserBroadcastPush(message); + } + } + _encodeBinaryUserBroadcastPush(message) { + var _a2, _b; + const userPayload = (_b = (_a2 = message.payload) === null || _a2 === void 0 ? void 0 : _a2.payload) !== null && _b !== void 0 ? _b : new ArrayBuffer(0); + return this._encodeUserBroadcastPush(message, this.BINARY_ENCODING, userPayload); + } + _encodeJsonUserBroadcastPush(message) { + var _a2, _b; + const userPayload = (_b = (_a2 = message.payload) === null || _a2 === void 0 ? void 0 : _a2.payload) !== null && _b !== void 0 ? _b : {}; + const encoder2 = new TextEncoder(); + const encodedUserPayload = encoder2.encode(JSON.stringify(userPayload)).buffer; + return this._encodeUserBroadcastPush(message, this.JSON_ENCODING, encodedUserPayload); + } + _encodeUserBroadcastPush(message, encodingType, encodedPayload) { + var _a2, _b; + const topic = message.topic; + const ref = (_a2 = message.ref) !== null && _a2 !== void 0 ? _a2 : ""; + const joinRef = (_b = message.join_ref) !== null && _b !== void 0 ? _b : ""; + const userEvent = message.payload.event; + const rest = this.allowedMetadataKeys ? this._pick(message.payload, this.allowedMetadataKeys) : {}; + const metadata = Object.keys(rest).length === 0 ? "" : JSON.stringify(rest); + if (joinRef.length > 255) { + throw new Error(`joinRef length ${joinRef.length} exceeds maximum of 255`); + } + if (ref.length > 255) { + throw new Error(`ref length ${ref.length} exceeds maximum of 255`); + } + if (topic.length > 255) { + throw new Error(`topic length ${topic.length} exceeds maximum of 255`); + } + if (userEvent.length > 255) { + throw new Error(`userEvent length ${userEvent.length} exceeds maximum of 255`); + } + if (metadata.length > 255) { + throw new Error(`metadata length ${metadata.length} exceeds maximum of 255`); + } + const metaLength = this.USER_BROADCAST_PUSH_META_LENGTH + joinRef.length + ref.length + topic.length + userEvent.length + metadata.length; + const header = new ArrayBuffer(this.HEADER_LENGTH + metaLength); + let view2 = new DataView(header); + let offset = 0; + view2.setUint8(offset++, this.KINDS.userBroadcastPush); + view2.setUint8(offset++, joinRef.length); + view2.setUint8(offset++, ref.length); + view2.setUint8(offset++, topic.length); + view2.setUint8(offset++, userEvent.length); + view2.setUint8(offset++, metadata.length); + view2.setUint8(offset++, encodingType); + Array.from(joinRef, (char) => view2.setUint8(offset++, char.charCodeAt(0))); + Array.from(ref, (char) => view2.setUint8(offset++, char.charCodeAt(0))); + Array.from(topic, (char) => view2.setUint8(offset++, char.charCodeAt(0))); + Array.from(userEvent, (char) => view2.setUint8(offset++, char.charCodeAt(0))); + Array.from(metadata, (char) => view2.setUint8(offset++, char.charCodeAt(0))); + var combined = new Uint8Array(header.byteLength + encodedPayload.byteLength); + combined.set(new Uint8Array(header), 0); + combined.set(new Uint8Array(encodedPayload), header.byteLength); + return combined.buffer; + } + decode(rawPayload, callback) { + if (this._isArrayBuffer(rawPayload)) { + let result = this._binaryDecode(rawPayload); + return callback(result); + } + if (typeof rawPayload === "string") { + const jsonPayload = JSON.parse(rawPayload); + const [join_ref, ref, topic, event, payload] = jsonPayload; + return callback({ join_ref, ref, topic, event, payload }); + } + return callback({}); + } + _binaryDecode(buffer) { + const view2 = new DataView(buffer); + const kind = view2.getUint8(0); + const decoder = new TextDecoder(); + switch (kind) { + case this.KINDS.userBroadcast: + return this._decodeUserBroadcast(buffer, view2, decoder); + } + } + _decodeUserBroadcast(buffer, view2, decoder) { + const topicSize = view2.getUint8(1); + const userEventSize = view2.getUint8(2); + const metadataSize = view2.getUint8(3); + const payloadEncoding = view2.getUint8(4); + let offset = this.HEADER_LENGTH + 4; + const topic = decoder.decode(buffer.slice(offset, offset + topicSize)); + offset = offset + topicSize; + const userEvent = decoder.decode(buffer.slice(offset, offset + userEventSize)); + offset = offset + userEventSize; + const metadata = decoder.decode(buffer.slice(offset, offset + metadataSize)); + offset = offset + metadataSize; + const payload = buffer.slice(offset, buffer.byteLength); + const parsedPayload = payloadEncoding === this.JSON_ENCODING ? JSON.parse(decoder.decode(payload)) : payload; + const data = { + type: this.BROADCAST_EVENT, + event: userEvent, + payload: parsedPayload + }; + if (metadataSize > 0) { + data["meta"] = JSON.parse(metadata); + } + return { join_ref: null, ref: null, topic, event: this.BROADCAST_EVENT, payload: data }; + } + _isArrayBuffer(buffer) { + var _a2; + return buffer instanceof ArrayBuffer || ((_a2 = buffer === null || buffer === void 0 ? void 0 : buffer.constructor) === null || _a2 === void 0 ? void 0 : _a2.name) === "ArrayBuffer"; + } + _pick(obj, keys) { + if (!obj || typeof obj !== "object") { + return {}; + } + return Object.fromEntries(Object.entries(obj).filter(([key]) => keys.includes(key))); + } + }; + exports.default = Serializer; + } +}); + +// node_modules/@supabase/realtime-js/dist/main/lib/timer.js +var require_timer = __commonJS({ + "node_modules/@supabase/realtime-js/dist/main/lib/timer.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var Timer = class { + constructor(callback, timerCalc) { + this.callback = callback; + this.timerCalc = timerCalc; + this.timer = void 0; + this.tries = 0; + this.callback = callback; + this.timerCalc = timerCalc; + } + reset() { + this.tries = 0; + clearTimeout(this.timer); + this.timer = void 0; + } + // Cancels any previous scheduleTimeout and schedules callback + scheduleTimeout() { + clearTimeout(this.timer); + this.timer = setTimeout(() => { + this.tries = this.tries + 1; + this.callback(); + }, this.timerCalc(this.tries + 1)); + } + }; + exports.default = Timer; + } +}); + +// node_modules/@supabase/realtime-js/dist/main/lib/transformers.js +var require_transformers = __commonJS({ + "node_modules/@supabase/realtime-js/dist/main/lib/transformers.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.httpEndpointURL = exports.toTimestampString = exports.toArray = exports.toJson = exports.toNumber = exports.toBoolean = exports.convertCell = exports.convertColumn = exports.convertChangeData = exports.PostgresTypes = void 0; + var PostgresTypes; + (function(PostgresTypes2) { + PostgresTypes2["abstime"] = "abstime"; + PostgresTypes2["bool"] = "bool"; + PostgresTypes2["date"] = "date"; + PostgresTypes2["daterange"] = "daterange"; + PostgresTypes2["float4"] = "float4"; + PostgresTypes2["float8"] = "float8"; + PostgresTypes2["int2"] = "int2"; + PostgresTypes2["int4"] = "int4"; + PostgresTypes2["int4range"] = "int4range"; + PostgresTypes2["int8"] = "int8"; + PostgresTypes2["int8range"] = "int8range"; + PostgresTypes2["json"] = "json"; + PostgresTypes2["jsonb"] = "jsonb"; + PostgresTypes2["money"] = "money"; + PostgresTypes2["numeric"] = "numeric"; + PostgresTypes2["oid"] = "oid"; + PostgresTypes2["reltime"] = "reltime"; + PostgresTypes2["text"] = "text"; + PostgresTypes2["time"] = "time"; + PostgresTypes2["timestamp"] = "timestamp"; + PostgresTypes2["timestamptz"] = "timestamptz"; + PostgresTypes2["timetz"] = "timetz"; + PostgresTypes2["tsrange"] = "tsrange"; + PostgresTypes2["tstzrange"] = "tstzrange"; + })(PostgresTypes || (exports.PostgresTypes = PostgresTypes = {})); + var convertChangeData = (columns, record, options = {}) => { + var _a2; + const skipTypes = (_a2 = options.skipTypes) !== null && _a2 !== void 0 ? _a2 : []; + if (!record) { + return {}; + } + return Object.keys(record).reduce((acc, rec_key) => { + acc[rec_key] = (0, exports.convertColumn)(rec_key, columns, record, skipTypes); + return acc; + }, {}); + }; + exports.convertChangeData = convertChangeData; + var convertColumn = (columnName, columns, record, skipTypes) => { + const column = columns.find((x) => x.name === columnName); + const colType = column === null || column === void 0 ? void 0 : column.type; + const value = record[columnName]; + if (colType && !skipTypes.includes(colType)) { + return (0, exports.convertCell)(colType, value); + } + return noop(value); + }; + exports.convertColumn = convertColumn; + var convertCell = (type, value) => { + if (type.charAt(0) === "_") { + const dataType = type.slice(1, type.length); + return (0, exports.toArray)(value, dataType); + } + switch (type) { + case PostgresTypes.bool: + return (0, exports.toBoolean)(value); + case PostgresTypes.float4: + case PostgresTypes.float8: + case PostgresTypes.int2: + case PostgresTypes.int4: + case PostgresTypes.int8: + case PostgresTypes.numeric: + case PostgresTypes.oid: + return (0, exports.toNumber)(value); + case PostgresTypes.json: + case PostgresTypes.jsonb: + return (0, exports.toJson)(value); + case PostgresTypes.timestamp: + return (0, exports.toTimestampString)(value); + // Format to be consistent with PostgREST + case PostgresTypes.abstime: + // To allow users to cast it based on Timezone + case PostgresTypes.date: + // To allow users to cast it based on Timezone + case PostgresTypes.daterange: + case PostgresTypes.int4range: + case PostgresTypes.int8range: + case PostgresTypes.money: + case PostgresTypes.reltime: + // To allow users to cast it based on Timezone + case PostgresTypes.text: + case PostgresTypes.time: + // To allow users to cast it based on Timezone + case PostgresTypes.timestamptz: + // To allow users to cast it based on Timezone + case PostgresTypes.timetz: + // To allow users to cast it based on Timezone + case PostgresTypes.tsrange: + case PostgresTypes.tstzrange: + return noop(value); + default: + return noop(value); + } + }; + exports.convertCell = convertCell; + var noop = (value) => { + return value; + }; + var toBoolean = (value) => { + switch (value) { + case "t": + return true; + case "f": + return false; + default: + return value; + } + }; + exports.toBoolean = toBoolean; + var toNumber = (value) => { + if (typeof value === "string") { + const parsedValue = parseFloat(value); + if (!Number.isNaN(parsedValue)) { + return parsedValue; + } + } + return value; + }; + exports.toNumber = toNumber; + var toJson = (value) => { + if (typeof value === "string") { + try { + return JSON.parse(value); + } catch (error) { + console.log(`JSON parse error: ${error}`); + return value; + } + } + return value; + }; + exports.toJson = toJson; + var toArray2 = (value, type) => { + if (typeof value !== "string") { + return value; + } + const lastIdx = value.length - 1; + const closeBrace = value[lastIdx]; + const openBrace = value[0]; + if (openBrace === "{" && closeBrace === "}") { + let arr3; + const valTrim = value.slice(1, lastIdx); + try { + arr3 = JSON.parse("[" + valTrim + "]"); + } catch (_) { + arr3 = valTrim ? valTrim.split(",") : []; + } + return arr3.map((val) => (0, exports.convertCell)(type, val)); + } + return value; + }; + exports.toArray = toArray2; + var toTimestampString = (value) => { + if (typeof value === "string") { + return value.replace(" ", "T"); + } + return value; + }; + exports.toTimestampString = toTimestampString; + var httpEndpointURL = (socketUrl) => { + const wsUrl = new URL(socketUrl); + wsUrl.protocol = wsUrl.protocol.replace(/^ws/i, "http"); + wsUrl.pathname = wsUrl.pathname.replace(/\/+$/, "").replace(/\/socket\/websocket$/i, "").replace(/\/socket$/i, "").replace(/\/websocket$/i, ""); + if (wsUrl.pathname === "" || wsUrl.pathname === "/") { + wsUrl.pathname = "/api/broadcast"; + } else { + wsUrl.pathname = wsUrl.pathname + "/api/broadcast"; + } + return wsUrl.href; + }; + exports.httpEndpointURL = httpEndpointURL; + } +}); + +// node_modules/@supabase/realtime-js/dist/main/lib/push.js +var require_push = __commonJS({ + "node_modules/@supabase/realtime-js/dist/main/lib/push.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var constants_1 = require_constants2(); + var Push = class { + /** + * Initializes the Push + * + * @param channel The Channel + * @param event The event, for example `"phx_join"` + * @param payload The payload, for example `{user_id: 123}` + * @param timeout The push timeout in milliseconds + */ + constructor(channel, event, payload = {}, timeout = constants_1.DEFAULT_TIMEOUT) { + this.channel = channel; + this.event = event; + this.payload = payload; + this.timeout = timeout; + this.sent = false; + this.timeoutTimer = void 0; + this.ref = ""; + this.receivedResp = null; + this.recHooks = []; + this.refEvent = null; + } + resend(timeout) { + this.timeout = timeout; + this._cancelRefEvent(); + this.ref = ""; + this.refEvent = null; + this.receivedResp = null; + this.sent = false; + this.send(); + } + send() { + if (this._hasReceived("timeout")) { + return; + } + this.startTimeout(); + this.sent = true; + this.channel.socket.push({ + topic: this.channel.topic, + event: this.event, + payload: this.payload, + ref: this.ref, + join_ref: this.channel._joinRef() + }); + } + updatePayload(payload) { + this.payload = Object.assign(Object.assign({}, this.payload), payload); + } + receive(status, callback) { + var _a2; + if (this._hasReceived(status)) { + callback((_a2 = this.receivedResp) === null || _a2 === void 0 ? void 0 : _a2.response); + } + this.recHooks.push({ status, callback }); + return this; + } + startTimeout() { + if (this.timeoutTimer) { + return; + } + this.ref = this.channel.socket._makeRef(); + this.refEvent = this.channel._replyEventName(this.ref); + const callback = (payload) => { + this._cancelRefEvent(); + this._cancelTimeout(); + this.receivedResp = payload; + this._matchReceive(payload); + }; + this.channel._on(this.refEvent, {}, callback); + this.timeoutTimer = setTimeout(() => { + this.trigger("timeout", {}); + }, this.timeout); + } + trigger(status, response) { + if (this.refEvent) + this.channel._trigger(this.refEvent, { status, response }); + } + destroy() { + this._cancelRefEvent(); + this._cancelTimeout(); + } + _cancelRefEvent() { + if (!this.refEvent) { + return; + } + this.channel._off(this.refEvent, {}); + } + _cancelTimeout() { + clearTimeout(this.timeoutTimer); + this.timeoutTimer = void 0; + } + _matchReceive({ status, response }) { + this.recHooks.filter((h) => h.status === status).forEach((h) => h.callback(response)); + } + _hasReceived(status) { + return this.receivedResp && this.receivedResp.status === status; + } + }; + exports.default = Push; + } +}); + +// node_modules/@supabase/realtime-js/dist/main/RealtimePresence.js +var require_RealtimePresence = __commonJS({ + "node_modules/@supabase/realtime-js/dist/main/RealtimePresence.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.REALTIME_PRESENCE_LISTEN_EVENTS = void 0; + var REALTIME_PRESENCE_LISTEN_EVENTS2; + (function(REALTIME_PRESENCE_LISTEN_EVENTS3) { + REALTIME_PRESENCE_LISTEN_EVENTS3["SYNC"] = "sync"; + REALTIME_PRESENCE_LISTEN_EVENTS3["JOIN"] = "join"; + REALTIME_PRESENCE_LISTEN_EVENTS3["LEAVE"] = "leave"; + })(REALTIME_PRESENCE_LISTEN_EVENTS2 || (exports.REALTIME_PRESENCE_LISTEN_EVENTS = REALTIME_PRESENCE_LISTEN_EVENTS2 = {})); + var RealtimePresence2 = class _RealtimePresence { + /** + * Creates a Presence helper that keeps the local presence state in sync with the server. + * + * @param channel - The realtime channel to bind to. + * @param opts - Optional custom event names, e.g. `{ events: { state: 'state', diff: 'diff' } }`. + * + * @example + * ```ts + * const presence = new RealtimePresence(channel) + * + * channel.on('presence', ({ event, key }) => { + * console.log(`Presence ${event} on ${key}`) + * }) + * ``` + */ + constructor(channel, opts) { + this.channel = channel; + this.state = {}; + this.pendingDiffs = []; + this.joinRef = null; + this.enabled = false; + this.caller = { + onJoin: () => { + }, + onLeave: () => { + }, + onSync: () => { + } + }; + const events = (opts === null || opts === void 0 ? void 0 : opts.events) || { + state: "presence_state", + diff: "presence_diff" + }; + this.channel._on(events.state, {}, (newState) => { + const { onJoin, onLeave, onSync } = this.caller; + this.joinRef = this.channel._joinRef(); + this.state = _RealtimePresence.syncState(this.state, newState, onJoin, onLeave); + this.pendingDiffs.forEach((diff) => { + this.state = _RealtimePresence.syncDiff(this.state, diff, onJoin, onLeave); + }); + this.pendingDiffs = []; + onSync(); + }); + this.channel._on(events.diff, {}, (diff) => { + const { onJoin, onLeave, onSync } = this.caller; + if (this.inPendingSyncState()) { + this.pendingDiffs.push(diff); + } else { + this.state = _RealtimePresence.syncDiff(this.state, diff, onJoin, onLeave); + onSync(); + } + }); + this.onJoin((key, currentPresences, newPresences) => { + this.channel._trigger("presence", { + event: "join", + key, + currentPresences, + newPresences + }); + }); + this.onLeave((key, currentPresences, leftPresences) => { + this.channel._trigger("presence", { + event: "leave", + key, + currentPresences, + leftPresences + }); + }); + this.onSync(() => { + this.channel._trigger("presence", { event: "sync" }); + }); + } + /** + * Used to sync the list of presences on the server with the + * client's state. + * + * An optional `onJoin` and `onLeave` callback can be provided to + * react to changes in the client's local presences across + * disconnects and reconnects with the server. + * + * @internal + */ + static syncState(currentState, newState, onJoin, onLeave) { + const state = this.cloneDeep(currentState); + const transformedState = this.transformState(newState); + const joins = {}; + const leaves = {}; + this.map(state, (key, presences) => { + if (!transformedState[key]) { + leaves[key] = presences; + } + }); + this.map(transformedState, (key, newPresences) => { + const currentPresences = state[key]; + if (currentPresences) { + const newPresenceRefs = newPresences.map((m) => m.presence_ref); + const curPresenceRefs = currentPresences.map((m) => m.presence_ref); + const joinedPresences = newPresences.filter((m) => curPresenceRefs.indexOf(m.presence_ref) < 0); + const leftPresences = currentPresences.filter((m) => newPresenceRefs.indexOf(m.presence_ref) < 0); + if (joinedPresences.length > 0) { + joins[key] = joinedPresences; + } + if (leftPresences.length > 0) { + leaves[key] = leftPresences; + } + } else { + joins[key] = newPresences; + } + }); + return this.syncDiff(state, { joins, leaves }, onJoin, onLeave); + } + /** + * Used to sync a diff of presence join and leave events from the + * server, as they happen. + * + * Like `syncState`, `syncDiff` accepts optional `onJoin` and + * `onLeave` callbacks to react to a user joining or leaving from a + * device. + * + * @internal + */ + static syncDiff(state, diff, onJoin, onLeave) { + const { joins, leaves } = { + joins: this.transformState(diff.joins), + leaves: this.transformState(diff.leaves) + }; + if (!onJoin) { + onJoin = () => { + }; + } + if (!onLeave) { + onLeave = () => { + }; + } + this.map(joins, (key, newPresences) => { + var _a2; + const currentPresences = (_a2 = state[key]) !== null && _a2 !== void 0 ? _a2 : []; + state[key] = this.cloneDeep(newPresences); + if (currentPresences.length > 0) { + const joinedPresenceRefs = state[key].map((m) => m.presence_ref); + const curPresences = currentPresences.filter((m) => joinedPresenceRefs.indexOf(m.presence_ref) < 0); + state[key].unshift(...curPresences); + } + onJoin(key, currentPresences, newPresences); + }); + this.map(leaves, (key, leftPresences) => { + let currentPresences = state[key]; + if (!currentPresences) + return; + const presenceRefsToRemove = leftPresences.map((m) => m.presence_ref); + currentPresences = currentPresences.filter((m) => presenceRefsToRemove.indexOf(m.presence_ref) < 0); + state[key] = currentPresences; + onLeave(key, currentPresences, leftPresences); + if (currentPresences.length === 0) + delete state[key]; + }); + return state; + } + /** @internal */ + static map(obj, func) { + return Object.getOwnPropertyNames(obj).map((key) => func(key, obj[key])); + } + /** + * Remove 'metas' key + * Change 'phx_ref' to 'presence_ref' + * Remove 'phx_ref' and 'phx_ref_prev' + * + * @example + * // returns { + * abc123: [ + * { presence_ref: '2', user_id: 1 }, + * { presence_ref: '3', user_id: 2 } + * ] + * } + * RealtimePresence.transformState({ + * abc123: { + * metas: [ + * { phx_ref: '2', phx_ref_prev: '1' user_id: 1 }, + * { phx_ref: '3', user_id: 2 } + * ] + * } + * }) + * + * @internal + */ + static transformState(state) { + state = this.cloneDeep(state); + return Object.getOwnPropertyNames(state).reduce((newState, key) => { + const presences = state[key]; + if ("metas" in presences) { + newState[key] = presences.metas.map((presence) => { + presence["presence_ref"] = presence["phx_ref"]; + delete presence["phx_ref"]; + delete presence["phx_ref_prev"]; + return presence; + }); + } else { + newState[key] = presences; + } + return newState; + }, {}); + } + /** @internal */ + static cloneDeep(obj) { + return JSON.parse(JSON.stringify(obj)); + } + /** @internal */ + onJoin(callback) { + this.caller.onJoin = callback; + } + /** @internal */ + onLeave(callback) { + this.caller.onLeave = callback; + } + /** @internal */ + onSync(callback) { + this.caller.onSync = callback; + } + /** @internal */ + inPendingSyncState() { + return !this.joinRef || this.joinRef !== this.channel._joinRef(); + } + }; + exports.default = RealtimePresence2; + } +}); + +// node_modules/@supabase/realtime-js/dist/main/RealtimeChannel.js +var require_RealtimeChannel = __commonJS({ + "node_modules/@supabase/realtime-js/dist/main/RealtimeChannel.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.REALTIME_CHANNEL_STATES = exports.REALTIME_SUBSCRIBE_STATES = exports.REALTIME_LISTEN_TYPES = exports.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT = void 0; + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var constants_1 = require_constants2(); + var push_1 = tslib_1.__importDefault(require_push()); + var timer_1 = tslib_1.__importDefault(require_timer()); + var RealtimePresence_1 = tslib_1.__importDefault(require_RealtimePresence()); + var Transformers = tslib_1.__importStar(require_transformers()); + var transformers_1 = require_transformers(); + var REALTIME_POSTGRES_CHANGES_LISTEN_EVENT2; + (function(REALTIME_POSTGRES_CHANGES_LISTEN_EVENT3) { + REALTIME_POSTGRES_CHANGES_LISTEN_EVENT3["ALL"] = "*"; + REALTIME_POSTGRES_CHANGES_LISTEN_EVENT3["INSERT"] = "INSERT"; + REALTIME_POSTGRES_CHANGES_LISTEN_EVENT3["UPDATE"] = "UPDATE"; + REALTIME_POSTGRES_CHANGES_LISTEN_EVENT3["DELETE"] = "DELETE"; + })(REALTIME_POSTGRES_CHANGES_LISTEN_EVENT2 || (exports.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT = REALTIME_POSTGRES_CHANGES_LISTEN_EVENT2 = {})); + var REALTIME_LISTEN_TYPES2; + (function(REALTIME_LISTEN_TYPES3) { + REALTIME_LISTEN_TYPES3["BROADCAST"] = "broadcast"; + REALTIME_LISTEN_TYPES3["PRESENCE"] = "presence"; + REALTIME_LISTEN_TYPES3["POSTGRES_CHANGES"] = "postgres_changes"; + REALTIME_LISTEN_TYPES3["SYSTEM"] = "system"; + })(REALTIME_LISTEN_TYPES2 || (exports.REALTIME_LISTEN_TYPES = REALTIME_LISTEN_TYPES2 = {})); + var REALTIME_SUBSCRIBE_STATES2; + (function(REALTIME_SUBSCRIBE_STATES3) { + REALTIME_SUBSCRIBE_STATES3["SUBSCRIBED"] = "SUBSCRIBED"; + REALTIME_SUBSCRIBE_STATES3["TIMED_OUT"] = "TIMED_OUT"; + REALTIME_SUBSCRIBE_STATES3["CLOSED"] = "CLOSED"; + REALTIME_SUBSCRIBE_STATES3["CHANNEL_ERROR"] = "CHANNEL_ERROR"; + })(REALTIME_SUBSCRIBE_STATES2 || (exports.REALTIME_SUBSCRIBE_STATES = REALTIME_SUBSCRIBE_STATES2 = {})); + exports.REALTIME_CHANNEL_STATES = constants_1.CHANNEL_STATES; + var RealtimeChannel2 = class _RealtimeChannel { + /** + * Creates a channel that can broadcast messages, sync presence, and listen to Postgres changes. + * + * The topic determines which realtime stream you are subscribing to. Config options let you + * enable acknowledgement for broadcasts, presence tracking, or private channels. + * + * @example + * ```ts + * import RealtimeClient from '@supabase/realtime-js' + * + * const client = new RealtimeClient('https://xyzcompany.supabase.co/realtime/v1', { + * params: { apikey: 'public-anon-key' }, + * }) + * const channel = new RealtimeChannel('realtime:public:messages', { config: {} }, client) + * ``` + */ + constructor(topic, params = { config: {} }, socket) { + var _a2, _b; + this.topic = topic; + this.params = params; + this.socket = socket; + this.bindings = {}; + this.state = constants_1.CHANNEL_STATES.closed; + this.joinedOnce = false; + this.pushBuffer = []; + this.subTopic = topic.replace(/^realtime:/i, ""); + this.params.config = Object.assign({ + broadcast: { ack: false, self: false }, + presence: { key: "", enabled: false }, + private: false + }, params.config); + this.timeout = this.socket.timeout; + this.joinPush = new push_1.default(this, constants_1.CHANNEL_EVENTS.join, this.params, this.timeout); + this.rejoinTimer = new timer_1.default(() => this._rejoinUntilConnected(), this.socket.reconnectAfterMs); + this.joinPush.receive("ok", () => { + this.state = constants_1.CHANNEL_STATES.joined; + this.rejoinTimer.reset(); + this.pushBuffer.forEach((pushEvent) => pushEvent.send()); + this.pushBuffer = []; + }); + this._onClose(() => { + this.rejoinTimer.reset(); + this.socket.log("channel", `close ${this.topic} ${this._joinRef()}`); + this.state = constants_1.CHANNEL_STATES.closed; + this.socket._remove(this); + }); + this._onError((reason) => { + if (this._isLeaving() || this._isClosed()) { + return; + } + this.socket.log("channel", `error ${this.topic}`, reason); + this.state = constants_1.CHANNEL_STATES.errored; + this.rejoinTimer.scheduleTimeout(); + }); + this.joinPush.receive("timeout", () => { + if (!this._isJoining()) { + return; + } + this.socket.log("channel", `timeout ${this.topic}`, this.joinPush.timeout); + this.state = constants_1.CHANNEL_STATES.errored; + this.rejoinTimer.scheduleTimeout(); + }); + this.joinPush.receive("error", (reason) => { + if (this._isLeaving() || this._isClosed()) { + return; + } + this.socket.log("channel", `error ${this.topic}`, reason); + this.state = constants_1.CHANNEL_STATES.errored; + this.rejoinTimer.scheduleTimeout(); + }); + this._on(constants_1.CHANNEL_EVENTS.reply, {}, (payload, ref) => { + this._trigger(this._replyEventName(ref), payload); + }); + this.presence = new RealtimePresence_1.default(this); + this.broadcastEndpointURL = (0, transformers_1.httpEndpointURL)(this.socket.endPoint); + this.private = this.params.config.private || false; + if (!this.private && ((_b = (_a2 = this.params.config) === null || _a2 === void 0 ? void 0 : _a2.broadcast) === null || _b === void 0 ? void 0 : _b.replay)) { + throw `tried to use replay on public channel '${this.topic}'. It must be a private channel.`; + } + } + /** Subscribe registers your client with the server */ + subscribe(callback, timeout = this.timeout) { + var _a2, _b, _c; + if (!this.socket.isConnected()) { + this.socket.connect(); + } + if (this.state == constants_1.CHANNEL_STATES.closed) { + const { config: { broadcast, presence, private: isPrivate } } = this.params; + const postgres_changes = (_b = (_a2 = this.bindings.postgres_changes) === null || _a2 === void 0 ? void 0 : _a2.map((r) => r.filter)) !== null && _b !== void 0 ? _b : []; + const presence_enabled = !!this.bindings[REALTIME_LISTEN_TYPES2.PRESENCE] && this.bindings[REALTIME_LISTEN_TYPES2.PRESENCE].length > 0 || ((_c = this.params.config.presence) === null || _c === void 0 ? void 0 : _c.enabled) === true; + const accessTokenPayload = {}; + const config2 = { + broadcast, + presence: Object.assign(Object.assign({}, presence), { enabled: presence_enabled }), + postgres_changes, + private: isPrivate + }; + if (this.socket.accessTokenValue) { + accessTokenPayload.access_token = this.socket.accessTokenValue; + } + this._onError((e) => callback === null || callback === void 0 ? void 0 : callback(REALTIME_SUBSCRIBE_STATES2.CHANNEL_ERROR, e)); + this._onClose(() => callback === null || callback === void 0 ? void 0 : callback(REALTIME_SUBSCRIBE_STATES2.CLOSED)); + this.updateJoinPayload(Object.assign({ config: config2 }, accessTokenPayload)); + this.joinedOnce = true; + this._rejoin(timeout); + this.joinPush.receive("ok", async ({ postgres_changes: postgres_changes2 }) => { + var _a3; + if (!this.socket._isManualToken()) { + this.socket.setAuth(); + } + if (postgres_changes2 === void 0) { + callback === null || callback === void 0 ? void 0 : callback(REALTIME_SUBSCRIBE_STATES2.SUBSCRIBED); + return; + } else { + const clientPostgresBindings = this.bindings.postgres_changes; + const bindingsLen = (_a3 = clientPostgresBindings === null || clientPostgresBindings === void 0 ? void 0 : clientPostgresBindings.length) !== null && _a3 !== void 0 ? _a3 : 0; + const newPostgresBindings = []; + for (let i = 0; i < bindingsLen; i++) { + const clientPostgresBinding = clientPostgresBindings[i]; + const { filter: { event, schema, table, filter } } = clientPostgresBinding; + const serverPostgresFilter = postgres_changes2 && postgres_changes2[i]; + if (serverPostgresFilter && serverPostgresFilter.event === event && _RealtimeChannel.isFilterValueEqual(serverPostgresFilter.schema, schema) && _RealtimeChannel.isFilterValueEqual(serverPostgresFilter.table, table) && _RealtimeChannel.isFilterValueEqual(serverPostgresFilter.filter, filter)) { + newPostgresBindings.push(Object.assign(Object.assign({}, clientPostgresBinding), { id: serverPostgresFilter.id })); + } else { + this.unsubscribe(); + this.state = constants_1.CHANNEL_STATES.errored; + callback === null || callback === void 0 ? void 0 : callback(REALTIME_SUBSCRIBE_STATES2.CHANNEL_ERROR, new Error("mismatch between server and client bindings for postgres changes")); + return; + } + } + this.bindings.postgres_changes = newPostgresBindings; + callback && callback(REALTIME_SUBSCRIBE_STATES2.SUBSCRIBED); + return; + } + }).receive("error", (error) => { + this.state = constants_1.CHANNEL_STATES.errored; + callback === null || callback === void 0 ? void 0 : callback(REALTIME_SUBSCRIBE_STATES2.CHANNEL_ERROR, new Error(JSON.stringify(Object.values(error).join(", ") || "error"))); + return; + }).receive("timeout", () => { + callback === null || callback === void 0 ? void 0 : callback(REALTIME_SUBSCRIBE_STATES2.TIMED_OUT); + return; + }); + } + return this; + } + /** + * Returns the current presence state for this channel. + * + * The shape is a map keyed by presence key (for example a user id) where each entry contains the + * tracked metadata for that user. + */ + presenceState() { + return this.presence.state; + } + /** + * Sends the supplied payload to the presence tracker so other subscribers can see that this + * client is online. Use `untrack` to stop broadcasting presence for the same key. + */ + async track(payload, opts = {}) { + return await this.send({ + type: "presence", + event: "track", + payload + }, opts.timeout || this.timeout); + } + /** + * Removes the current presence state for this client. + */ + async untrack(opts = {}) { + return await this.send({ + type: "presence", + event: "untrack" + }, opts); + } + on(type, filter, callback) { + if (this.state === constants_1.CHANNEL_STATES.joined && type === REALTIME_LISTEN_TYPES2.PRESENCE) { + this.socket.log("channel", `resubscribe to ${this.topic} due to change in presence callbacks on joined channel`); + this.unsubscribe().then(async () => await this.subscribe()); + } + return this._on(type, filter, callback); + } + /** + * Sends a broadcast message explicitly via REST API. + * + * This method always uses the REST API endpoint regardless of WebSocket connection state. + * Useful when you want to guarantee REST delivery or when gradually migrating from implicit REST fallback. + * + * @param event The name of the broadcast event + * @param payload Payload to be sent (required) + * @param opts Options including timeout + * @returns Promise resolving to object with success status, and error details if failed + */ + async httpSend(event, payload, opts = {}) { + var _a2; + const authorization = this.socket.accessTokenValue ? `Bearer ${this.socket.accessTokenValue}` : ""; + if (payload === void 0 || payload === null) { + return Promise.reject("Payload is required for httpSend()"); + } + const options = { + method: "POST", + headers: { + Authorization: authorization, + apikey: this.socket.apiKey ? this.socket.apiKey : "", + "Content-Type": "application/json" + }, + body: JSON.stringify({ + messages: [ + { + topic: this.subTopic, + event, + payload, + private: this.private + } + ] + }) + }; + const response = await this._fetchWithTimeout(this.broadcastEndpointURL, options, (_a2 = opts.timeout) !== null && _a2 !== void 0 ? _a2 : this.timeout); + if (response.status === 202) { + return { success: true }; + } + let errorMessage = response.statusText; + try { + const errorBody = await response.json(); + errorMessage = errorBody.error || errorBody.message || errorMessage; + } catch (_b) { + } + return Promise.reject(new Error(errorMessage)); + } + /** + * Sends a message into the channel. + * + * @param args Arguments to send to channel + * @param args.type The type of event to send + * @param args.event The name of the event being sent + * @param args.payload Payload to be sent + * @param opts Options to be used during the send process + */ + async send(args, opts = {}) { + var _a2, _b; + if (!this._canPush() && args.type === "broadcast") { + console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery."); + const { event, payload: endpoint_payload } = args; + const authorization = this.socket.accessTokenValue ? `Bearer ${this.socket.accessTokenValue}` : ""; + const options = { + method: "POST", + headers: { + Authorization: authorization, + apikey: this.socket.apiKey ? this.socket.apiKey : "", + "Content-Type": "application/json" + }, + body: JSON.stringify({ + messages: [ + { + topic: this.subTopic, + event, + payload: endpoint_payload, + private: this.private + } + ] + }) + }; + try { + const response = await this._fetchWithTimeout(this.broadcastEndpointURL, options, (_a2 = opts.timeout) !== null && _a2 !== void 0 ? _a2 : this.timeout); + await ((_b = response.body) === null || _b === void 0 ? void 0 : _b.cancel()); + return response.ok ? "ok" : "error"; + } catch (error) { + if (error.name === "AbortError") { + return "timed out"; + } else { + return "error"; + } + } + } else { + return new Promise((resolve) => { + var _a3, _b2, _c; + const push2 = this._push(args.type, args, opts.timeout || this.timeout); + if (args.type === "broadcast" && !((_c = (_b2 = (_a3 = this.params) === null || _a3 === void 0 ? void 0 : _a3.config) === null || _b2 === void 0 ? void 0 : _b2.broadcast) === null || _c === void 0 ? void 0 : _c.ack)) { + resolve("ok"); + } + push2.receive("ok", () => resolve("ok")); + push2.receive("error", () => resolve("error")); + push2.receive("timeout", () => resolve("timed out")); + }); + } + } + /** + * Updates the payload that will be sent the next time the channel joins (reconnects). + * Useful for rotating access tokens or updating config without re-creating the channel. + */ + updateJoinPayload(payload) { + this.joinPush.updatePayload(payload); + } + /** + * Leaves the channel. + * + * Unsubscribes from server events, and instructs channel to terminate on server. + * Triggers onClose() hooks. + * + * To receive leave acknowledgements, use the a `receive` hook to bind to the server ack, ie: + * channel.unsubscribe().receive("ok", () => alert("left!") ) + */ + unsubscribe(timeout = this.timeout) { + this.state = constants_1.CHANNEL_STATES.leaving; + const onClose = () => { + this.socket.log("channel", `leave ${this.topic}`); + this._trigger(constants_1.CHANNEL_EVENTS.close, "leave", this._joinRef()); + }; + this.joinPush.destroy(); + let leavePush = null; + return new Promise((resolve) => { + leavePush = new push_1.default(this, constants_1.CHANNEL_EVENTS.leave, {}, timeout); + leavePush.receive("ok", () => { + onClose(); + resolve("ok"); + }).receive("timeout", () => { + onClose(); + resolve("timed out"); + }).receive("error", () => { + resolve("error"); + }); + leavePush.send(); + if (!this._canPush()) { + leavePush.trigger("ok", {}); + } + }).finally(() => { + leavePush === null || leavePush === void 0 ? void 0 : leavePush.destroy(); + }); + } + /** + * Teardown the channel. + * + * Destroys and stops related timers. + */ + teardown() { + this.pushBuffer.forEach((push2) => push2.destroy()); + this.pushBuffer = []; + this.rejoinTimer.reset(); + this.joinPush.destroy(); + this.state = constants_1.CHANNEL_STATES.closed; + this.bindings = {}; + } + /** @internal */ + async _fetchWithTimeout(url, options, timeout) { + const controller = new AbortController(); + const id = setTimeout(() => controller.abort(), timeout); + const response = await this.socket.fetch(url, Object.assign(Object.assign({}, options), { signal: controller.signal })); + clearTimeout(id); + return response; + } + /** @internal */ + _push(event, payload, timeout = this.timeout) { + if (!this.joinedOnce) { + throw `tried to push '${event}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`; + } + let pushEvent = new push_1.default(this, event, payload, timeout); + if (this._canPush()) { + pushEvent.send(); + } else { + this._addToPushBuffer(pushEvent); + } + return pushEvent; + } + /** @internal */ + _addToPushBuffer(pushEvent) { + pushEvent.startTimeout(); + this.pushBuffer.push(pushEvent); + if (this.pushBuffer.length > constants_1.MAX_PUSH_BUFFER_SIZE) { + const removedPush = this.pushBuffer.shift(); + if (removedPush) { + removedPush.destroy(); + this.socket.log("channel", `discarded push due to buffer overflow: ${removedPush.event}`, removedPush.payload); + } + } + } + /** + * Overridable message hook + * + * Receives all events for specialized message handling before dispatching to the channel callbacks. + * Must return the payload, modified or unmodified. + * + * @internal + */ + _onMessage(_event, payload, _ref) { + return payload; + } + /** @internal */ + _isMember(topic) { + return this.topic === topic; + } + /** @internal */ + _joinRef() { + return this.joinPush.ref; + } + /** @internal */ + _trigger(type, payload, ref) { + var _a2, _b; + const typeLower = type.toLocaleLowerCase(); + const { close, error, leave, join } = constants_1.CHANNEL_EVENTS; + const events = [close, error, leave, join]; + if (ref && events.indexOf(typeLower) >= 0 && ref !== this._joinRef()) { + return; + } + let handledPayload = this._onMessage(typeLower, payload, ref); + if (payload && !handledPayload) { + throw "channel onMessage callbacks must return the payload, modified or unmodified"; + } + if (["insert", "update", "delete"].includes(typeLower)) { + (_a2 = this.bindings.postgres_changes) === null || _a2 === void 0 ? void 0 : _a2.filter((bind2) => { + var _a3, _b2, _c; + return ((_a3 = bind2.filter) === null || _a3 === void 0 ? void 0 : _a3.event) === "*" || ((_c = (_b2 = bind2.filter) === null || _b2 === void 0 ? void 0 : _b2.event) === null || _c === void 0 ? void 0 : _c.toLocaleLowerCase()) === typeLower; + }).map((bind2) => bind2.callback(handledPayload, ref)); + } else { + (_b = this.bindings[typeLower]) === null || _b === void 0 ? void 0 : _b.filter((bind2) => { + var _a3, _b2, _c, _d, _e, _f; + if (["broadcast", "presence", "postgres_changes"].includes(typeLower)) { + if ("id" in bind2) { + const bindId = bind2.id; + const bindEvent = (_a3 = bind2.filter) === null || _a3 === void 0 ? void 0 : _a3.event; + return bindId && ((_b2 = payload.ids) === null || _b2 === void 0 ? void 0 : _b2.includes(bindId)) && (bindEvent === "*" || (bindEvent === null || bindEvent === void 0 ? void 0 : bindEvent.toLocaleLowerCase()) === ((_c = payload.data) === null || _c === void 0 ? void 0 : _c.type.toLocaleLowerCase())); + } else { + const bindEvent = (_e = (_d = bind2 === null || bind2 === void 0 ? void 0 : bind2.filter) === null || _d === void 0 ? void 0 : _d.event) === null || _e === void 0 ? void 0 : _e.toLocaleLowerCase(); + return bindEvent === "*" || bindEvent === ((_f = payload === null || payload === void 0 ? void 0 : payload.event) === null || _f === void 0 ? void 0 : _f.toLocaleLowerCase()); + } + } else { + return bind2.type.toLocaleLowerCase() === typeLower; + } + }).map((bind2) => { + if (typeof handledPayload === "object" && "ids" in handledPayload) { + const postgresChanges = handledPayload.data; + const { schema, table, commit_timestamp, type: type2, errors } = postgresChanges; + const enrichedPayload = { + schema, + table, + commit_timestamp, + eventType: type2, + new: {}, + old: {}, + errors + }; + handledPayload = Object.assign(Object.assign({}, enrichedPayload), this._getPayloadRecords(postgresChanges)); + } + bind2.callback(handledPayload, ref); + }); + } + } + /** @internal */ + _isClosed() { + return this.state === constants_1.CHANNEL_STATES.closed; + } + /** @internal */ + _isJoined() { + return this.state === constants_1.CHANNEL_STATES.joined; + } + /** @internal */ + _isJoining() { + return this.state === constants_1.CHANNEL_STATES.joining; + } + /** @internal */ + _isLeaving() { + return this.state === constants_1.CHANNEL_STATES.leaving; + } + /** @internal */ + _replyEventName(ref) { + return `chan_reply_${ref}`; + } + /** @internal */ + _on(type, filter, callback) { + const typeLower = type.toLocaleLowerCase(); + const binding = { + type: typeLower, + filter, + callback + }; + if (this.bindings[typeLower]) { + this.bindings[typeLower].push(binding); + } else { + this.bindings[typeLower] = [binding]; + } + return this; + } + /** @internal */ + _off(type, filter) { + const typeLower = type.toLocaleLowerCase(); + if (this.bindings[typeLower]) { + this.bindings[typeLower] = this.bindings[typeLower].filter((bind2) => { + var _a2; + return !(((_a2 = bind2.type) === null || _a2 === void 0 ? void 0 : _a2.toLocaleLowerCase()) === typeLower && _RealtimeChannel.isEqual(bind2.filter, filter)); + }); + } + return this; + } + /** @internal */ + static isEqual(obj1, obj2) { + if (Object.keys(obj1).length !== Object.keys(obj2).length) { + return false; + } + for (const k in obj1) { + if (obj1[k] !== obj2[k]) { + return false; + } + } + return true; + } + /** + * Compares two optional filter values for equality. + * Treats undefined, null, and empty string as equivalent empty values. + * @internal + */ + static isFilterValueEqual(serverValue, clientValue) { + const normalizedServer = serverValue !== null && serverValue !== void 0 ? serverValue : void 0; + const normalizedClient = clientValue !== null && clientValue !== void 0 ? clientValue : void 0; + return normalizedServer === normalizedClient; + } + /** @internal */ + _rejoinUntilConnected() { + this.rejoinTimer.scheduleTimeout(); + if (this.socket.isConnected()) { + this._rejoin(); + } + } + /** + * Registers a callback that will be executed when the channel closes. + * + * @internal + */ + _onClose(callback) { + this._on(constants_1.CHANNEL_EVENTS.close, {}, callback); + } + /** + * Registers a callback that will be executed when the channel encounteres an error. + * + * @internal + */ + _onError(callback) { + this._on(constants_1.CHANNEL_EVENTS.error, {}, (reason) => callback(reason)); + } + /** + * Returns `true` if the socket is connected and the channel has been joined. + * + * @internal + */ + _canPush() { + return this.socket.isConnected() && this._isJoined(); + } + /** @internal */ + _rejoin(timeout = this.timeout) { + if (this._isLeaving()) { + return; + } + this.socket._leaveOpenTopic(this.topic); + this.state = constants_1.CHANNEL_STATES.joining; + this.joinPush.resend(timeout); + } + /** @internal */ + _getPayloadRecords(payload) { + const records = { + new: {}, + old: {} + }; + if (payload.type === "INSERT" || payload.type === "UPDATE") { + records.new = Transformers.convertChangeData(payload.columns, payload.record); + } + if (payload.type === "UPDATE" || payload.type === "DELETE") { + records.old = Transformers.convertChangeData(payload.columns, payload.old_record); + } + return records; + } + }; + exports.default = RealtimeChannel2; + } +}); + +// node_modules/@supabase/realtime-js/dist/main/RealtimeClient.js +var require_RealtimeClient = __commonJS({ + "node_modules/@supabase/realtime-js/dist/main/RealtimeClient.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var websocket_factory_1 = tslib_1.__importDefault(require_websocket_factory()); + var constants_1 = require_constants2(); + var serializer_1 = tslib_1.__importDefault(require_serializer()); + var timer_1 = tslib_1.__importDefault(require_timer()); + var transformers_1 = require_transformers(); + var RealtimeChannel_1 = tslib_1.__importDefault(require_RealtimeChannel()); + var noop = () => { + }; + var CONNECTION_TIMEOUTS = { + HEARTBEAT_INTERVAL: 25e3, + RECONNECT_DELAY: 10, + HEARTBEAT_TIMEOUT_FALLBACK: 100 + }; + var RECONNECT_INTERVALS = [1e3, 2e3, 5e3, 1e4]; + var DEFAULT_RECONNECT_FALLBACK = 1e4; + var WORKER_SCRIPT = ` + addEventListener("message", (e) => { + if (e.data.event === "start") { + setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); + } + });`; + var RealtimeClient2 = class { + /** + * Initializes the Socket. + * + * @param endPoint The string WebSocket endpoint, ie, "ws://example.com/socket", "wss://example.com", "/socket" (inherited host & protocol) + * @param httpEndpoint The string HTTP endpoint, ie, "https://example.com", "/" (inherited host & protocol) + * @param options.transport The Websocket Transport, for example WebSocket. This can be a custom implementation + * @param options.timeout The default timeout in milliseconds to trigger push timeouts. + * @param options.params The optional params to pass when connecting. + * @param options.headers Deprecated: headers cannot be set on websocket connections and this option will be removed in the future. + * @param options.heartbeatIntervalMs The millisec interval to send a heartbeat message. + * @param options.heartbeatCallback The optional function to handle heartbeat status. + * @param options.logger The optional function for specialized logging, ie: logger: (kind, msg, data) => { console.log(`${kind}: ${msg}`, data) } + * @param options.logLevel Sets the log level for Realtime + * @param options.encode The function to encode outgoing messages. Defaults to JSON: (payload, callback) => callback(JSON.stringify(payload)) + * @param options.decode The function to decode incoming messages. Defaults to Serializer's decode. + * @param options.reconnectAfterMs he optional function that returns the millsec reconnect interval. Defaults to stepped backoff off. + * @param options.worker Use Web Worker to set a side flow. Defaults to false. + * @param options.workerUrl The URL of the worker script. Defaults to https://realtime.supabase.com/worker.js that includes a heartbeat event call to keep the connection alive. + * @example + * ```ts + * import RealtimeClient from '@supabase/realtime-js' + * + * const client = new RealtimeClient('https://xyzcompany.supabase.co/realtime/v1', { + * params: { apikey: 'public-anon-key' }, + * }) + * client.connect() + * ``` + */ + constructor(endPoint, options) { + var _a2; + this.accessTokenValue = null; + this.apiKey = null; + this._manuallySetToken = false; + this.channels = new Array(); + this.endPoint = ""; + this.httpEndpoint = ""; + this.headers = {}; + this.params = {}; + this.timeout = constants_1.DEFAULT_TIMEOUT; + this.transport = null; + this.heartbeatIntervalMs = CONNECTION_TIMEOUTS.HEARTBEAT_INTERVAL; + this.heartbeatTimer = void 0; + this.pendingHeartbeatRef = null; + this.heartbeatCallback = noop; + this.ref = 0; + this.reconnectTimer = null; + this.vsn = constants_1.DEFAULT_VSN; + this.logger = noop; + this.conn = null; + this.sendBuffer = []; + this.serializer = new serializer_1.default(); + this.stateChangeCallbacks = { + open: [], + close: [], + error: [], + message: [] + }; + this.accessToken = null; + this._connectionState = "disconnected"; + this._wasManualDisconnect = false; + this._authPromise = null; + this._resolveFetch = (customFetch) => { + if (customFetch) { + return (...args) => customFetch(...args); + } + return (...args) => fetch(...args); + }; + if (!((_a2 = options === null || options === void 0 ? void 0 : options.params) === null || _a2 === void 0 ? void 0 : _a2.apikey)) { + throw new Error("API key is required to connect to Realtime"); + } + this.apiKey = options.params.apikey; + this.endPoint = `${endPoint}/${constants_1.TRANSPORTS.websocket}`; + this.httpEndpoint = (0, transformers_1.httpEndpointURL)(endPoint); + this._initializeOptions(options); + this._setupReconnectionTimer(); + this.fetch = this._resolveFetch(options === null || options === void 0 ? void 0 : options.fetch); + } + /** + * Connects the socket, unless already connected. + */ + connect() { + if (this.isConnecting() || this.isDisconnecting() || this.conn !== null && this.isConnected()) { + return; + } + this._setConnectionState("connecting"); + if (this.accessToken && !this._authPromise) { + this._setAuthSafely("connect"); + } + if (this.transport) { + this.conn = new this.transport(this.endpointURL()); + } else { + try { + this.conn = websocket_factory_1.default.createWebSocket(this.endpointURL()); + } catch (error) { + this._setConnectionState("disconnected"); + const errorMessage = error.message; + if (errorMessage.includes("Node.js")) { + throw new Error(`${errorMessage} + +To use Realtime in Node.js, you need to provide a WebSocket implementation: + +Option 1: Use Node.js 22+ which has native WebSocket support +Option 2: Install and provide the "ws" package: + + npm install ws + + import ws from "ws" + const client = new RealtimeClient(url, { + ...options, + transport: ws + })`); + } + throw new Error(`WebSocket not available: ${errorMessage}`); + } + } + this._setupConnectionHandlers(); + } + /** + * Returns the URL of the websocket. + * @returns string The URL of the websocket. + */ + endpointURL() { + return this._appendParams(this.endPoint, Object.assign({}, this.params, { vsn: this.vsn })); + } + /** + * Disconnects the socket. + * + * @param code A numeric status code to send on disconnect. + * @param reason A custom reason for the disconnect. + */ + disconnect(code, reason) { + if (this.isDisconnecting()) { + return; + } + this._setConnectionState("disconnecting", true); + if (this.conn) { + const fallbackTimer = setTimeout(() => { + this._setConnectionState("disconnected"); + }, 100); + this.conn.onclose = () => { + clearTimeout(fallbackTimer); + this._setConnectionState("disconnected"); + }; + if (typeof this.conn.close === "function") { + if (code) { + this.conn.close(code, reason !== null && reason !== void 0 ? reason : ""); + } else { + this.conn.close(); + } + } + this._teardownConnection(); + } else { + this._setConnectionState("disconnected"); + } + } + /** + * Returns all created channels + */ + getChannels() { + return this.channels; + } + /** + * Unsubscribes and removes a single channel + * @param channel A RealtimeChannel instance + */ + async removeChannel(channel) { + const status = await channel.unsubscribe(); + if (this.channels.length === 0) { + this.disconnect(); + } + return status; + } + /** + * Unsubscribes and removes all channels + */ + async removeAllChannels() { + const values_1 = await Promise.all(this.channels.map((channel) => channel.unsubscribe())); + this.channels = []; + this.disconnect(); + return values_1; + } + /** + * Logs the message. + * + * For customized logging, `this.logger` can be overridden. + */ + log(kind, msg, data) { + this.logger(kind, msg, data); + } + /** + * Returns the current state of the socket. + */ + connectionState() { + switch (this.conn && this.conn.readyState) { + case constants_1.SOCKET_STATES.connecting: + return constants_1.CONNECTION_STATE.Connecting; + case constants_1.SOCKET_STATES.open: + return constants_1.CONNECTION_STATE.Open; + case constants_1.SOCKET_STATES.closing: + return constants_1.CONNECTION_STATE.Closing; + default: + return constants_1.CONNECTION_STATE.Closed; + } + } + /** + * Returns `true` is the connection is open. + */ + isConnected() { + return this.connectionState() === constants_1.CONNECTION_STATE.Open; + } + /** + * Returns `true` if the connection is currently connecting. + */ + isConnecting() { + return this._connectionState === "connecting"; + } + /** + * Returns `true` if the connection is currently disconnecting. + */ + isDisconnecting() { + return this._connectionState === "disconnecting"; + } + /** + * Creates (or reuses) a {@link RealtimeChannel} for the provided topic. + * + * Topics are automatically prefixed with `realtime:` to match the Realtime service. + * If a channel with the same topic already exists it will be returned instead of creating + * a duplicate connection. + */ + channel(topic, params = { config: {} }) { + const realtimeTopic = `realtime:${topic}`; + const exists = this.getChannels().find((c) => c.topic === realtimeTopic); + if (!exists) { + const chan = new RealtimeChannel_1.default(`realtime:${topic}`, params, this); + this.channels.push(chan); + return chan; + } else { + return exists; + } + } + /** + * Push out a message if the socket is connected. + * + * If the socket is not connected, the message gets enqueued within a local buffer, and sent out when a connection is next established. + */ + push(data) { + const { topic, event, payload, ref } = data; + const callback = () => { + this.encode(data, (result) => { + var _a2; + (_a2 = this.conn) === null || _a2 === void 0 ? void 0 : _a2.send(result); + }); + }; + this.log("push", `${topic} ${event} (${ref})`, payload); + if (this.isConnected()) { + callback(); + } else { + this.sendBuffer.push(callback); + } + } + /** + * Sets the JWT access token used for channel subscription authorization and Realtime RLS. + * + * If param is null it will use the `accessToken` callback function or the token set on the client. + * + * On callback used, it will set the value of the token internal to the client. + * + * When a token is explicitly provided, it will be preserved across channel operations + * (including removeChannel and resubscribe). The `accessToken` callback will not be + * invoked until `setAuth()` is called without arguments. + * + * @param token A JWT string to override the token set on the client. + * + * @example + * // Use a manual token (preserved across resubscribes, ignores accessToken callback) + * client.realtime.setAuth('my-custom-jwt') + * + * // Switch back to using the accessToken callback + * client.realtime.setAuth() + */ + async setAuth(token = null) { + this._authPromise = this._performAuth(token); + try { + await this._authPromise; + } finally { + this._authPromise = null; + } + } + /** + * Returns true if the current access token was explicitly set via setAuth(token), + * false if it was obtained via the accessToken callback. + * @internal + */ + _isManualToken() { + return this._manuallySetToken; + } + /** + * Sends a heartbeat message if the socket is connected. + */ + async sendHeartbeat() { + var _a2; + if (!this.isConnected()) { + try { + this.heartbeatCallback("disconnected"); + } catch (e) { + this.log("error", "error in heartbeat callback", e); + } + return; + } + if (this.pendingHeartbeatRef) { + this.pendingHeartbeatRef = null; + this.log("transport", "heartbeat timeout. Attempting to re-establish connection"); + try { + this.heartbeatCallback("timeout"); + } catch (e) { + this.log("error", "error in heartbeat callback", e); + } + this._wasManualDisconnect = false; + (_a2 = this.conn) === null || _a2 === void 0 ? void 0 : _a2.close(constants_1.WS_CLOSE_NORMAL, "heartbeat timeout"); + setTimeout(() => { + var _a3; + if (!this.isConnected()) { + (_a3 = this.reconnectTimer) === null || _a3 === void 0 ? void 0 : _a3.scheduleTimeout(); + } + }, CONNECTION_TIMEOUTS.HEARTBEAT_TIMEOUT_FALLBACK); + return; + } + this.pendingHeartbeatRef = this._makeRef(); + this.push({ + topic: "phoenix", + event: "heartbeat", + payload: {}, + ref: this.pendingHeartbeatRef + }); + try { + this.heartbeatCallback("sent"); + } catch (e) { + this.log("error", "error in heartbeat callback", e); + } + this._setAuthSafely("heartbeat"); + } + /** + * Sets a callback that receives lifecycle events for internal heartbeat messages. + * Useful for instrumenting connection health (e.g. sent/ok/timeout/disconnected). + */ + onHeartbeat(callback) { + this.heartbeatCallback = callback; + } + /** + * Flushes send buffer + */ + flushSendBuffer() { + if (this.isConnected() && this.sendBuffer.length > 0) { + this.sendBuffer.forEach((callback) => callback()); + this.sendBuffer = []; + } + } + /** + * Return the next message ref, accounting for overflows + * + * @internal + */ + _makeRef() { + let newRef = this.ref + 1; + if (newRef === this.ref) { + this.ref = 0; + } else { + this.ref = newRef; + } + return this.ref.toString(); + } + /** + * Unsubscribe from channels with the specified topic. + * + * @internal + */ + _leaveOpenTopic(topic) { + let dupChannel = this.channels.find((c) => c.topic === topic && (c._isJoined() || c._isJoining())); + if (dupChannel) { + this.log("transport", `leaving duplicate topic "${topic}"`); + dupChannel.unsubscribe(); + } + } + /** + * Removes a subscription from the socket. + * + * @param channel An open subscription. + * + * @internal + */ + _remove(channel) { + this.channels = this.channels.filter((c) => c.topic !== channel.topic); + } + /** @internal */ + _onConnMessage(rawMessage) { + this.decode(rawMessage.data, (msg) => { + if (msg.topic === "phoenix" && msg.event === "phx_reply") { + try { + this.heartbeatCallback(msg.payload.status === "ok" ? "ok" : "error"); + } catch (e) { + this.log("error", "error in heartbeat callback", e); + } + } + if (msg.ref && msg.ref === this.pendingHeartbeatRef) { + this.pendingHeartbeatRef = null; + } + const { topic, event, payload, ref } = msg; + const refString = ref ? `(${ref})` : ""; + const status = payload.status || ""; + this.log("receive", `${status} ${topic} ${event} ${refString}`.trim(), payload); + this.channels.filter((channel) => channel._isMember(topic)).forEach((channel) => channel._trigger(event, payload, ref)); + this._triggerStateCallbacks("message", msg); + }); + } + /** + * Clear specific timer + * @internal + */ + _clearTimer(timer) { + var _a2; + if (timer === "heartbeat" && this.heartbeatTimer) { + clearInterval(this.heartbeatTimer); + this.heartbeatTimer = void 0; + } else if (timer === "reconnect") { + (_a2 = this.reconnectTimer) === null || _a2 === void 0 ? void 0 : _a2.reset(); + } + } + /** + * Clear all timers + * @internal + */ + _clearAllTimers() { + this._clearTimer("heartbeat"); + this._clearTimer("reconnect"); + } + /** + * Setup connection handlers for WebSocket events + * @internal + */ + _setupConnectionHandlers() { + if (!this.conn) + return; + if ("binaryType" in this.conn) { + ; + this.conn.binaryType = "arraybuffer"; + } + this.conn.onopen = () => this._onConnOpen(); + this.conn.onerror = (error) => this._onConnError(error); + this.conn.onmessage = (event) => this._onConnMessage(event); + this.conn.onclose = (event) => this._onConnClose(event); + } + /** + * Teardown connection and cleanup resources + * @internal + */ + _teardownConnection() { + if (this.conn) { + if (this.conn.readyState === constants_1.SOCKET_STATES.open || this.conn.readyState === constants_1.SOCKET_STATES.connecting) { + try { + this.conn.close(); + } catch (e) { + this.log("error", "Error closing connection", e); + } + } + this.conn.onopen = null; + this.conn.onerror = null; + this.conn.onmessage = null; + this.conn.onclose = null; + this.conn = null; + } + this._clearAllTimers(); + this.channels.forEach((channel) => channel.teardown()); + } + /** @internal */ + _onConnOpen() { + this._setConnectionState("connected"); + this.log("transport", `connected to ${this.endpointURL()}`); + const authPromise = this._authPromise || (this.accessToken && !this.accessTokenValue ? this.setAuth() : Promise.resolve()); + authPromise.then(() => { + this.flushSendBuffer(); + }).catch((e) => { + this.log("error", "error waiting for auth on connect", e); + this.flushSendBuffer(); + }); + this._clearTimer("reconnect"); + if (!this.worker) { + this._startHeartbeat(); + } else { + if (!this.workerRef) { + this._startWorkerHeartbeat(); + } + } + this._triggerStateCallbacks("open"); + } + /** @internal */ + _startHeartbeat() { + this.heartbeatTimer && clearInterval(this.heartbeatTimer); + this.heartbeatTimer = setInterval(() => this.sendHeartbeat(), this.heartbeatIntervalMs); + } + /** @internal */ + _startWorkerHeartbeat() { + if (this.workerUrl) { + this.log("worker", `starting worker for from ${this.workerUrl}`); + } else { + this.log("worker", `starting default worker`); + } + const objectUrl = this._workerObjectUrl(this.workerUrl); + this.workerRef = new Worker(objectUrl); + this.workerRef.onerror = (error) => { + this.log("worker", "worker error", error.message); + this.workerRef.terminate(); + }; + this.workerRef.onmessage = (event) => { + if (event.data.event === "keepAlive") { + this.sendHeartbeat(); + } + }; + this.workerRef.postMessage({ + event: "start", + interval: this.heartbeatIntervalMs + }); + } + /** @internal */ + _onConnClose(event) { + var _a2; + this._setConnectionState("disconnected"); + this.log("transport", "close", event); + this._triggerChanError(); + this._clearTimer("heartbeat"); + if (!this._wasManualDisconnect) { + (_a2 = this.reconnectTimer) === null || _a2 === void 0 ? void 0 : _a2.scheduleTimeout(); + } + this._triggerStateCallbacks("close", event); + } + /** @internal */ + _onConnError(error) { + this._setConnectionState("disconnected"); + this.log("transport", `${error}`); + this._triggerChanError(); + this._triggerStateCallbacks("error", error); + } + /** @internal */ + _triggerChanError() { + this.channels.forEach((channel) => channel._trigger(constants_1.CHANNEL_EVENTS.error)); + } + /** @internal */ + _appendParams(url, params) { + if (Object.keys(params).length === 0) { + return url; + } + const prefix = url.match(/\?/) ? "&" : "?"; + const query = new URLSearchParams(params); + return `${url}${prefix}${query}`; + } + _workerObjectUrl(url) { + let result_url; + if (url) { + result_url = url; + } else { + const blob = new Blob([WORKER_SCRIPT], { type: "application/javascript" }); + result_url = URL.createObjectURL(blob); + } + return result_url; + } + /** + * Set connection state with proper state management + * @internal + */ + _setConnectionState(state, manual = false) { + this._connectionState = state; + if (state === "connecting") { + this._wasManualDisconnect = false; + } else if (state === "disconnecting") { + this._wasManualDisconnect = manual; + } + } + /** + * Perform the actual auth operation + * @internal + */ + async _performAuth(token = null) { + let tokenToSend; + let isManualToken = false; + if (token) { + tokenToSend = token; + isManualToken = true; + } else if (this.accessToken) { + try { + tokenToSend = await this.accessToken(); + } catch (e) { + this.log("error", "Error fetching access token from callback", e); + tokenToSend = this.accessTokenValue; + } + } else { + tokenToSend = this.accessTokenValue; + } + if (isManualToken) { + this._manuallySetToken = true; + } else if (this.accessToken) { + this._manuallySetToken = false; + } + if (this.accessTokenValue != tokenToSend) { + this.accessTokenValue = tokenToSend; + this.channels.forEach((channel) => { + const payload = { + access_token: tokenToSend, + version: constants_1.DEFAULT_VERSION + }; + tokenToSend && channel.updateJoinPayload(payload); + if (channel.joinedOnce && channel._isJoined()) { + channel._push(constants_1.CHANNEL_EVENTS.access_token, { + access_token: tokenToSend + }); + } + }); + } + } + /** + * Wait for any in-flight auth operations to complete + * @internal + */ + async _waitForAuthIfNeeded() { + if (this._authPromise) { + await this._authPromise; + } + } + /** + * Safely call setAuth with standardized error handling + * @internal + */ + _setAuthSafely(context = "general") { + if (!this._isManualToken()) { + this.setAuth().catch((e) => { + this.log("error", `Error setting auth in ${context}`, e); + }); + } + } + /** + * Trigger state change callbacks with proper error handling + * @internal + */ + _triggerStateCallbacks(event, data) { + try { + this.stateChangeCallbacks[event].forEach((callback) => { + try { + callback(data); + } catch (e) { + this.log("error", `error in ${event} callback`, e); + } + }); + } catch (e) { + this.log("error", `error triggering ${event} callbacks`, e); + } + } + /** + * Setup reconnection timer with proper configuration + * @internal + */ + _setupReconnectionTimer() { + this.reconnectTimer = new timer_1.default(async () => { + setTimeout(async () => { + await this._waitForAuthIfNeeded(); + if (!this.isConnected()) { + this.connect(); + } + }, CONNECTION_TIMEOUTS.RECONNECT_DELAY); + }, this.reconnectAfterMs); + } + /** + * Initialize client options with defaults + * @internal + */ + _initializeOptions(options) { + var _a2, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m; + this.transport = (_a2 = options === null || options === void 0 ? void 0 : options.transport) !== null && _a2 !== void 0 ? _a2 : null; + this.timeout = (_b = options === null || options === void 0 ? void 0 : options.timeout) !== null && _b !== void 0 ? _b : constants_1.DEFAULT_TIMEOUT; + this.heartbeatIntervalMs = (_c = options === null || options === void 0 ? void 0 : options.heartbeatIntervalMs) !== null && _c !== void 0 ? _c : CONNECTION_TIMEOUTS.HEARTBEAT_INTERVAL; + this.worker = (_d = options === null || options === void 0 ? void 0 : options.worker) !== null && _d !== void 0 ? _d : false; + this.accessToken = (_e = options === null || options === void 0 ? void 0 : options.accessToken) !== null && _e !== void 0 ? _e : null; + this.heartbeatCallback = (_f = options === null || options === void 0 ? void 0 : options.heartbeatCallback) !== null && _f !== void 0 ? _f : noop; + this.vsn = (_g = options === null || options === void 0 ? void 0 : options.vsn) !== null && _g !== void 0 ? _g : constants_1.DEFAULT_VSN; + if (options === null || options === void 0 ? void 0 : options.params) + this.params = options.params; + if (options === null || options === void 0 ? void 0 : options.logger) + this.logger = options.logger; + if ((options === null || options === void 0 ? void 0 : options.logLevel) || (options === null || options === void 0 ? void 0 : options.log_level)) { + this.logLevel = options.logLevel || options.log_level; + this.params = Object.assign(Object.assign({}, this.params), { log_level: this.logLevel }); + } + this.reconnectAfterMs = (_h = options === null || options === void 0 ? void 0 : options.reconnectAfterMs) !== null && _h !== void 0 ? _h : ((tries) => { + return RECONNECT_INTERVALS[tries - 1] || DEFAULT_RECONNECT_FALLBACK; + }); + switch (this.vsn) { + case constants_1.VSN_1_0_0: + this.encode = (_j = options === null || options === void 0 ? void 0 : options.encode) !== null && _j !== void 0 ? _j : ((payload, callback) => { + return callback(JSON.stringify(payload)); + }); + this.decode = (_k = options === null || options === void 0 ? void 0 : options.decode) !== null && _k !== void 0 ? _k : ((payload, callback) => { + return callback(JSON.parse(payload)); + }); + break; + case constants_1.VSN_2_0_0: + this.encode = (_l = options === null || options === void 0 ? void 0 : options.encode) !== null && _l !== void 0 ? _l : this.serializer.encode.bind(this.serializer); + this.decode = (_m = options === null || options === void 0 ? void 0 : options.decode) !== null && _m !== void 0 ? _m : this.serializer.decode.bind(this.serializer); + break; + default: + throw new Error(`Unsupported serializer version: ${this.vsn}`); + } + if (this.worker) { + if (typeof window !== "undefined" && !window.Worker) { + throw new Error("Web Worker is not supported"); + } + this.workerUrl = options === null || options === void 0 ? void 0 : options.workerUrl; + } + } + }; + exports.default = RealtimeClient2; + } +}); + +// node_modules/@supabase/realtime-js/dist/main/index.js +var require_main2 = __commonJS({ + "node_modules/@supabase/realtime-js/dist/main/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.WebSocketFactory = exports.REALTIME_CHANNEL_STATES = exports.REALTIME_SUBSCRIBE_STATES = exports.REALTIME_PRESENCE_LISTEN_EVENTS = exports.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT = exports.REALTIME_LISTEN_TYPES = exports.RealtimeClient = exports.RealtimeChannel = exports.RealtimePresence = void 0; + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var RealtimeClient_1 = tslib_1.__importDefault(require_RealtimeClient()); + exports.RealtimeClient = RealtimeClient_1.default; + var RealtimeChannel_1 = tslib_1.__importStar(require_RealtimeChannel()); + exports.RealtimeChannel = RealtimeChannel_1.default; + Object.defineProperty(exports, "REALTIME_LISTEN_TYPES", { enumerable: true, get: function() { + return RealtimeChannel_1.REALTIME_LISTEN_TYPES; + } }); + Object.defineProperty(exports, "REALTIME_POSTGRES_CHANGES_LISTEN_EVENT", { enumerable: true, get: function() { + return RealtimeChannel_1.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT; + } }); + Object.defineProperty(exports, "REALTIME_SUBSCRIBE_STATES", { enumerable: true, get: function() { + return RealtimeChannel_1.REALTIME_SUBSCRIBE_STATES; + } }); + Object.defineProperty(exports, "REALTIME_CHANNEL_STATES", { enumerable: true, get: function() { + return RealtimeChannel_1.REALTIME_CHANNEL_STATES; + } }); + var RealtimePresence_1 = tslib_1.__importStar(require_RealtimePresence()); + exports.RealtimePresence = RealtimePresence_1.default; + Object.defineProperty(exports, "REALTIME_PRESENCE_LISTEN_EVENTS", { enumerable: true, get: function() { + return RealtimePresence_1.REALTIME_PRESENCE_LISTEN_EVENTS; + } }); + var websocket_factory_1 = tslib_1.__importDefault(require_websocket_factory()); + exports.WebSocketFactory = websocket_factory_1.default; + } +}); + +// node_modules/@supabase/storage-js/dist/main/lib/errors.js +var require_errors = __commonJS({ + "node_modules/@supabase/storage-js/dist/main/lib/errors.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.StorageUnknownError = exports.StorageApiError = exports.StorageError = void 0; + exports.isStorageError = isStorageError; + var StorageError = class extends Error { + constructor(message) { + super(message); + this.__isStorageError = true; + this.name = "StorageError"; + } + }; + exports.StorageError = StorageError; + function isStorageError(error) { + return typeof error === "object" && error !== null && "__isStorageError" in error; + } + var StorageApiError = class extends StorageError { + constructor(message, status, statusCode) { + super(message); + this.name = "StorageApiError"; + this.status = status; + this.statusCode = statusCode; + } + toJSON() { + return { + name: this.name, + message: this.message, + status: this.status, + statusCode: this.statusCode + }; + } + }; + exports.StorageApiError = StorageApiError; + var StorageUnknownError = class extends StorageError { + constructor(message, originalError) { + super(message); + this.name = "StorageUnknownError"; + this.originalError = originalError; + } + }; + exports.StorageUnknownError = StorageUnknownError; + } +}); + +// node_modules/@supabase/storage-js/dist/main/lib/helpers.js +var require_helpers = __commonJS({ + "node_modules/@supabase/storage-js/dist/main/lib/helpers.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.isValidBucketName = exports.isPlainObject = exports.recursiveToCamel = exports.resolveResponse = exports.resolveFetch = void 0; + var resolveFetch = (customFetch) => { + if (customFetch) { + return (...args) => customFetch(...args); + } + return (...args) => fetch(...args); + }; + exports.resolveFetch = resolveFetch; + var resolveResponse = () => { + return Response; + }; + exports.resolveResponse = resolveResponse; + var recursiveToCamel = (item) => { + if (Array.isArray(item)) { + return item.map((el) => (0, exports.recursiveToCamel)(el)); + } else if (typeof item === "function" || item !== Object(item)) { + return item; + } + const result = {}; + Object.entries(item).forEach(([key, value]) => { + const newKey = key.replace(/([-_][a-z])/gi, (c) => c.toUpperCase().replace(/[-_]/g, "")); + result[newKey] = (0, exports.recursiveToCamel)(value); + }); + return result; + }; + exports.recursiveToCamel = recursiveToCamel; + var isPlainObject2 = (value) => { + if (typeof value !== "object" || value === null) { + return false; + } + const prototype = Object.getPrototypeOf(value); + return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value); + }; + exports.isPlainObject = isPlainObject2; + var isValidBucketName = (bucketName) => { + if (!bucketName || typeof bucketName !== "string") { + return false; + } + if (bucketName.length === 0 || bucketName.length > 100) { + return false; + } + if (bucketName.trim() !== bucketName) { + return false; + } + if (bucketName.includes("/") || bucketName.includes("\\")) { + return false; + } + const bucketNameRegex = /^[\w!.\*'() &$@=;:+,?-]+$/; + return bucketNameRegex.test(bucketName); + }; + exports.isValidBucketName = isValidBucketName; + } +}); + +// node_modules/@supabase/storage-js/dist/main/lib/fetch.js +var require_fetch = __commonJS({ + "node_modules/@supabase/storage-js/dist/main/lib/fetch.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.get = get; + exports.post = post; + exports.put = put; + exports.head = head; + exports.remove = remove2; + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var errors_1 = require_errors(); + var helpers_1 = require_helpers(); + var _getErrorMessage = (err) => { + var _a2; + return err.msg || err.message || err.error_description || (typeof err.error === "string" ? err.error : (_a2 = err.error) === null || _a2 === void 0 ? void 0 : _a2.message) || JSON.stringify(err); + }; + var handleError = (error, reject, options) => tslib_1.__awaiter(void 0, void 0, void 0, function* () { + const Res = yield (0, helpers_1.resolveResponse)(); + if (error instanceof Res && !(options === null || options === void 0 ? void 0 : options.noResolveJson)) { + error.json().then((err) => { + const status = error.status || 500; + const statusCode = (err === null || err === void 0 ? void 0 : err.statusCode) || status + ""; + reject(new errors_1.StorageApiError(_getErrorMessage(err), status, statusCode)); + }).catch((err) => { + reject(new errors_1.StorageUnknownError(_getErrorMessage(err), err)); + }); + } else { + reject(new errors_1.StorageUnknownError(_getErrorMessage(error), error)); + } + }); + var _getRequestParams = (method, options, parameters, body) => { + const params = { method, headers: (options === null || options === void 0 ? void 0 : options.headers) || {} }; + if (method === "GET" || !body) { + return params; + } + if ((0, helpers_1.isPlainObject)(body)) { + params.headers = Object.assign({ "Content-Type": "application/json" }, options === null || options === void 0 ? void 0 : options.headers); + params.body = JSON.stringify(body); + } else { + params.body = body; + } + if (options === null || options === void 0 ? void 0 : options.duplex) { + params.duplex = options.duplex; + } + return Object.assign(Object.assign({}, params), parameters); + }; + function _handleRequest(fetcher, method, url, options, parameters, body) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return new Promise((resolve, reject) => { + fetcher(url, _getRequestParams(method, options, parameters, body)).then((result) => { + if (!result.ok) + throw result; + if (options === null || options === void 0 ? void 0 : options.noResolveJson) + return result; + return result.json(); + }).then((data) => resolve(data)).catch((error) => handleError(error, reject, options)); + }); + }); + } + function get(fetcher, url, options, parameters) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _handleRequest(fetcher, "GET", url, options, parameters); + }); + } + function post(fetcher, url, body, options, parameters) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _handleRequest(fetcher, "POST", url, options, parameters, body); + }); + } + function put(fetcher, url, body, options, parameters) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _handleRequest(fetcher, "PUT", url, options, parameters, body); + }); + } + function head(fetcher, url, options, parameters) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _handleRequest(fetcher, "HEAD", url, Object.assign(Object.assign({}, options), { noResolveJson: true }), parameters); + }); + } + function remove2(fetcher, url, body, options, parameters) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _handleRequest(fetcher, "DELETE", url, options, parameters, body); + }); + } + } +}); + +// node_modules/@supabase/storage-js/dist/main/packages/StreamDownloadBuilder.js +var require_StreamDownloadBuilder = __commonJS({ + "node_modules/@supabase/storage-js/dist/main/packages/StreamDownloadBuilder.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var errors_1 = require_errors(); + var StreamDownloadBuilder = class { + constructor(downloadFn, shouldThrowOnError) { + this.downloadFn = downloadFn; + this.shouldThrowOnError = shouldThrowOnError; + } + then(onfulfilled, onrejected) { + return this.execute().then(onfulfilled, onrejected); + } + execute() { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const result = yield this.downloadFn(); + return { + data: result.body, + error: null + }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + }; + exports.default = StreamDownloadBuilder; + } +}); + +// node_modules/@supabase/storage-js/dist/main/packages/BlobDownloadBuilder.js +var require_BlobDownloadBuilder = __commonJS({ + "node_modules/@supabase/storage-js/dist/main/packages/BlobDownloadBuilder.js"(exports) { + "use strict"; + var _a2; + Object.defineProperty(exports, "__esModule", { value: true }); + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var errors_1 = require_errors(); + var StreamDownloadBuilder_1 = tslib_1.__importDefault(require_StreamDownloadBuilder()); + var BlobDownloadBuilder = class { + constructor(downloadFn, shouldThrowOnError) { + this.downloadFn = downloadFn; + this.shouldThrowOnError = shouldThrowOnError; + this[_a2] = "BlobDownloadBuilder"; + this.promise = null; + } + asStream() { + return new StreamDownloadBuilder_1.default(this.downloadFn, this.shouldThrowOnError); + } + then(onfulfilled, onrejected) { + return this.getPromise().then(onfulfilled, onrejected); + } + catch(onrejected) { + return this.getPromise().catch(onrejected); + } + finally(onfinally) { + return this.getPromise().finally(onfinally); + } + getPromise() { + if (!this.promise) { + this.promise = this.execute(); + } + return this.promise; + } + execute() { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const result = yield this.downloadFn(); + return { + data: yield result.blob(), + error: null + }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + }; + _a2 = Symbol.toStringTag; + exports.default = BlobDownloadBuilder; + } +}); + +// node_modules/@supabase/storage-js/dist/main/packages/StorageFileApi.js +var require_StorageFileApi = __commonJS({ + "node_modules/@supabase/storage-js/dist/main/packages/StorageFileApi.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var errors_1 = require_errors(); + var fetch_1 = require_fetch(); + var helpers_1 = require_helpers(); + var BlobDownloadBuilder_1 = tslib_1.__importDefault(require_BlobDownloadBuilder()); + var DEFAULT_SEARCH_OPTIONS = { + limit: 100, + offset: 0, + sortBy: { + column: "name", + order: "asc" + } + }; + var DEFAULT_FILE_OPTIONS = { + cacheControl: "3600", + contentType: "text/plain;charset=UTF-8", + upsert: false + }; + var StorageFileApi = class { + constructor(url, headers = {}, bucketId, fetch2) { + this.shouldThrowOnError = false; + this.url = url; + this.headers = headers; + this.bucketId = bucketId; + this.fetch = (0, helpers_1.resolveFetch)(fetch2); + } + /** + * Enable throwing errors instead of returning them. + * + * @category File Buckets + */ + throwOnError() { + this.shouldThrowOnError = true; + return this; + } + /** + * Uploads a file to an existing bucket or replaces an existing file at the specified path with a new one. + * + * @param method HTTP method. + * @param path The relative file path. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload. + * @param fileBody The body of the file to be stored in the bucket. + */ + uploadOrUpdate(method, path, fileBody, fileOptions) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + let body; + const options = Object.assign(Object.assign({}, DEFAULT_FILE_OPTIONS), fileOptions); + let headers = Object.assign(Object.assign({}, this.headers), method === "POST" && { "x-upsert": String(options.upsert) }); + const metadata = options.metadata; + if (typeof Blob !== "undefined" && fileBody instanceof Blob) { + body = new FormData(); + body.append("cacheControl", options.cacheControl); + if (metadata) { + body.append("metadata", this.encodeMetadata(metadata)); + } + body.append("", fileBody); + } else if (typeof FormData !== "undefined" && fileBody instanceof FormData) { + body = fileBody; + if (!body.has("cacheControl")) { + body.append("cacheControl", options.cacheControl); + } + if (metadata && !body.has("metadata")) { + body.append("metadata", this.encodeMetadata(metadata)); + } + } else { + body = fileBody; + headers["cache-control"] = `max-age=${options.cacheControl}`; + headers["content-type"] = options.contentType; + if (metadata) { + headers["x-metadata"] = this.toBase64(this.encodeMetadata(metadata)); + } + const isStream = typeof ReadableStream !== "undefined" && body instanceof ReadableStream || body && typeof body === "object" && "pipe" in body && typeof body.pipe === "function"; + if (isStream && !options.duplex) { + options.duplex = "half"; + } + } + if (fileOptions === null || fileOptions === void 0 ? void 0 : fileOptions.headers) { + headers = Object.assign(Object.assign({}, headers), fileOptions.headers); + } + const cleanPath = this._removeEmptyFolders(path); + const _path = this._getFinalPath(cleanPath); + const data = yield (method == "PUT" ? fetch_1.put : fetch_1.post)(this.fetch, `${this.url}/object/${_path}`, body, Object.assign({ headers }, (options === null || options === void 0 ? void 0 : options.duplex) ? { duplex: options.duplex } : {})); + return { + data: { path: cleanPath, id: data.Id, fullPath: data.Key }, + error: null + }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Uploads a file to an existing bucket. + * + * @category File Buckets + * @param path The file path, including the file name. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload. + * @param fileBody The body of the file to be stored in the bucket. + * @param fileOptions Optional file upload options including cacheControl, contentType, upsert, and metadata. + * @returns Promise with response containing file path, id, and fullPath or error + * + * @example Upload file + * ```js + * const avatarFile = event.target.files[0] + * const { data, error } = await supabase + * .storage + * .from('avatars') + * .upload('public/avatar1.png', avatarFile, { + * cacheControl: '3600', + * upsert: false + * }) + * ``` + * + * Response: + * ```json + * { + * "data": { + * "path": "public/avatar1.png", + * "fullPath": "avatars/public/avatar1.png" + * }, + * "error": null + * } + * ``` + * + * @example Upload file using `ArrayBuffer` from base64 file data + * ```js + * import { decode } from 'base64-arraybuffer' + * + * const { data, error } = await supabase + * .storage + * .from('avatars') + * .upload('public/avatar1.png', decode('base64FileData'), { + * contentType: 'image/png' + * }) + * ``` + */ + upload(path, fileBody, fileOptions) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return this.uploadOrUpdate("POST", path, fileBody, fileOptions); + }); + } + /** + * Upload a file with a token generated from `createSignedUploadUrl`. + * + * @category File Buckets + * @param path The file path, including the file name. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload. + * @param token The token generated from `createSignedUploadUrl` + * @param fileBody The body of the file to be stored in the bucket. + * @param fileOptions HTTP headers (cacheControl, contentType, etc.). + * **Note:** The `upsert` option has no effect here. To enable upsert behavior, + * pass `{ upsert: true }` when calling `createSignedUploadUrl()` instead. + * @returns Promise with response containing file path and fullPath or error + * + * @example Upload to a signed URL + * ```js + * const { data, error } = await supabase + * .storage + * .from('avatars') + * .uploadToSignedUrl('folder/cat.jpg', 'token-from-createSignedUploadUrl', file) + * ``` + * + * Response: + * ```json + * { + * "data": { + * "path": "folder/cat.jpg", + * "fullPath": "avatars/folder/cat.jpg" + * }, + * "error": null + * } + * ``` + */ + uploadToSignedUrl(path, token, fileBody, fileOptions) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + const cleanPath = this._removeEmptyFolders(path); + const _path = this._getFinalPath(cleanPath); + const url = new URL(this.url + `/object/upload/sign/${_path}`); + url.searchParams.set("token", token); + try { + let body; + const options = Object.assign({ upsert: DEFAULT_FILE_OPTIONS.upsert }, fileOptions); + const headers = Object.assign(Object.assign({}, this.headers), { "x-upsert": String(options.upsert) }); + if (typeof Blob !== "undefined" && fileBody instanceof Blob) { + body = new FormData(); + body.append("cacheControl", options.cacheControl); + body.append("", fileBody); + } else if (typeof FormData !== "undefined" && fileBody instanceof FormData) { + body = fileBody; + body.append("cacheControl", options.cacheControl); + } else { + body = fileBody; + headers["cache-control"] = `max-age=${options.cacheControl}`; + headers["content-type"] = options.contentType; + } + const data = yield (0, fetch_1.put)(this.fetch, url.toString(), body, { headers }); + return { + data: { path: cleanPath, fullPath: data.Key }, + error: null + }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Creates a signed upload URL. + * Signed upload URLs can be used to upload files to the bucket without further authentication. + * They are valid for 2 hours. + * + * @category File Buckets + * @param path The file path, including the current file name. For example `folder/image.png`. + * @param options.upsert If set to true, allows the file to be overwritten if it already exists. + * @returns Promise with response containing signed upload URL, token, and path or error + * + * @example Create Signed Upload URL + * ```js + * const { data, error } = await supabase + * .storage + * .from('avatars') + * .createSignedUploadUrl('folder/cat.jpg') + * ``` + * + * Response: + * ```json + * { + * "data": { + * "signedUrl": "https://example.supabase.co/storage/v1/object/upload/sign/avatars/folder/cat.jpg?token=", + * "path": "folder/cat.jpg", + * "token": "" + * }, + * "error": null + * } + * ``` + */ + createSignedUploadUrl(path, options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + let _path = this._getFinalPath(path); + const headers = Object.assign({}, this.headers); + if (options === null || options === void 0 ? void 0 : options.upsert) { + headers["x-upsert"] = "true"; + } + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/upload/sign/${_path}`, {}, { headers }); + const url = new URL(this.url + data.url); + const token = url.searchParams.get("token"); + if (!token) { + throw new errors_1.StorageError("No token returned by API"); + } + return { data: { signedUrl: url.toString(), path, token }, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Replaces an existing file at the specified path with a new one. + * + * @category File Buckets + * @param path The relative file path. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to update. + * @param fileBody The body of the file to be stored in the bucket. + * @param fileOptions Optional file upload options including cacheControl, contentType, upsert, and metadata. + * @returns Promise with response containing file path, id, and fullPath or error + * + * @example Update file + * ```js + * const avatarFile = event.target.files[0] + * const { data, error } = await supabase + * .storage + * .from('avatars') + * .update('public/avatar1.png', avatarFile, { + * cacheControl: '3600', + * upsert: true + * }) + * ``` + * + * Response: + * ```json + * { + * "data": { + * "path": "public/avatar1.png", + * "fullPath": "avatars/public/avatar1.png" + * }, + * "error": null + * } + * ``` + * + * @example Update file using `ArrayBuffer` from base64 file data + * ```js + * import {decode} from 'base64-arraybuffer' + * + * const { data, error } = await supabase + * .storage + * .from('avatars') + * .update('public/avatar1.png', decode('base64FileData'), { + * contentType: 'image/png' + * }) + * ``` + */ + update(path, fileBody, fileOptions) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return this.uploadOrUpdate("PUT", path, fileBody, fileOptions); + }); + } + /** + * Moves an existing file to a new path in the same bucket. + * + * @category File Buckets + * @param fromPath The original file path, including the current file name. For example `folder/image.png`. + * @param toPath The new file path, including the new file name. For example `folder/image-new.png`. + * @param options The destination options. + * @returns Promise with response containing success message or error + * + * @example Move file + * ```js + * const { data, error } = await supabase + * .storage + * .from('avatars') + * .move('public/avatar1.png', 'private/avatar2.png') + * ``` + * + * Response: + * ```json + * { + * "data": { + * "message": "Successfully moved" + * }, + * "error": null + * } + * ``` + */ + move(fromPath, toPath, options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/move`, { + bucketId: this.bucketId, + sourceKey: fromPath, + destinationKey: toPath, + destinationBucket: options === null || options === void 0 ? void 0 : options.destinationBucket + }, { headers: this.headers }); + return { data, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Copies an existing file to a new path in the same bucket. + * + * @category File Buckets + * @param fromPath The original file path, including the current file name. For example `folder/image.png`. + * @param toPath The new file path, including the new file name. For example `folder/image-copy.png`. + * @param options The destination options. + * @returns Promise with response containing copied file path or error + * + * @example Copy file + * ```js + * const { data, error } = await supabase + * .storage + * .from('avatars') + * .copy('public/avatar1.png', 'private/avatar2.png') + * ``` + * + * Response: + * ```json + * { + * "data": { + * "path": "avatars/private/avatar2.png" + * }, + * "error": null + * } + * ``` + */ + copy(fromPath, toPath, options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/copy`, { + bucketId: this.bucketId, + sourceKey: fromPath, + destinationKey: toPath, + destinationBucket: options === null || options === void 0 ? void 0 : options.destinationBucket + }, { headers: this.headers }); + return { data: { path: data.Key }, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Creates a signed URL. Use a signed URL to share a file for a fixed amount of time. + * + * @category File Buckets + * @param path The file path, including the current file name. For example `folder/image.png`. + * @param expiresIn The number of seconds until the signed URL expires. For example, `60` for a URL which is valid for one minute. + * @param options.download triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename. + * @param options.transform Transform the asset before serving it to the client. + * @returns Promise with response containing signed URL or error + * + * @example Create Signed URL + * ```js + * const { data, error } = await supabase + * .storage + * .from('avatars') + * .createSignedUrl('folder/avatar1.png', 60) + * ``` + * + * Response: + * ```json + * { + * "data": { + * "signedUrl": "https://example.supabase.co/storage/v1/object/sign/avatars/folder/avatar1.png?token=" + * }, + * "error": null + * } + * ``` + * + * @example Create a signed URL for an asset with transformations + * ```js + * const { data } = await supabase + * .storage + * .from('avatars') + * .createSignedUrl('folder/avatar1.png', 60, { + * transform: { + * width: 100, + * height: 100, + * } + * }) + * ``` + * + * @example Create a signed URL which triggers the download of the asset + * ```js + * const { data } = await supabase + * .storage + * .from('avatars') + * .createSignedUrl('folder/avatar1.png', 60, { + * download: true, + * }) + * ``` + */ + createSignedUrl(path, expiresIn, options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + let _path = this._getFinalPath(path); + let data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/sign/${_path}`, Object.assign({ expiresIn }, (options === null || options === void 0 ? void 0 : options.transform) ? { transform: options.transform } : {}), { headers: this.headers }); + const downloadQueryParam = (options === null || options === void 0 ? void 0 : options.download) ? `&download=${options.download === true ? "" : options.download}` : ""; + const signedUrl = encodeURI(`${this.url}${data.signedURL}${downloadQueryParam}`); + data = { signedUrl }; + return { data, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Creates multiple signed URLs. Use a signed URL to share a file for a fixed amount of time. + * + * @category File Buckets + * @param paths The file paths to be downloaded, including the current file names. For example `['folder/image.png', 'folder2/image2.png']`. + * @param expiresIn The number of seconds until the signed URLs expire. For example, `60` for URLs which are valid for one minute. + * @param options.download triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename. + * @returns Promise with response containing array of objects with signedUrl, path, and error or error + * + * @example Create Signed URLs + * ```js + * const { data, error } = await supabase + * .storage + * .from('avatars') + * .createSignedUrls(['folder/avatar1.png', 'folder/avatar2.png'], 60) + * ``` + * + * Response: + * ```json + * { + * "data": [ + * { + * "error": null, + * "path": "folder/avatar1.png", + * "signedURL": "/object/sign/avatars/folder/avatar1.png?token=", + * "signedUrl": "https://example.supabase.co/storage/v1/object/sign/avatars/folder/avatar1.png?token=" + * }, + * { + * "error": null, + * "path": "folder/avatar2.png", + * "signedURL": "/object/sign/avatars/folder/avatar2.png?token=", + * "signedUrl": "https://example.supabase.co/storage/v1/object/sign/avatars/folder/avatar2.png?token=" + * } + * ], + * "error": null + * } + * ``` + */ + createSignedUrls(paths, expiresIn, options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/sign/${this.bucketId}`, { expiresIn, paths }, { headers: this.headers }); + const downloadQueryParam = (options === null || options === void 0 ? void 0 : options.download) ? `&download=${options.download === true ? "" : options.download}` : ""; + return { + data: data.map((datum) => Object.assign(Object.assign({}, datum), { signedUrl: datum.signedURL ? encodeURI(`${this.url}${datum.signedURL}${downloadQueryParam}`) : null })), + error: null + }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Downloads a file from a private bucket. For public buckets, make a request to the URL returned from `getPublicUrl` instead. + * + * @category File Buckets + * @param path The full path and file name of the file to be downloaded. For example `folder/image.png`. + * @param options.transform Transform the asset before serving it to the client. + * @returns BlobDownloadBuilder instance for downloading the file + * + * @example Download file + * ```js + * const { data, error } = await supabase + * .storage + * .from('avatars') + * .download('folder/avatar1.png') + * ``` + * + * Response: + * ```json + * { + * "data": , + * "error": null + * } + * ``` + * + * @example Download file with transformations + * ```js + * const { data, error } = await supabase + * .storage + * .from('avatars') + * .download('folder/avatar1.png', { + * transform: { + * width: 100, + * height: 100, + * quality: 80 + * } + * }) + * ``` + */ + download(path, options) { + const wantsTransformation = typeof (options === null || options === void 0 ? void 0 : options.transform) !== "undefined"; + const renderPath = wantsTransformation ? "render/image/authenticated" : "object"; + const transformationQuery = this.transformOptsToQueryString((options === null || options === void 0 ? void 0 : options.transform) || {}); + const queryString = transformationQuery ? `?${transformationQuery}` : ""; + const _path = this._getFinalPath(path); + const downloadFn = () => (0, fetch_1.get)(this.fetch, `${this.url}/${renderPath}/${_path}${queryString}`, { + headers: this.headers, + noResolveJson: true + }); + return new BlobDownloadBuilder_1.default(downloadFn, this.shouldThrowOnError); + } + /** + * Retrieves the details of an existing file. + * + * @category File Buckets + * @param path The file path, including the file name. For example `folder/image.png`. + * @returns Promise with response containing file metadata or error + * + * @example Get file info + * ```js + * const { data, error } = await supabase + * .storage + * .from('avatars') + * .info('folder/avatar1.png') + * ``` + */ + info(path) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + const _path = this._getFinalPath(path); + try { + const data = yield (0, fetch_1.get)(this.fetch, `${this.url}/object/info/${_path}`, { + headers: this.headers + }); + return { data: (0, helpers_1.recursiveToCamel)(data), error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Checks the existence of a file. + * + * @category File Buckets + * @param path The file path, including the file name. For example `folder/image.png`. + * @returns Promise with response containing boolean indicating file existence or error + * + * @example Check file existence + * ```js + * const { data, error } = await supabase + * .storage + * .from('avatars') + * .exists('folder/avatar1.png') + * ``` + */ + exists(path) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + const _path = this._getFinalPath(path); + try { + yield (0, fetch_1.head)(this.fetch, `${this.url}/object/${_path}`, { + headers: this.headers + }); + return { data: true, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error) && error instanceof errors_1.StorageUnknownError) { + const originalError = error.originalError; + if ([400, 404].includes(originalError === null || originalError === void 0 ? void 0 : originalError.status)) { + return { data: false, error }; + } + } + throw error; + } + }); + } + /** + * A simple convenience function to get the URL for an asset in a public bucket. If you do not want to use this function, you can construct the public URL by concatenating the bucket URL with the path to the asset. + * This function does not verify if the bucket is public. If a public URL is created for a bucket which is not public, you will not be able to download the asset. + * + * @category File Buckets + * @param path The path and name of the file to generate the public URL for. For example `folder/image.png`. + * @param options.download Triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename. + * @param options.transform Transform the asset before serving it to the client. + * @returns Object with public URL + * + * @example Returns the URL for an asset in a public bucket + * ```js + * const { data } = supabase + * .storage + * .from('public-bucket') + * .getPublicUrl('folder/avatar1.png') + * ``` + * + * Response: + * ```json + * { + * "data": { + * "publicUrl": "https://example.supabase.co/storage/v1/object/public/public-bucket/folder/avatar1.png" + * } + * } + * ``` + * + * @example Returns the URL for an asset in a public bucket with transformations + * ```js + * const { data } = supabase + * .storage + * .from('public-bucket') + * .getPublicUrl('folder/avatar1.png', { + * transform: { + * width: 100, + * height: 100, + * } + * }) + * ``` + * + * @example Returns the URL which triggers the download of an asset in a public bucket + * ```js + * const { data } = supabase + * .storage + * .from('public-bucket') + * .getPublicUrl('folder/avatar1.png', { + * download: true, + * }) + * ``` + */ + getPublicUrl(path, options) { + const _path = this._getFinalPath(path); + const _queryString = []; + const downloadQueryParam = (options === null || options === void 0 ? void 0 : options.download) ? `download=${options.download === true ? "" : options.download}` : ""; + if (downloadQueryParam !== "") { + _queryString.push(downloadQueryParam); + } + const wantsTransformation = typeof (options === null || options === void 0 ? void 0 : options.transform) !== "undefined"; + const renderPath = wantsTransformation ? "render/image" : "object"; + const transformationQuery = this.transformOptsToQueryString((options === null || options === void 0 ? void 0 : options.transform) || {}); + if (transformationQuery !== "") { + _queryString.push(transformationQuery); + } + let queryString = _queryString.join("&"); + if (queryString !== "") { + queryString = `?${queryString}`; + } + return { + data: { publicUrl: encodeURI(`${this.url}/${renderPath}/public/${_path}${queryString}`) } + }; + } + /** + * Deletes files within the same bucket + * + * @category File Buckets + * @param paths An array of files to delete, including the path and file name. For example [`'folder/image.png'`]. + * @returns Promise with response containing array of deleted file objects or error + * + * @example Delete file + * ```js + * const { data, error } = await supabase + * .storage + * .from('avatars') + * .remove(['folder/avatar1.png']) + * ``` + * + * Response: + * ```json + * { + * "data": [], + * "error": null + * } + * ``` + */ + remove(paths) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.remove)(this.fetch, `${this.url}/object/${this.bucketId}`, { prefixes: paths }, { headers: this.headers }); + return { data, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Get file metadata + * @param id the file id to retrieve metadata + */ + // async getMetadata( + // id: string + // ): Promise< + // | { + // data: Metadata + // error: null + // } + // | { + // data: null + // error: StorageError + // } + // > { + // try { + // const data = await get(this.fetch, `${this.url}/metadata/${id}`, { headers: this.headers }) + // return { data, error: null } + // } catch (error) { + // if (isStorageError(error)) { + // return { data: null, error } + // } + // throw error + // } + // } + /** + * Update file metadata + * @param id the file id to update metadata + * @param meta the new file metadata + */ + // async updateMetadata( + // id: string, + // meta: Metadata + // ): Promise< + // | { + // data: Metadata + // error: null + // } + // | { + // data: null + // error: StorageError + // } + // > { + // try { + // const data = await post( + // this.fetch, + // `${this.url}/metadata/${id}`, + // { ...meta }, + // { headers: this.headers } + // ) + // return { data, error: null } + // } catch (error) { + // if (isStorageError(error)) { + // return { data: null, error } + // } + // throw error + // } + // } + /** + * Lists all the files and folders within a path of the bucket. + * + * @category File Buckets + * @param path The folder path. + * @param options Search options including limit (defaults to 100), offset, sortBy, and search + * @param parameters Optional fetch parameters including signal for cancellation + * @returns Promise with response containing array of files or error + * + * @example List files in a bucket + * ```js + * const { data, error } = await supabase + * .storage + * .from('avatars') + * .list('folder', { + * limit: 100, + * offset: 0, + * sortBy: { column: 'name', order: 'asc' }, + * }) + * ``` + * + * Response: + * ```json + * { + * "data": [ + * { + * "name": "avatar1.png", + * "id": "e668cf7f-821b-4a2f-9dce-7dfa5dd1cfd2", + * "updated_at": "2024-05-22T23:06:05.580Z", + * "created_at": "2024-05-22T23:04:34.443Z", + * "last_accessed_at": "2024-05-22T23:04:34.443Z", + * "metadata": { + * "eTag": "\"c5e8c553235d9af30ef4f6e280790b92\"", + * "size": 32175, + * "mimetype": "image/png", + * "cacheControl": "max-age=3600", + * "lastModified": "2024-05-22T23:06:05.574Z", + * "contentLength": 32175, + * "httpStatusCode": 200 + * } + * } + * ], + * "error": null + * } + * ``` + * + * @example Search files in a bucket + * ```js + * const { data, error } = await supabase + * .storage + * .from('avatars') + * .list('folder', { + * limit: 100, + * offset: 0, + * sortBy: { column: 'name', order: 'asc' }, + * search: 'jon' + * }) + * ``` + */ + list(path, options, parameters) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const body = Object.assign(Object.assign(Object.assign({}, DEFAULT_SEARCH_OPTIONS), options), { prefix: path || "" }); + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/list/${this.bucketId}`, body, { headers: this.headers }, parameters); + return { data, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * @experimental this method signature might change in the future + * + * @category File Buckets + * @param options search options + * @param parameters + */ + listV2(options, parameters) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const body = Object.assign({}, options); + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/list-v2/${this.bucketId}`, body, { headers: this.headers }, parameters); + return { data, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + encodeMetadata(metadata) { + return JSON.stringify(metadata); + } + toBase64(data) { + if (typeof Buffer !== "undefined") { + return Buffer.from(data).toString("base64"); + } + return btoa(data); + } + _getFinalPath(path) { + return `${this.bucketId}/${path.replace(/^\/+/, "")}`; + } + _removeEmptyFolders(path) { + return path.replace(/^\/|\/$/g, "").replace(/\/+/g, "/"); + } + transformOptsToQueryString(transform) { + const params = []; + if (transform.width) { + params.push(`width=${transform.width}`); + } + if (transform.height) { + params.push(`height=${transform.height}`); + } + if (transform.resize) { + params.push(`resize=${transform.resize}`); + } + if (transform.format) { + params.push(`format=${transform.format}`); + } + if (transform.quality) { + params.push(`quality=${transform.quality}`); + } + return params.join("&"); + } + }; + exports.default = StorageFileApi; + } +}); + +// node_modules/@supabase/storage-js/dist/main/lib/version.js +var require_version2 = __commonJS({ + "node_modules/@supabase/storage-js/dist/main/lib/version.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.version = void 0; + exports.version = "2.87.1"; + } +}); + +// node_modules/@supabase/storage-js/dist/main/lib/constants.js +var require_constants3 = __commonJS({ + "node_modules/@supabase/storage-js/dist/main/lib/constants.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DEFAULT_HEADERS = void 0; + var version_1 = require_version2(); + exports.DEFAULT_HEADERS = { + "X-Client-Info": `storage-js/${version_1.version}` + }; + } +}); + +// node_modules/@supabase/storage-js/dist/main/packages/StorageBucketApi.js +var require_StorageBucketApi = __commonJS({ + "node_modules/@supabase/storage-js/dist/main/packages/StorageBucketApi.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var constants_1 = require_constants3(); + var errors_1 = require_errors(); + var fetch_1 = require_fetch(); + var helpers_1 = require_helpers(); + var StorageBucketApi = class { + constructor(url, headers = {}, fetch2, opts) { + this.shouldThrowOnError = false; + const baseUrl = new URL(url); + if (opts === null || opts === void 0 ? void 0 : opts.useNewHostname) { + const isSupabaseHost = /supabase\.(co|in|red)$/.test(baseUrl.hostname); + if (isSupabaseHost && !baseUrl.hostname.includes("storage.supabase.")) { + baseUrl.hostname = baseUrl.hostname.replace("supabase.", "storage.supabase."); + } + } + this.url = baseUrl.href.replace(/\/$/, ""); + this.headers = Object.assign(Object.assign({}, constants_1.DEFAULT_HEADERS), headers); + this.fetch = (0, helpers_1.resolveFetch)(fetch2); + } + /** + * Enable throwing errors instead of returning them. + * + * @category File Buckets + */ + throwOnError() { + this.shouldThrowOnError = true; + return this; + } + /** + * Retrieves the details of all Storage buckets within an existing project. + * + * @category File Buckets + * @param options Query parameters for listing buckets + * @param options.limit Maximum number of buckets to return + * @param options.offset Number of buckets to skip + * @param options.sortColumn Column to sort by ('id', 'name', 'created_at', 'updated_at') + * @param options.sortOrder Sort order ('asc' or 'desc') + * @param options.search Search term to filter bucket names + * @returns Promise with response containing array of buckets or error + * + * @example List buckets + * ```js + * const { data, error } = await supabase + * .storage + * .listBuckets() + * ``` + * + * @example List buckets with options + * ```js + * const { data, error } = await supabase + * .storage + * .listBuckets({ + * limit: 10, + * offset: 0, + * sortColumn: 'created_at', + * sortOrder: 'desc', + * search: 'prod' + * }) + * ``` + */ + listBuckets(options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const queryString = this.listBucketOptionsToQueryString(options); + const data = yield (0, fetch_1.get)(this.fetch, `${this.url}/bucket${queryString}`, { + headers: this.headers + }); + return { data, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Retrieves the details of an existing Storage bucket. + * + * @category File Buckets + * @param id The unique identifier of the bucket you would like to retrieve. + * @returns Promise with response containing bucket details or error + * + * @example Get bucket + * ```js + * const { data, error } = await supabase + * .storage + * .getBucket('avatars') + * ``` + * + * Response: + * ```json + * { + * "data": { + * "id": "avatars", + * "name": "avatars", + * "owner": "", + * "public": false, + * "file_size_limit": 1024, + * "allowed_mime_types": [ + * "image/png" + * ], + * "created_at": "2024-05-22T22:26:05.100Z", + * "updated_at": "2024-05-22T22:26:05.100Z" + * }, + * "error": null + * } + * ``` + */ + getBucket(id) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.get)(this.fetch, `${this.url}/bucket/${id}`, { headers: this.headers }); + return { data, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Creates a new Storage bucket + * + * @category File Buckets + * @param id A unique identifier for the bucket you are creating. + * @param options.public The visibility of the bucket. Public buckets don't require an authorization token to download objects, but still require a valid token for all other operations. By default, buckets are private. + * @param options.fileSizeLimit specifies the max file size in bytes that can be uploaded to this bucket. + * The global file size limit takes precedence over this value. + * The default value is null, which doesn't set a per bucket file size limit. + * @param options.allowedMimeTypes specifies the allowed mime types that this bucket can accept during upload. + * The default value is null, which allows files with all mime types to be uploaded. + * Each mime type specified can be a wildcard, e.g. image/*, or a specific mime type, e.g. image/png. + * @param options.type (private-beta) specifies the bucket type. see `BucketType` for more details. + * - default bucket type is `STANDARD` + * @returns Promise with response containing newly created bucket name or error + * + * @example Create bucket + * ```js + * const { data, error } = await supabase + * .storage + * .createBucket('avatars', { + * public: false, + * allowedMimeTypes: ['image/png'], + * fileSizeLimit: 1024 + * }) + * ``` + * + * Response: + * ```json + * { + * "data": { + * "name": "avatars" + * }, + * "error": null + * } + * ``` + */ + createBucket(id_1) { + return tslib_1.__awaiter(this, arguments, void 0, function* (id, options = { + public: false + }) { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/bucket`, { + id, + name: id, + type: options.type, + public: options.public, + file_size_limit: options.fileSizeLimit, + allowed_mime_types: options.allowedMimeTypes + }, { headers: this.headers }); + return { data, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Updates a Storage bucket + * + * @category File Buckets + * @param id A unique identifier for the bucket you are updating. + * @param options.public The visibility of the bucket. Public buckets don't require an authorization token to download objects, but still require a valid token for all other operations. + * @param options.fileSizeLimit specifies the max file size in bytes that can be uploaded to this bucket. + * The global file size limit takes precedence over this value. + * The default value is null, which doesn't set a per bucket file size limit. + * @param options.allowedMimeTypes specifies the allowed mime types that this bucket can accept during upload. + * The default value is null, which allows files with all mime types to be uploaded. + * Each mime type specified can be a wildcard, e.g. image/*, or a specific mime type, e.g. image/png. + * @returns Promise with response containing success message or error + * + * @example Update bucket + * ```js + * const { data, error } = await supabase + * .storage + * .updateBucket('avatars', { + * public: false, + * allowedMimeTypes: ['image/png'], + * fileSizeLimit: 1024 + * }) + * ``` + * + * Response: + * ```json + * { + * "data": { + * "message": "Successfully updated" + * }, + * "error": null + * } + * ``` + */ + updateBucket(id, options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.put)(this.fetch, `${this.url}/bucket/${id}`, { + id, + name: id, + public: options.public, + file_size_limit: options.fileSizeLimit, + allowed_mime_types: options.allowedMimeTypes + }, { headers: this.headers }); + return { data, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Removes all objects inside a single bucket. + * + * @category File Buckets + * @param id The unique identifier of the bucket you would like to empty. + * @returns Promise with success message or error + * + * @example Empty bucket + * ```js + * const { data, error } = await supabase + * .storage + * .emptyBucket('avatars') + * ``` + * + * Response: + * ```json + * { + * "data": { + * "message": "Successfully emptied" + * }, + * "error": null + * } + * ``` + */ + emptyBucket(id) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/bucket/${id}/empty`, {}, { headers: this.headers }); + return { data, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Deletes an existing bucket. A bucket can't be deleted with existing objects inside it. + * You must first `empty()` the bucket. + * + * @category File Buckets + * @param id The unique identifier of the bucket you would like to delete. + * @returns Promise with success message or error + * + * @example Delete bucket + * ```js + * const { data, error } = await supabase + * .storage + * .deleteBucket('avatars') + * ``` + * + * Response: + * ```json + * { + * "data": { + * "message": "Successfully deleted" + * }, + * "error": null + * } + * ``` + */ + deleteBucket(id) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.remove)(this.fetch, `${this.url}/bucket/${id}`, {}, { headers: this.headers }); + return { data, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + listBucketOptionsToQueryString(options) { + const params = {}; + if (options) { + if ("limit" in options) { + params.limit = String(options.limit); + } + if ("offset" in options) { + params.offset = String(options.offset); + } + if (options.search) { + params.search = options.search; + } + if (options.sortColumn) { + params.sortColumn = options.sortColumn; + } + if (options.sortOrder) { + params.sortOrder = options.sortOrder; + } + } + return Object.keys(params).length > 0 ? "?" + new URLSearchParams(params).toString() : ""; + } + }; + exports.default = StorageBucketApi; + } +}); + +// node_modules/iceberg-js/dist/index.cjs +var require_dist2 = __commonJS({ + "node_modules/iceberg-js/dist/index.cjs"(exports) { + "use strict"; + var IcebergError = class extends Error { + constructor(message, opts) { + super(message); + this.name = "IcebergError"; + this.status = opts.status; + this.icebergType = opts.icebergType; + this.icebergCode = opts.icebergCode; + this.details = opts.details; + this.isCommitStateUnknown = opts.icebergType === "CommitStateUnknownException" || [500, 502, 504].includes(opts.status) && opts.icebergType?.includes("CommitState") === true; + } + /** + * Returns true if the error is a 404 Not Found error. + */ + isNotFound() { + return this.status === 404; + } + /** + * Returns true if the error is a 409 Conflict error. + */ + isConflict() { + return this.status === 409; + } + /** + * Returns true if the error is a 419 Authentication Timeout error. + */ + isAuthenticationTimeout() { + return this.status === 419; + } + }; + function buildUrl(baseUrl, path, query) { + const url = new URL(path, baseUrl); + if (query) { + for (const [key, value] of Object.entries(query)) { + if (value !== void 0) { + url.searchParams.set(key, value); + } + } + } + return url.toString(); + } + async function buildAuthHeaders(auth) { + if (!auth || auth.type === "none") { + return {}; + } + if (auth.type === "bearer") { + return { Authorization: `Bearer ${auth.token}` }; + } + if (auth.type === "header") { + return { [auth.name]: auth.value }; + } + if (auth.type === "custom") { + return await auth.getHeaders(); + } + return {}; + } + function createFetchClient(options) { + const fetchFn = options.fetchImpl ?? globalThis.fetch; + return { + async request({ + method, + path, + query, + body, + headers + }) { + const url = buildUrl(options.baseUrl, path, query); + const authHeaders = await buildAuthHeaders(options.auth); + const res = await fetchFn(url, { + method, + headers: { + ...body ? { "Content-Type": "application/json" } : {}, + ...authHeaders, + ...headers + }, + body: body ? JSON.stringify(body) : void 0 + }); + const text = await res.text(); + const isJson = (res.headers.get("content-type") || "").includes("application/json"); + const data = isJson && text ? JSON.parse(text) : text; + if (!res.ok) { + const errBody = isJson ? data : void 0; + const errorDetail = errBody?.error; + throw new IcebergError( + errorDetail?.message ?? `Request failed with status ${res.status}`, + { + status: res.status, + icebergType: errorDetail?.type, + icebergCode: errorDetail?.code, + details: errBody + } + ); + } + return { status: res.status, headers: res.headers, data }; + } + }; + } + function namespaceToPath(namespace) { + return namespace.join(""); + } + var NamespaceOperations = class { + constructor(client2, prefix = "") { + this.client = client2; + this.prefix = prefix; + } + async listNamespaces(parent) { + const query = parent ? { parent: namespaceToPath(parent.namespace) } : void 0; + const response = await this.client.request({ + method: "GET", + path: `${this.prefix}/namespaces`, + query + }); + return response.data.namespaces.map((ns) => ({ namespace: ns })); + } + async createNamespace(id, metadata) { + const request = { + namespace: id.namespace, + properties: metadata?.properties + }; + const response = await this.client.request({ + method: "POST", + path: `${this.prefix}/namespaces`, + body: request + }); + return response.data; + } + async dropNamespace(id) { + await this.client.request({ + method: "DELETE", + path: `${this.prefix}/namespaces/${namespaceToPath(id.namespace)}` + }); + } + async loadNamespaceMetadata(id) { + const response = await this.client.request({ + method: "GET", + path: `${this.prefix}/namespaces/${namespaceToPath(id.namespace)}` + }); + return { + properties: response.data.properties + }; + } + async namespaceExists(id) { + try { + await this.client.request({ + method: "HEAD", + path: `${this.prefix}/namespaces/${namespaceToPath(id.namespace)}` + }); + return true; + } catch (error) { + if (error instanceof IcebergError && error.status === 404) { + return false; + } + throw error; + } + } + async createNamespaceIfNotExists(id, metadata) { + try { + return await this.createNamespace(id, metadata); + } catch (error) { + if (error instanceof IcebergError && error.status === 409) { + return; + } + throw error; + } + } + }; + function namespaceToPath2(namespace) { + return namespace.join(""); + } + var TableOperations = class { + constructor(client2, prefix = "", accessDelegation) { + this.client = client2; + this.prefix = prefix; + this.accessDelegation = accessDelegation; + } + async listTables(namespace) { + const response = await this.client.request({ + method: "GET", + path: `${this.prefix}/namespaces/${namespaceToPath2(namespace.namespace)}/tables` + }); + return response.data.identifiers; + } + async createTable(namespace, request) { + const headers = {}; + if (this.accessDelegation) { + headers["X-Iceberg-Access-Delegation"] = this.accessDelegation; + } + const response = await this.client.request({ + method: "POST", + path: `${this.prefix}/namespaces/${namespaceToPath2(namespace.namespace)}/tables`, + body: request, + headers + }); + return response.data.metadata; + } + async updateTable(id, request) { + const response = await this.client.request({ + method: "POST", + path: `${this.prefix}/namespaces/${namespaceToPath2(id.namespace)}/tables/${id.name}`, + body: request + }); + return { + "metadata-location": response.data["metadata-location"], + metadata: response.data.metadata + }; + } + async dropTable(id, options) { + await this.client.request({ + method: "DELETE", + path: `${this.prefix}/namespaces/${namespaceToPath2(id.namespace)}/tables/${id.name}`, + query: { purgeRequested: String(options?.purge ?? false) } + }); + } + async loadTable(id) { + const headers = {}; + if (this.accessDelegation) { + headers["X-Iceberg-Access-Delegation"] = this.accessDelegation; + } + const response = await this.client.request({ + method: "GET", + path: `${this.prefix}/namespaces/${namespaceToPath2(id.namespace)}/tables/${id.name}`, + headers + }); + return response.data.metadata; + } + async tableExists(id) { + const headers = {}; + if (this.accessDelegation) { + headers["X-Iceberg-Access-Delegation"] = this.accessDelegation; + } + try { + await this.client.request({ + method: "HEAD", + path: `${this.prefix}/namespaces/${namespaceToPath2(id.namespace)}/tables/${id.name}`, + headers + }); + return true; + } catch (error) { + if (error instanceof IcebergError && error.status === 404) { + return false; + } + throw error; + } + } + async createTableIfNotExists(namespace, request) { + try { + return await this.createTable(namespace, request); + } catch (error) { + if (error instanceof IcebergError && error.status === 409) { + return await this.loadTable({ namespace: namespace.namespace, name: request.name }); + } + throw error; + } + } + }; + var IcebergRestCatalog = class { + /** + * Creates a new Iceberg REST Catalog client. + * + * @param options - Configuration options for the catalog client + */ + constructor(options) { + let prefix = "v1"; + if (options.catalogName) { + prefix += `/${options.catalogName}`; + } + const baseUrl = options.baseUrl.endsWith("/") ? options.baseUrl : `${options.baseUrl}/`; + this.client = createFetchClient({ + baseUrl, + auth: options.auth, + fetchImpl: options.fetch + }); + this.accessDelegation = options.accessDelegation?.join(","); + this.namespaceOps = new NamespaceOperations(this.client, prefix); + this.tableOps = new TableOperations(this.client, prefix, this.accessDelegation); + } + /** + * Lists all namespaces in the catalog. + * + * @param parent - Optional parent namespace to list children under + * @returns Array of namespace identifiers + * + * @example + * ```typescript + * // List all top-level namespaces + * const namespaces = await catalog.listNamespaces(); + * + * // List namespaces under a parent + * const children = await catalog.listNamespaces({ namespace: ['analytics'] }); + * ``` + */ + async listNamespaces(parent) { + return this.namespaceOps.listNamespaces(parent); + } + /** + * Creates a new namespace in the catalog. + * + * @param id - Namespace identifier to create + * @param metadata - Optional metadata properties for the namespace + * @returns Response containing the created namespace and its properties + * + * @example + * ```typescript + * const response = await catalog.createNamespace( + * { namespace: ['analytics'] }, + * { properties: { owner: 'data-team' } } + * ); + * console.log(response.namespace); // ['analytics'] + * console.log(response.properties); // { owner: 'data-team', ... } + * ``` + */ + async createNamespace(id, metadata) { + return this.namespaceOps.createNamespace(id, metadata); + } + /** + * Drops a namespace from the catalog. + * + * The namespace must be empty (contain no tables) before it can be dropped. + * + * @param id - Namespace identifier to drop + * + * @example + * ```typescript + * await catalog.dropNamespace({ namespace: ['analytics'] }); + * ``` + */ + async dropNamespace(id) { + await this.namespaceOps.dropNamespace(id); + } + /** + * Loads metadata for a namespace. + * + * @param id - Namespace identifier to load + * @returns Namespace metadata including properties + * + * @example + * ```typescript + * const metadata = await catalog.loadNamespaceMetadata({ namespace: ['analytics'] }); + * console.log(metadata.properties); + * ``` + */ + async loadNamespaceMetadata(id) { + return this.namespaceOps.loadNamespaceMetadata(id); + } + /** + * Lists all tables in a namespace. + * + * @param namespace - Namespace identifier to list tables from + * @returns Array of table identifiers + * + * @example + * ```typescript + * const tables = await catalog.listTables({ namespace: ['analytics'] }); + * console.log(tables); // [{ namespace: ['analytics'], name: 'events' }, ...] + * ``` + */ + async listTables(namespace) { + return this.tableOps.listTables(namespace); + } + /** + * Creates a new table in the catalog. + * + * @param namespace - Namespace to create the table in + * @param request - Table creation request including name, schema, partition spec, etc. + * @returns Table metadata for the created table + * + * @example + * ```typescript + * const metadata = await catalog.createTable( + * { namespace: ['analytics'] }, + * { + * name: 'events', + * schema: { + * type: 'struct', + * fields: [ + * { id: 1, name: 'id', type: 'long', required: true }, + * { id: 2, name: 'timestamp', type: 'timestamp', required: true } + * ], + * 'schema-id': 0 + * }, + * 'partition-spec': { + * 'spec-id': 0, + * fields: [ + * { source_id: 2, field_id: 1000, name: 'ts_day', transform: 'day' } + * ] + * } + * } + * ); + * ``` + */ + async createTable(namespace, request) { + return this.tableOps.createTable(namespace, request); + } + /** + * Updates an existing table's metadata. + * + * Can update the schema, partition spec, or properties of a table. + * + * @param id - Table identifier to update + * @param request - Update request with fields to modify + * @returns Response containing the metadata location and updated table metadata + * + * @example + * ```typescript + * const response = await catalog.updateTable( + * { namespace: ['analytics'], name: 'events' }, + * { + * properties: { 'read.split.target-size': '134217728' } + * } + * ); + * console.log(response['metadata-location']); // s3://... + * console.log(response.metadata); // TableMetadata object + * ``` + */ + async updateTable(id, request) { + return this.tableOps.updateTable(id, request); + } + /** + * Drops a table from the catalog. + * + * @param id - Table identifier to drop + * + * @example + * ```typescript + * await catalog.dropTable({ namespace: ['analytics'], name: 'events' }); + * ``` + */ + async dropTable(id, options) { + await this.tableOps.dropTable(id, options); + } + /** + * Loads metadata for a table. + * + * @param id - Table identifier to load + * @returns Table metadata including schema, partition spec, location, etc. + * + * @example + * ```typescript + * const metadata = await catalog.loadTable({ namespace: ['analytics'], name: 'events' }); + * console.log(metadata.schema); + * console.log(metadata.location); + * ``` + */ + async loadTable(id) { + return this.tableOps.loadTable(id); + } + /** + * Checks if a namespace exists in the catalog. + * + * @param id - Namespace identifier to check + * @returns True if the namespace exists, false otherwise + * + * @example + * ```typescript + * const exists = await catalog.namespaceExists({ namespace: ['analytics'] }); + * console.log(exists); // true or false + * ``` + */ + async namespaceExists(id) { + return this.namespaceOps.namespaceExists(id); + } + /** + * Checks if a table exists in the catalog. + * + * @param id - Table identifier to check + * @returns True if the table exists, false otherwise + * + * @example + * ```typescript + * const exists = await catalog.tableExists({ namespace: ['analytics'], name: 'events' }); + * console.log(exists); // true or false + * ``` + */ + async tableExists(id) { + return this.tableOps.tableExists(id); + } + /** + * Creates a namespace if it does not exist. + * + * If the namespace already exists, returns void. If created, returns the response. + * + * @param id - Namespace identifier to create + * @param metadata - Optional metadata properties for the namespace + * @returns Response containing the created namespace and its properties, or void if it already exists + * + * @example + * ```typescript + * const response = await catalog.createNamespaceIfNotExists( + * { namespace: ['analytics'] }, + * { properties: { owner: 'data-team' } } + * ); + * if (response) { + * console.log('Created:', response.namespace); + * } else { + * console.log('Already exists'); + * } + * ``` + */ + async createNamespaceIfNotExists(id, metadata) { + return this.namespaceOps.createNamespaceIfNotExists(id, metadata); + } + /** + * Creates a table if it does not exist. + * + * If the table already exists, returns its metadata instead. + * + * @param namespace - Namespace to create the table in + * @param request - Table creation request including name, schema, partition spec, etc. + * @returns Table metadata for the created or existing table + * + * @example + * ```typescript + * const metadata = await catalog.createTableIfNotExists( + * { namespace: ['analytics'] }, + * { + * name: 'events', + * schema: { + * type: 'struct', + * fields: [ + * { id: 1, name: 'id', type: 'long', required: true }, + * { id: 2, name: 'timestamp', type: 'timestamp', required: true } + * ], + * 'schema-id': 0 + * } + * } + * ); + * ``` + */ + async createTableIfNotExists(namespace, request) { + return this.tableOps.createTableIfNotExists(namespace, request); + } + }; + var DECIMAL_REGEX = /^decimal\s*\(\s*(\d+)\s*,\s*(\d+)\s*\)$/; + var FIXED_REGEX = /^fixed\s*\[\s*(\d+)\s*\]$/; + function parseDecimalType(type) { + const match = type.match(DECIMAL_REGEX); + if (!match) return null; + return { + precision: parseInt(match[1], 10), + scale: parseInt(match[2], 10) + }; + } + function parseFixedType(type) { + const match = type.match(FIXED_REGEX); + if (!match) return null; + return { + length: parseInt(match[1], 10) + }; + } + function isDecimalType(type) { + return DECIMAL_REGEX.test(type); + } + function isFixedType(type) { + return FIXED_REGEX.test(type); + } + function typesEqual(a, b) { + const decimalA = parseDecimalType(a); + const decimalB = parseDecimalType(b); + if (decimalA && decimalB) { + return decimalA.precision === decimalB.precision && decimalA.scale === decimalB.scale; + } + const fixedA = parseFixedType(a); + const fixedB = parseFixedType(b); + if (fixedA && fixedB) { + return fixedA.length === fixedB.length; + } + return a === b; + } + function getCurrentSchema(metadata) { + return metadata.schemas.find((s) => s["schema-id"] === metadata["current-schema-id"]); + } + exports.IcebergError = IcebergError; + exports.IcebergRestCatalog = IcebergRestCatalog; + exports.getCurrentSchema = getCurrentSchema; + exports.isDecimalType = isDecimalType; + exports.isFixedType = isFixedType; + exports.parseDecimalType = parseDecimalType; + exports.parseFixedType = parseFixedType; + exports.typesEqual = typesEqual; + } +}); + +// node_modules/@supabase/storage-js/dist/main/packages/StorageAnalyticsClient.js +var require_StorageAnalyticsClient = __commonJS({ + "node_modules/@supabase/storage-js/dist/main/packages/StorageAnalyticsClient.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var iceberg_js_1 = require_dist2(); + var constants_1 = require_constants3(); + var errors_1 = require_errors(); + var fetch_1 = require_fetch(); + var helpers_1 = require_helpers(); + var StorageAnalyticsClient = class { + /** + * @alpha + * + * Creates a new StorageAnalyticsClient instance + * + * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. + * + * @category Analytics Buckets + * @param url - The base URL for the storage API + * @param headers - HTTP headers to include in requests + * @param fetch - Optional custom fetch implementation + * + * @example + * ```typescript + * const client = new StorageAnalyticsClient(url, headers) + * ``` + */ + constructor(url, headers = {}, fetch2) { + this.shouldThrowOnError = false; + this.url = url.replace(/\/$/, ""); + this.headers = Object.assign(Object.assign({}, constants_1.DEFAULT_HEADERS), headers); + this.fetch = (0, helpers_1.resolveFetch)(fetch2); + } + /** + * @alpha + * + * Enable throwing errors instead of returning them in the response + * When enabled, failed operations will throw instead of returning { data: null, error } + * + * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. + * + * @category Analytics Buckets + * @returns This instance for method chaining + */ + throwOnError() { + this.shouldThrowOnError = true; + return this; + } + /** + * @alpha + * + * Creates a new analytics bucket using Iceberg tables + * Analytics buckets are optimized for analytical queries and data processing + * + * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. + * + * @category Analytics Buckets + * @param name A unique name for the bucket you are creating + * @returns Promise with response containing newly created analytics bucket or error + * + * @example Create analytics bucket + * ```js + * const { data, error } = await supabase + * .storage + * .analytics + * .createBucket('analytics-data') + * ``` + * + * Response: + * ```json + * { + * "data": { + * "name": "analytics-data", + * "type": "ANALYTICS", + * "format": "iceberg", + * "created_at": "2024-05-22T22:26:05.100Z", + * "updated_at": "2024-05-22T22:26:05.100Z" + * }, + * "error": null + * } + * ``` + */ + createBucket(name) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/bucket`, { name }, { headers: this.headers }); + return { data, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * @alpha + * + * Retrieves the details of all Analytics Storage buckets within an existing project + * Only returns buckets of type 'ANALYTICS' + * + * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. + * + * @category Analytics Buckets + * @param options Query parameters for listing buckets + * @param options.limit Maximum number of buckets to return + * @param options.offset Number of buckets to skip + * @param options.sortColumn Column to sort by ('name', 'created_at', 'updated_at') + * @param options.sortOrder Sort order ('asc' or 'desc') + * @param options.search Search term to filter bucket names + * @returns Promise with response containing array of analytics buckets or error + * + * @example List analytics buckets + * ```js + * const { data, error } = await supabase + * .storage + * .analytics + * .listBuckets({ + * limit: 10, + * offset: 0, + * sortColumn: 'created_at', + * sortOrder: 'desc' + * }) + * ``` + * + * Response: + * ```json + * { + * "data": [ + * { + * "name": "analytics-data", + * "type": "ANALYTICS", + * "format": "iceberg", + * "created_at": "2024-05-22T22:26:05.100Z", + * "updated_at": "2024-05-22T22:26:05.100Z" + * } + * ], + * "error": null + * } + * ``` + */ + listBuckets(options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const queryParams = new URLSearchParams(); + if ((options === null || options === void 0 ? void 0 : options.limit) !== void 0) + queryParams.set("limit", options.limit.toString()); + if ((options === null || options === void 0 ? void 0 : options.offset) !== void 0) + queryParams.set("offset", options.offset.toString()); + if (options === null || options === void 0 ? void 0 : options.sortColumn) + queryParams.set("sortColumn", options.sortColumn); + if (options === null || options === void 0 ? void 0 : options.sortOrder) + queryParams.set("sortOrder", options.sortOrder); + if (options === null || options === void 0 ? void 0 : options.search) + queryParams.set("search", options.search); + const queryString = queryParams.toString(); + const url = queryString ? `${this.url}/bucket?${queryString}` : `${this.url}/bucket`; + const data = yield (0, fetch_1.get)(this.fetch, url, { headers: this.headers }); + return { data, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * @alpha + * + * Deletes an existing analytics bucket + * A bucket can't be deleted with existing objects inside it + * You must first empty the bucket before deletion + * + * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. + * + * @category Analytics Buckets + * @param bucketName The unique identifier of the bucket you would like to delete + * @returns Promise with response containing success message or error + * + * @example Delete analytics bucket + * ```js + * const { data, error } = await supabase + * .storage + * .analytics + * .deleteBucket('analytics-data') + * ``` + * + * Response: + * ```json + * { + * "data": { + * "message": "Successfully deleted" + * }, + * "error": null + * } + * ``` + */ + deleteBucket(bucketName) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.remove)(this.fetch, `${this.url}/bucket/${bucketName}`, {}, { headers: this.headers }); + return { data, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * @alpha + * + * Get an Iceberg REST Catalog client configured for a specific analytics bucket + * Use this to perform advanced table and namespace operations within the bucket + * The returned client provides full access to the Apache Iceberg REST Catalog API + * with the Supabase `{ data, error }` pattern for consistent error handling on all operations. + * + * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. + * + * @category Analytics Buckets + * @param bucketName - The name of the analytics bucket (warehouse) to connect to + * @returns The wrapped Iceberg catalog client + * @throws {StorageError} If the bucket name is invalid + * + * @example Get catalog and create table + * ```js + * // First, create an analytics bucket + * const { data: bucket, error: bucketError } = await supabase + * .storage + * .analytics + * .createBucket('analytics-data') + * + * // Get the Iceberg catalog for that bucket + * const catalog = supabase.storage.analytics.from('analytics-data') + * + * // Create a namespace + * const { error: nsError } = await catalog.createNamespace({ namespace: ['default'] }) + * + * // Create a table with schema + * const { data: tableMetadata, error: tableError } = await catalog.createTable( + * { namespace: ['default'] }, + * { + * name: 'events', + * schema: { + * type: 'struct', + * fields: [ + * { id: 1, name: 'id', type: 'long', required: true }, + * { id: 2, name: 'timestamp', type: 'timestamp', required: true }, + * { id: 3, name: 'user_id', type: 'string', required: false } + * ], + * 'schema-id': 0, + * 'identifier-field-ids': [1] + * }, + * 'partition-spec': { + * 'spec-id': 0, + * fields: [] + * }, + * 'write-order': { + * 'order-id': 0, + * fields: [] + * }, + * properties: { + * 'write.format.default': 'parquet' + * } + * } + * ) + * ``` + * + * @example List tables in namespace + * ```js + * const catalog = supabase.storage.analytics.from('analytics-data') + * + * // List all tables in the default namespace + * const { data: tables, error: listError } = await catalog.listTables({ namespace: ['default'] }) + * if (listError) { + * if (listError.isNotFound()) { + * console.log('Namespace not found') + * } + * return + * } + * console.log(tables) // [{ namespace: ['default'], name: 'events' }] + * ``` + * + * @example Working with namespaces + * ```js + * const catalog = supabase.storage.analytics.from('analytics-data') + * + * // List all namespaces + * const { data: namespaces } = await catalog.listNamespaces() + * + * // Create namespace with properties + * await catalog.createNamespace( + * { namespace: ['production'] }, + * { properties: { owner: 'data-team', env: 'prod' } } + * ) + * ``` + * + * @example Cleanup operations + * ```js + * const catalog = supabase.storage.analytics.from('analytics-data') + * + * // Drop table with purge option (removes all data) + * const { error: dropError } = await catalog.dropTable( + * { namespace: ['default'], name: 'events' }, + * { purge: true } + * ) + * + * if (dropError?.isNotFound()) { + * console.log('Table does not exist') + * } + * + * // Drop namespace (must be empty) + * await catalog.dropNamespace({ namespace: ['default'] }) + * ``` + * + * @remarks + * This method provides a bridge between Supabase's bucket management and the standard + * Apache Iceberg REST Catalog API. The bucket name maps to the Iceberg warehouse parameter. + * All authentication and configuration is handled automatically using your Supabase credentials. + * + * **Error Handling**: Invalid bucket names throw immediately. All catalog + * operations return `{ data, error }` where errors are `IcebergError` instances from iceberg-js. + * Use helper methods like `error.isNotFound()` or check `error.status` for specific error handling. + * Use `.throwOnError()` on the analytics client if you prefer exceptions for catalog operations. + * + * **Cleanup Operations**: When using `dropTable`, the `purge: true` option permanently + * deletes all table data. Without it, the table is marked as deleted but data remains. + * + * **Library Dependency**: The returned catalog wraps `IcebergRestCatalog` from iceberg-js. + * For complete API documentation and advanced usage, refer to the + * [iceberg-js documentation](https://supabase.github.io/iceberg-js/). + */ + from(bucketName) { + if (!(0, helpers_1.isValidBucketName)(bucketName)) { + throw new errors_1.StorageError("Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters."); + } + const catalog = new iceberg_js_1.IcebergRestCatalog({ + baseUrl: this.url, + catalogName: bucketName, + // Maps to the warehouse parameter in Supabase's implementation + auth: { + type: "custom", + getHeaders: () => tslib_1.__awaiter(this, void 0, void 0, function* () { + return this.headers; + }) + }, + fetch: this.fetch + }); + const shouldThrowOnError = this.shouldThrowOnError; + const wrappedCatalog = new Proxy(catalog, { + get(target, prop) { + const value = target[prop]; + if (typeof value !== "function") { + return value; + } + return (...args) => tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield value.apply(target, args); + return { data, error: null }; + } catch (error) { + if (shouldThrowOnError) { + throw error; + } + return { data: null, error }; + } + }); + } + }); + return wrappedCatalog; + } + }; + exports.default = StorageAnalyticsClient; + } +}); + +// node_modules/@supabase/storage-js/dist/main/lib/vectors/constants.js +var require_constants4 = __commonJS({ + "node_modules/@supabase/storage-js/dist/main/lib/vectors/constants.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DEFAULT_HEADERS = void 0; + var version_1 = require_version2(); + exports.DEFAULT_HEADERS = { + "X-Client-Info": `storage-js/${version_1.version}`, + "Content-Type": "application/json" + }; + } +}); + +// node_modules/@supabase/storage-js/dist/main/lib/vectors/errors.js +var require_errors2 = __commonJS({ + "node_modules/@supabase/storage-js/dist/main/lib/vectors/errors.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.StorageVectorsErrorCode = exports.StorageVectorsUnknownError = exports.StorageVectorsApiError = exports.StorageVectorsError = void 0; + exports.isStorageVectorsError = isStorageVectorsError; + var StorageVectorsError = class extends Error { + constructor(message) { + super(message); + this.__isStorageVectorsError = true; + this.name = "StorageVectorsError"; + } + }; + exports.StorageVectorsError = StorageVectorsError; + function isStorageVectorsError(error) { + return typeof error === "object" && error !== null && "__isStorageVectorsError" in error; + } + var StorageVectorsApiError = class extends StorageVectorsError { + constructor(message, status, statusCode) { + super(message); + this.name = "StorageVectorsApiError"; + this.status = status; + this.statusCode = statusCode; + } + toJSON() { + return { + name: this.name, + message: this.message, + status: this.status, + statusCode: this.statusCode + }; + } + }; + exports.StorageVectorsApiError = StorageVectorsApiError; + var StorageVectorsUnknownError = class extends StorageVectorsError { + constructor(message, originalError) { + super(message); + this.name = "StorageVectorsUnknownError"; + this.originalError = originalError; + } + }; + exports.StorageVectorsUnknownError = StorageVectorsUnknownError; + var StorageVectorsErrorCode; + (function(StorageVectorsErrorCode2) { + StorageVectorsErrorCode2["InternalError"] = "InternalError"; + StorageVectorsErrorCode2["S3VectorConflictException"] = "S3VectorConflictException"; + StorageVectorsErrorCode2["S3VectorNotFoundException"] = "S3VectorNotFoundException"; + StorageVectorsErrorCode2["S3VectorBucketNotEmpty"] = "S3VectorBucketNotEmpty"; + StorageVectorsErrorCode2["S3VectorMaxBucketsExceeded"] = "S3VectorMaxBucketsExceeded"; + StorageVectorsErrorCode2["S3VectorMaxIndexesExceeded"] = "S3VectorMaxIndexesExceeded"; + })(StorageVectorsErrorCode || (exports.StorageVectorsErrorCode = StorageVectorsErrorCode = {})); + } +}); + +// node_modules/@supabase/storage-js/dist/main/lib/vectors/helpers.js +var require_helpers2 = __commonJS({ + "node_modules/@supabase/storage-js/dist/main/lib/vectors/helpers.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateVectorDimension = exports.normalizeToFloat32 = exports.isPlainObject = exports.resolveResponse = exports.resolveFetch = void 0; + var resolveFetch = (customFetch) => { + if (customFetch) { + return (...args) => customFetch(...args); + } + return (...args) => fetch(...args); + }; + exports.resolveFetch = resolveFetch; + var resolveResponse = () => { + return Response; + }; + exports.resolveResponse = resolveResponse; + var isPlainObject2 = (value) => { + if (typeof value !== "object" || value === null) { + return false; + } + const prototype = Object.getPrototypeOf(value); + return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value); + }; + exports.isPlainObject = isPlainObject2; + var normalizeToFloat32 = (values) => { + return Array.from(new Float32Array(values)); + }; + exports.normalizeToFloat32 = normalizeToFloat32; + var validateVectorDimension = (vector, expectedDimension) => { + if (expectedDimension !== void 0 && vector.float32.length !== expectedDimension) { + throw new Error(`Vector dimension mismatch: expected ${expectedDimension}, got ${vector.float32.length}`); + } + }; + exports.validateVectorDimension = validateVectorDimension; + } +}); + +// node_modules/@supabase/storage-js/dist/main/lib/vectors/fetch.js +var require_fetch2 = __commonJS({ + "node_modules/@supabase/storage-js/dist/main/lib/vectors/fetch.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.get = get; + exports.post = post; + exports.put = put; + exports.remove = remove2; + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var errors_1 = require_errors2(); + var helpers_1 = require_helpers2(); + var _getErrorMessage = (err) => err.msg || err.message || err.error_description || err.error || JSON.stringify(err); + var handleError = (error, reject, options) => tslib_1.__awaiter(void 0, void 0, void 0, function* () { + const isResponseLike = error && typeof error === "object" && "status" in error && "ok" in error && typeof error.status === "number"; + if (isResponseLike && !(options === null || options === void 0 ? void 0 : options.noResolveJson)) { + const status = error.status || 500; + const responseError = error; + if (typeof responseError.json === "function") { + responseError.json().then((err) => { + const statusCode = (err === null || err === void 0 ? void 0 : err.statusCode) || (err === null || err === void 0 ? void 0 : err.code) || status + ""; + reject(new errors_1.StorageVectorsApiError(_getErrorMessage(err), status, statusCode)); + }).catch(() => { + const statusCode = status + ""; + const message = responseError.statusText || `HTTP ${status} error`; + reject(new errors_1.StorageVectorsApiError(message, status, statusCode)); + }); + } else { + const statusCode = status + ""; + const message = responseError.statusText || `HTTP ${status} error`; + reject(new errors_1.StorageVectorsApiError(message, status, statusCode)); + } + } else { + reject(new errors_1.StorageVectorsUnknownError(_getErrorMessage(error), error)); + } + }); + var _getRequestParams = (method, options, parameters, body) => { + const params = { method, headers: (options === null || options === void 0 ? void 0 : options.headers) || {} }; + if (method === "GET" || !body) { + return params; + } + if ((0, helpers_1.isPlainObject)(body)) { + params.headers = Object.assign({ "Content-Type": "application/json" }, options === null || options === void 0 ? void 0 : options.headers); + params.body = JSON.stringify(body); + } else { + params.body = body; + } + return Object.assign(Object.assign({}, params), parameters); + }; + function _handleRequest(fetcher, method, url, options, parameters, body) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return new Promise((resolve, reject) => { + fetcher(url, _getRequestParams(method, options, parameters, body)).then((result) => { + if (!result.ok) + throw result; + if (options === null || options === void 0 ? void 0 : options.noResolveJson) + return result; + const contentType = result.headers.get("content-type"); + if (!contentType || !contentType.includes("application/json")) { + return {}; + } + return result.json(); + }).then((data) => resolve(data)).catch((error) => handleError(error, reject, options)); + }); + }); + } + function get(fetcher, url, options, parameters) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _handleRequest(fetcher, "GET", url, options, parameters); + }); + } + function post(fetcher, url, body, options, parameters) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _handleRequest(fetcher, "POST", url, options, parameters, body); + }); + } + function put(fetcher, url, body, options, parameters) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _handleRequest(fetcher, "PUT", url, options, parameters, body); + }); + } + function remove2(fetcher, url, body, options, parameters) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _handleRequest(fetcher, "DELETE", url, options, parameters, body); + }); + } + } +}); + +// node_modules/@supabase/storage-js/dist/main/lib/vectors/VectorIndexApi.js +var require_VectorIndexApi = __commonJS({ + "node_modules/@supabase/storage-js/dist/main/lib/vectors/VectorIndexApi.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var constants_1 = require_constants4(); + var errors_1 = require_errors2(); + var fetch_1 = require_fetch2(); + var helpers_1 = require_helpers2(); + var VectorIndexApi = class { + /** Creates a new VectorIndexApi instance */ + constructor(url, headers = {}, fetch2) { + this.shouldThrowOnError = false; + this.url = url.replace(/\/$/, ""); + this.headers = Object.assign(Object.assign({}, constants_1.DEFAULT_HEADERS), headers); + this.fetch = (0, helpers_1.resolveFetch)(fetch2); + } + /** Enable throwing errors instead of returning them in the response */ + throwOnError() { + this.shouldThrowOnError = true; + return this; + } + /** Creates a new vector index within a bucket */ + createIndex(options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/CreateIndex`, options, { + headers: this.headers + }); + return { data: data || {}, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageVectorsError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** Retrieves metadata for a specific vector index */ + getIndex(vectorBucketName, indexName) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/GetIndex`, { vectorBucketName, indexName }, { headers: this.headers }); + return { data, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageVectorsError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** Lists vector indexes within a bucket with optional filtering and pagination */ + listIndexes(options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/ListIndexes`, options, { + headers: this.headers + }); + return { data, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageVectorsError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** Deletes a vector index and all its data */ + deleteIndex(vectorBucketName, indexName) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/DeleteIndex`, { vectorBucketName, indexName }, { headers: this.headers }); + return { data: data || {}, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageVectorsError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + }; + exports.default = VectorIndexApi; + } +}); + +// node_modules/@supabase/storage-js/dist/main/lib/vectors/VectorDataApi.js +var require_VectorDataApi = __commonJS({ + "node_modules/@supabase/storage-js/dist/main/lib/vectors/VectorDataApi.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var constants_1 = require_constants4(); + var errors_1 = require_errors2(); + var fetch_1 = require_fetch2(); + var helpers_1 = require_helpers2(); + var VectorDataApi = class { + /** Creates a new VectorDataApi instance */ + constructor(url, headers = {}, fetch2) { + this.shouldThrowOnError = false; + this.url = url.replace(/\/$/, ""); + this.headers = Object.assign(Object.assign({}, constants_1.DEFAULT_HEADERS), headers); + this.fetch = (0, helpers_1.resolveFetch)(fetch2); + } + /** Enable throwing errors instead of returning them in the response */ + throwOnError() { + this.shouldThrowOnError = true; + return this; + } + /** Inserts or updates vectors in batch (1-500 per request) */ + putVectors(options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + if (options.vectors.length < 1 || options.vectors.length > 500) { + throw new Error("Vector batch size must be between 1 and 500 items"); + } + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/PutVectors`, options, { + headers: this.headers + }); + return { data: data || {}, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageVectorsError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** Retrieves vectors by their keys in batch */ + getVectors(options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/GetVectors`, options, { + headers: this.headers + }); + return { data, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageVectorsError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** Lists vectors in an index with pagination */ + listVectors(options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + if (options.segmentCount !== void 0) { + if (options.segmentCount < 1 || options.segmentCount > 16) { + throw new Error("segmentCount must be between 1 and 16"); + } + if (options.segmentIndex !== void 0) { + if (options.segmentIndex < 0 || options.segmentIndex >= options.segmentCount) { + throw new Error(`segmentIndex must be between 0 and ${options.segmentCount - 1}`); + } + } + } + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/ListVectors`, options, { + headers: this.headers + }); + return { data, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageVectorsError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** Queries for similar vectors using approximate nearest neighbor search */ + queryVectors(options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/QueryVectors`, options, { + headers: this.headers + }); + return { data, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageVectorsError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** Deletes vectors by their keys in batch (1-500 per request) */ + deleteVectors(options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + if (options.keys.length < 1 || options.keys.length > 500) { + throw new Error("Keys batch size must be between 1 and 500 items"); + } + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/DeleteVectors`, options, { + headers: this.headers + }); + return { data: data || {}, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageVectorsError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + }; + exports.default = VectorDataApi; + } +}); + +// node_modules/@supabase/storage-js/dist/main/lib/vectors/VectorBucketApi.js +var require_VectorBucketApi = __commonJS({ + "node_modules/@supabase/storage-js/dist/main/lib/vectors/VectorBucketApi.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var constants_1 = require_constants4(); + var errors_1 = require_errors2(); + var fetch_1 = require_fetch2(); + var helpers_1 = require_helpers2(); + var VectorBucketApi = class { + /** Creates a new VectorBucketApi instance */ + constructor(url, headers = {}, fetch2) { + this.shouldThrowOnError = false; + this.url = url.replace(/\/$/, ""); + this.headers = Object.assign(Object.assign({}, constants_1.DEFAULT_HEADERS), headers); + this.fetch = (0, helpers_1.resolveFetch)(fetch2); + } + /** Enable throwing errors instead of returning them in the response */ + throwOnError() { + this.shouldThrowOnError = true; + return this; + } + /** Creates a new vector bucket */ + createBucket(vectorBucketName) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/CreateVectorBucket`, { vectorBucketName }, { headers: this.headers }); + return { data: data || {}, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageVectorsError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** Retrieves metadata for a specific vector bucket */ + getBucket(vectorBucketName) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/GetVectorBucket`, { vectorBucketName }, { headers: this.headers }); + return { data, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageVectorsError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** Lists vector buckets with optional filtering and pagination */ + listBuckets() { + return tslib_1.__awaiter(this, arguments, void 0, function* (options = {}) { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/ListVectorBuckets`, options, { + headers: this.headers + }); + return { data, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageVectorsError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** Deletes a vector bucket (must be empty first) */ + deleteBucket(vectorBucketName) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/DeleteVectorBucket`, { vectorBucketName }, { headers: this.headers }); + return { data: data || {}, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageVectorsError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + }; + exports.default = VectorBucketApi; + } +}); + +// node_modules/@supabase/storage-js/dist/main/lib/vectors/StorageVectorsClient.js +var require_StorageVectorsClient = __commonJS({ + "node_modules/@supabase/storage-js/dist/main/lib/vectors/StorageVectorsClient.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.VectorIndexScope = exports.VectorBucketScope = exports.StorageVectorsClient = void 0; + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var VectorIndexApi_1 = tslib_1.__importDefault(require_VectorIndexApi()); + var VectorDataApi_1 = tslib_1.__importDefault(require_VectorDataApi()); + var VectorBucketApi_1 = tslib_1.__importDefault(require_VectorBucketApi()); + var StorageVectorsClient = class extends VectorBucketApi_1.default { + /** + * @alpha + * + * Creates a StorageVectorsClient that can manage buckets, indexes, and vectors. + * + * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. + * + * @category Vector Buckets + * @param url - Base URL of the Storage Vectors REST API. + * @param options.headers - Optional headers (for example `Authorization`) applied to every request. + * @param options.fetch - Optional custom `fetch` implementation for non-browser runtimes. + * + * @example + * ```typescript + * const client = new StorageVectorsClient(url, options) + * ``` + */ + constructor(url, options = {}) { + super(url, options.headers || {}, options.fetch); + } + /** + * + * @alpha + * + * Access operations for a specific vector bucket + * Returns a scoped client for index and vector operations within the bucket + * + * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. + * + * @category Vector Buckets + * @param vectorBucketName - Name of the vector bucket + * @returns Bucket-scoped client with index and vector operations + * + * @example + * ```typescript + * const bucket = supabase.storage.vectors.from('embeddings-prod') + * ``` + */ + from(vectorBucketName) { + return new VectorBucketScope(this.url, this.headers, vectorBucketName, this.fetch); + } + /** + * + * @alpha + * + * Creates a new vector bucket + * Vector buckets are containers for vector indexes and their data + * + * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. + * + * @category Vector Buckets + * @param vectorBucketName - Unique name for the vector bucket + * @returns Promise with empty response on success or error + * + * @example + * ```typescript + * const { data, error } = await supabase + * .storage + * .vectors + * .createBucket('embeddings-prod') + * ``` + */ + createBucket(vectorBucketName) { + const _super = Object.create(null, { + createBucket: { get: () => super.createBucket } + }); + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _super.createBucket.call(this, vectorBucketName); + }); + } + /** + * + * @alpha + * + * Retrieves metadata for a specific vector bucket + * + * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. + * + * @category Vector Buckets + * @param vectorBucketName - Name of the vector bucket + * @returns Promise with bucket metadata or error + * + * @example + * ```typescript + * const { data, error } = await supabase + * .storage + * .vectors + * .getBucket('embeddings-prod') + * + * console.log('Bucket created:', data?.vectorBucket.creationTime) + * ``` + */ + getBucket(vectorBucketName) { + const _super = Object.create(null, { + getBucket: { get: () => super.getBucket } + }); + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _super.getBucket.call(this, vectorBucketName); + }); + } + /** + * + * @alpha + * + * Lists all vector buckets with optional filtering and pagination + * + * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. + * + * @category Vector Buckets + * @param options - Optional filters (prefix, maxResults, nextToken) + * @returns Promise with list of buckets or error + * + * @example + * ```typescript + * const { data, error } = await supabase + * .storage + * .vectors + * .listBuckets({ prefix: 'embeddings-' }) + * + * data?.vectorBuckets.forEach(bucket => { + * console.log(bucket.vectorBucketName) + * }) + * ``` + */ + listBuckets() { + const _super = Object.create(null, { + listBuckets: { get: () => super.listBuckets } + }); + return tslib_1.__awaiter(this, arguments, void 0, function* (options = {}) { + return _super.listBuckets.call(this, options); + }); + } + /** + * + * @alpha + * + * Deletes a vector bucket (bucket must be empty) + * All indexes must be deleted before deleting the bucket + * + * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. + * + * @category Vector Buckets + * @param vectorBucketName - Name of the vector bucket to delete + * @returns Promise with empty response on success or error + * + * @example + * ```typescript + * const { data, error } = await supabase + * .storage + * .vectors + * .deleteBucket('embeddings-old') + * ``` + */ + deleteBucket(vectorBucketName) { + const _super = Object.create(null, { + deleteBucket: { get: () => super.deleteBucket } + }); + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _super.deleteBucket.call(this, vectorBucketName); + }); + } + }; + exports.StorageVectorsClient = StorageVectorsClient; + var VectorBucketScope = class extends VectorIndexApi_1.default { + /** + * @alpha + * + * Creates a helper that automatically scopes all index operations to the provided bucket. + * + * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. + * + * @category Vector Buckets + * @example + * ```typescript + * const bucket = supabase.storage.vectors.from('embeddings-prod') + * ``` + */ + constructor(url, headers, vectorBucketName, fetch2) { + super(url, headers, fetch2); + this.vectorBucketName = vectorBucketName; + } + /** + * + * @alpha + * + * Creates a new vector index in this bucket + * Convenience method that automatically includes the bucket name + * + * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. + * + * @category Vector Buckets + * @param options - Index configuration (vectorBucketName is automatically set) + * @returns Promise with empty response on success or error + * + * @example + * ```typescript + * const bucket = supabase.storage.vectors.from('embeddings-prod') + * await bucket.createIndex({ + * indexName: 'documents-openai', + * dataType: 'float32', + * dimension: 1536, + * distanceMetric: 'cosine', + * metadataConfiguration: { + * nonFilterableMetadataKeys: ['raw_text'] + * } + * }) + * ``` + */ + createIndex(options) { + const _super = Object.create(null, { + createIndex: { get: () => super.createIndex } + }); + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _super.createIndex.call(this, Object.assign(Object.assign({}, options), { vectorBucketName: this.vectorBucketName })); + }); + } + /** + * + * @alpha + * + * Lists indexes in this bucket + * Convenience method that automatically includes the bucket name + * + * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. + * + * @category Vector Buckets + * @param options - Listing options (vectorBucketName is automatically set) + * @returns Promise with response containing indexes array and pagination token or error + * + * @example + * ```typescript + * const bucket = supabase.storage.vectors.from('embeddings-prod') + * const { data } = await bucket.listIndexes({ prefix: 'documents-' }) + * ``` + */ + listIndexes() { + const _super = Object.create(null, { + listIndexes: { get: () => super.listIndexes } + }); + return tslib_1.__awaiter(this, arguments, void 0, function* (options = {}) { + return _super.listIndexes.call(this, Object.assign(Object.assign({}, options), { vectorBucketName: this.vectorBucketName })); + }); + } + /** + * + * @alpha + * + * Retrieves metadata for a specific index in this bucket + * Convenience method that automatically includes the bucket name + * + * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. + * + * @category Vector Buckets + * @param indexName - Name of the index to retrieve + * @returns Promise with index metadata or error + * + * @example + * ```typescript + * const bucket = supabase.storage.vectors.from('embeddings-prod') + * const { data } = await bucket.getIndex('documents-openai') + * console.log('Dimension:', data?.index.dimension) + * ``` + */ + getIndex(indexName) { + const _super = Object.create(null, { + getIndex: { get: () => super.getIndex } + }); + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _super.getIndex.call(this, this.vectorBucketName, indexName); + }); + } + /** + * + * @alpha + * + * Deletes an index from this bucket + * Convenience method that automatically includes the bucket name + * + * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. + * + * @category Vector Buckets + * @param indexName - Name of the index to delete + * @returns Promise with empty response on success or error + * + * @example + * ```typescript + * const bucket = supabase.storage.vectors.from('embeddings-prod') + * await bucket.deleteIndex('old-index') + * ``` + */ + deleteIndex(indexName) { + const _super = Object.create(null, { + deleteIndex: { get: () => super.deleteIndex } + }); + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _super.deleteIndex.call(this, this.vectorBucketName, indexName); + }); + } + /** + * + * @alpha + * + * Access operations for a specific index within this bucket + * Returns a scoped client for vector data operations + * + * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. + * + * @category Vector Buckets + * @param indexName - Name of the index + * @returns Index-scoped client with vector data operations + * + * @example + * ```typescript + * const index = supabase.storage.vectors.from('embeddings-prod').index('documents-openai') + * + * // Insert vectors + * await index.putVectors({ + * vectors: [ + * { key: 'doc-1', data: { float32: [...] }, metadata: { title: 'Intro' } } + * ] + * }) + * + * // Query similar vectors + * const { data } = await index.queryVectors({ + * queryVector: { float32: [...] }, + * topK: 5 + * }) + * ``` + */ + index(indexName) { + return new VectorIndexScope(this.url, this.headers, this.vectorBucketName, indexName, this.fetch); + } + }; + exports.VectorBucketScope = VectorBucketScope; + var VectorIndexScope = class extends VectorDataApi_1.default { + /** + * + * @alpha + * + * Creates a helper that automatically scopes all vector operations to the provided bucket/index names. + * + * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. + * + * @category Vector Buckets + * @example + * ```typescript + * const index = supabase.storage.vectors.from('embeddings-prod').index('documents-openai') + * ``` + */ + constructor(url, headers, vectorBucketName, indexName, fetch2) { + super(url, headers, fetch2); + this.vectorBucketName = vectorBucketName; + this.indexName = indexName; + } + /** + * + * @alpha + * + * Inserts or updates vectors in this index + * Convenience method that automatically includes bucket and index names + * + * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. + * + * @category Vector Buckets + * @param options - Vector insertion options (bucket and index names automatically set) + * @returns Promise with empty response on success or error + * + * @example + * ```typescript + * const index = supabase.storage.vectors.from('embeddings-prod').index('documents-openai') + * await index.putVectors({ + * vectors: [ + * { + * key: 'doc-1', + * data: { float32: [0.1, 0.2, ...] }, + * metadata: { title: 'Introduction', page: 1 } + * } + * ] + * }) + * ``` + */ + putVectors(options) { + const _super = Object.create(null, { + putVectors: { get: () => super.putVectors } + }); + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _super.putVectors.call(this, Object.assign(Object.assign({}, options), { vectorBucketName: this.vectorBucketName, indexName: this.indexName })); + }); + } + /** + * + * @alpha + * + * Retrieves vectors by keys from this index + * Convenience method that automatically includes bucket and index names + * + * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. + * + * @category Vector Buckets + * @param options - Vector retrieval options (bucket and index names automatically set) + * @returns Promise with response containing vectors array or error + * + * @example + * ```typescript + * const index = supabase.storage.vectors.from('embeddings-prod').index('documents-openai') + * const { data } = await index.getVectors({ + * keys: ['doc-1', 'doc-2'], + * returnMetadata: true + * }) + * ``` + */ + getVectors(options) { + const _super = Object.create(null, { + getVectors: { get: () => super.getVectors } + }); + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _super.getVectors.call(this, Object.assign(Object.assign({}, options), { vectorBucketName: this.vectorBucketName, indexName: this.indexName })); + }); + } + /** + * + * @alpha + * + * Lists vectors in this index with pagination + * Convenience method that automatically includes bucket and index names + * + * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. + * + * @category Vector Buckets + * @param options - Listing options (bucket and index names automatically set) + * @returns Promise with response containing vectors array and pagination token or error + * + * @example + * ```typescript + * const index = supabase.storage.vectors.from('embeddings-prod').index('documents-openai') + * const { data } = await index.listVectors({ + * maxResults: 500, + * returnMetadata: true + * }) + * ``` + */ + listVectors() { + const _super = Object.create(null, { + listVectors: { get: () => super.listVectors } + }); + return tslib_1.__awaiter(this, arguments, void 0, function* (options = {}) { + return _super.listVectors.call(this, Object.assign(Object.assign({}, options), { vectorBucketName: this.vectorBucketName, indexName: this.indexName })); + }); + } + /** + * + * @alpha + * + * Queries for similar vectors in this index + * Convenience method that automatically includes bucket and index names + * + * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. + * + * @category Vector Buckets + * @param options - Query options (bucket and index names automatically set) + * @returns Promise with response containing matches array of similar vectors ordered by distance or error + * + * @example + * ```typescript + * const index = supabase.storage.vectors.from('embeddings-prod').index('documents-openai') + * const { data } = await index.queryVectors({ + * queryVector: { float32: [0.1, 0.2, ...] }, + * topK: 5, + * filter: { category: 'technical' }, + * returnDistance: true, + * returnMetadata: true + * }) + * ``` + */ + queryVectors(options) { + const _super = Object.create(null, { + queryVectors: { get: () => super.queryVectors } + }); + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _super.queryVectors.call(this, Object.assign(Object.assign({}, options), { vectorBucketName: this.vectorBucketName, indexName: this.indexName })); + }); + } + /** + * + * @alpha + * + * Deletes vectors by keys from this index + * Convenience method that automatically includes bucket and index names + * + * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. + * + * @category Vector Buckets + * @param options - Deletion options (bucket and index names automatically set) + * @returns Promise with empty response on success or error + * + * @example + * ```typescript + * const index = supabase.storage.vectors.from('embeddings-prod').index('documents-openai') + * await index.deleteVectors({ + * keys: ['doc-1', 'doc-2', 'doc-3'] + * }) + * ``` + */ + deleteVectors(options) { + const _super = Object.create(null, { + deleteVectors: { get: () => super.deleteVectors } + }); + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _super.deleteVectors.call(this, Object.assign(Object.assign({}, options), { vectorBucketName: this.vectorBucketName, indexName: this.indexName })); + }); + } + }; + exports.VectorIndexScope = VectorIndexScope; + } +}); + +// node_modules/@supabase/storage-js/dist/main/lib/vectors/index.js +var require_vectors = __commonJS({ + "node_modules/@supabase/storage-js/dist/main/lib/vectors/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateVectorDimension = exports.normalizeToFloat32 = exports.isPlainObject = exports.resolveResponse = exports.resolveFetch = exports.isStorageVectorsError = exports.StorageVectorsErrorCode = exports.StorageVectorsUnknownError = exports.StorageVectorsApiError = exports.StorageVectorsError = exports.VectorDataApi = exports.VectorIndexApi = exports.VectorBucketApi = exports.VectorIndexScope = exports.VectorBucketScope = exports.StorageVectorsClient = void 0; + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var StorageVectorsClient_1 = require_StorageVectorsClient(); + Object.defineProperty(exports, "StorageVectorsClient", { enumerable: true, get: function() { + return StorageVectorsClient_1.StorageVectorsClient; + } }); + Object.defineProperty(exports, "VectorBucketScope", { enumerable: true, get: function() { + return StorageVectorsClient_1.VectorBucketScope; + } }); + Object.defineProperty(exports, "VectorIndexScope", { enumerable: true, get: function() { + return StorageVectorsClient_1.VectorIndexScope; + } }); + var VectorBucketApi_1 = require_VectorBucketApi(); + Object.defineProperty(exports, "VectorBucketApi", { enumerable: true, get: function() { + return tslib_1.__importDefault(VectorBucketApi_1).default; + } }); + var VectorIndexApi_1 = require_VectorIndexApi(); + Object.defineProperty(exports, "VectorIndexApi", { enumerable: true, get: function() { + return tslib_1.__importDefault(VectorIndexApi_1).default; + } }); + var VectorDataApi_1 = require_VectorDataApi(); + Object.defineProperty(exports, "VectorDataApi", { enumerable: true, get: function() { + return tslib_1.__importDefault(VectorDataApi_1).default; + } }); + var errors_1 = require_errors2(); + Object.defineProperty(exports, "StorageVectorsError", { enumerable: true, get: function() { + return errors_1.StorageVectorsError; + } }); + Object.defineProperty(exports, "StorageVectorsApiError", { enumerable: true, get: function() { + return errors_1.StorageVectorsApiError; + } }); + Object.defineProperty(exports, "StorageVectorsUnknownError", { enumerable: true, get: function() { + return errors_1.StorageVectorsUnknownError; + } }); + Object.defineProperty(exports, "StorageVectorsErrorCode", { enumerable: true, get: function() { + return errors_1.StorageVectorsErrorCode; + } }); + Object.defineProperty(exports, "isStorageVectorsError", { enumerable: true, get: function() { + return errors_1.isStorageVectorsError; + } }); + var helpers_1 = require_helpers2(); + Object.defineProperty(exports, "resolveFetch", { enumerable: true, get: function() { + return helpers_1.resolveFetch; + } }); + Object.defineProperty(exports, "resolveResponse", { enumerable: true, get: function() { + return helpers_1.resolveResponse; + } }); + Object.defineProperty(exports, "isPlainObject", { enumerable: true, get: function() { + return helpers_1.isPlainObject; + } }); + Object.defineProperty(exports, "normalizeToFloat32", { enumerable: true, get: function() { + return helpers_1.normalizeToFloat32; + } }); + Object.defineProperty(exports, "validateVectorDimension", { enumerable: true, get: function() { + return helpers_1.validateVectorDimension; + } }); + } +}); + +// node_modules/@supabase/storage-js/dist/main/StorageClient.js +var require_StorageClient = __commonJS({ + "node_modules/@supabase/storage-js/dist/main/StorageClient.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.StorageClient = void 0; + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var StorageFileApi_1 = tslib_1.__importDefault(require_StorageFileApi()); + var StorageBucketApi_1 = tslib_1.__importDefault(require_StorageBucketApi()); + var StorageAnalyticsClient_1 = tslib_1.__importDefault(require_StorageAnalyticsClient()); + var vectors_1 = require_vectors(); + var StorageClient = class extends StorageBucketApi_1.default { + /** + * Creates a client for Storage buckets, files, analytics, and vectors. + * + * @category File Buckets + * @example + * ```ts + * import { StorageClient } from '@supabase/storage-js' + * + * const storage = new StorageClient('https://xyzcompany.supabase.co/storage/v1', { + * apikey: 'public-anon-key', + * }) + * const avatars = storage.from('avatars') + * ``` + */ + constructor(url, headers = {}, fetch2, opts) { + super(url, headers, fetch2, opts); + } + /** + * Perform file operation in a bucket. + * + * @category File Buckets + * @param id The bucket id to operate on. + * + * @example + * ```typescript + * const avatars = supabase.storage.from('avatars') + * ``` + */ + from(id) { + return new StorageFileApi_1.default(this.url, this.headers, id, this.fetch); + } + /** + * + * @alpha + * + * Access vector storage operations. + * + * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. + * + * @category Vector Buckets + * @returns A StorageVectorsClient instance configured with the current storage settings. + */ + get vectors() { + return new vectors_1.StorageVectorsClient(this.url + "/vector", { + headers: this.headers, + fetch: this.fetch + }); + } + /** + * + * @alpha + * + * Access analytics storage operations using Iceberg tables. + * + * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. + * + * @category Analytics Buckets + * @returns A StorageAnalyticsClient instance configured with the current storage settings. + */ + get analytics() { + return new StorageAnalyticsClient_1.default(this.url + "/iceberg", this.headers, this.fetch); + } + }; + exports.StorageClient = StorageClient; + } +}); + +// node_modules/@supabase/storage-js/dist/main/lib/types.js +var require_types2 = __commonJS({ + "node_modules/@supabase/storage-js/dist/main/lib/types.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + } +}); + +// node_modules/@supabase/storage-js/dist/main/index.js +var require_main3 = __commonJS({ + "node_modules/@supabase/storage-js/dist/main/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.StorageAnalyticsClient = exports.StorageClient = void 0; + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var StorageClient_1 = require_StorageClient(); + Object.defineProperty(exports, "StorageClient", { enumerable: true, get: function() { + return StorageClient_1.StorageClient; + } }); + var StorageAnalyticsClient_1 = require_StorageAnalyticsClient(); + Object.defineProperty(exports, "StorageAnalyticsClient", { enumerable: true, get: function() { + return tslib_1.__importDefault(StorageAnalyticsClient_1).default; + } }); + tslib_1.__exportStar(require_types2(), exports); + tslib_1.__exportStar(require_errors(), exports); + tslib_1.__exportStar(require_vectors(), exports); + } +}); + +// node_modules/@supabase/supabase-js/dist/main/lib/version.js +var require_version3 = __commonJS({ + "node_modules/@supabase/supabase-js/dist/main/lib/version.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.version = void 0; + exports.version = "2.87.1"; + } +}); + +// node_modules/@supabase/supabase-js/dist/main/lib/constants.js +var require_constants5 = __commonJS({ + "node_modules/@supabase/supabase-js/dist/main/lib/constants.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DEFAULT_REALTIME_OPTIONS = exports.DEFAULT_AUTH_OPTIONS = exports.DEFAULT_DB_OPTIONS = exports.DEFAULT_GLOBAL_OPTIONS = exports.DEFAULT_HEADERS = void 0; + var version_1 = require_version3(); + var JS_ENV = ""; + if (typeof Deno !== "undefined") { + JS_ENV = "deno"; + } else if (typeof document !== "undefined") { + JS_ENV = "web"; + } else if (typeof navigator !== "undefined" && navigator.product === "ReactNative") { + JS_ENV = "react-native"; + } else { + JS_ENV = "node"; + } + exports.DEFAULT_HEADERS = { "X-Client-Info": `supabase-js-${JS_ENV}/${version_1.version}` }; + exports.DEFAULT_GLOBAL_OPTIONS = { + headers: exports.DEFAULT_HEADERS + }; + exports.DEFAULT_DB_OPTIONS = { + schema: "public" + }; + exports.DEFAULT_AUTH_OPTIONS = { + autoRefreshToken: true, + persistSession: true, + detectSessionInUrl: true, + flowType: "implicit" + }; + exports.DEFAULT_REALTIME_OPTIONS = {}; + } +}); + +// node_modules/@supabase/supabase-js/dist/main/lib/fetch.js +var require_fetch3 = __commonJS({ + "node_modules/@supabase/supabase-js/dist/main/lib/fetch.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.fetchWithAuth = exports.resolveHeadersConstructor = exports.resolveFetch = void 0; + var resolveFetch = (customFetch) => { + if (customFetch) { + return (...args) => customFetch(...args); + } + return (...args) => fetch(...args); + }; + exports.resolveFetch = resolveFetch; + var resolveHeadersConstructor = () => { + return Headers; + }; + exports.resolveHeadersConstructor = resolveHeadersConstructor; + var fetchWithAuth = (supabaseKey, getAccessToken, customFetch) => { + const fetch2 = (0, exports.resolveFetch)(customFetch); + const HeadersConstructor = (0, exports.resolveHeadersConstructor)(); + return async (input, init) => { + var _a2; + const accessToken = (_a2 = await getAccessToken()) !== null && _a2 !== void 0 ? _a2 : supabaseKey; + let headers = new HeadersConstructor(init === null || init === void 0 ? void 0 : init.headers); + if (!headers.has("apikey")) { + headers.set("apikey", supabaseKey); + } + if (!headers.has("Authorization")) { + headers.set("Authorization", `Bearer ${accessToken}`); + } + return fetch2(input, Object.assign(Object.assign({}, init), { headers })); + }; + }; + exports.fetchWithAuth = fetchWithAuth; + } +}); + +// node_modules/@supabase/supabase-js/dist/main/lib/helpers.js +var require_helpers3 = __commonJS({ + "node_modules/@supabase/supabase-js/dist/main/lib/helpers.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.isBrowser = void 0; + exports.uuid = uuid; + exports.ensureTrailingSlash = ensureTrailingSlash; + exports.applySettingDefaults = applySettingDefaults; + exports.validateSupabaseUrl = validateSupabaseUrl; + function uuid() { + return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) { + var r = Math.random() * 16 | 0, v = c == "x" ? r : r & 3 | 8; + return v.toString(16); + }); + } + function ensureTrailingSlash(url) { + return url.endsWith("/") ? url : url + "/"; + } + var isBrowser3 = () => typeof window !== "undefined"; + exports.isBrowser = isBrowser3; + function applySettingDefaults(options, defaults) { + var _a2, _b; + const { db: dbOptions, auth: authOptions, realtime: realtimeOptions, global: globalOptions } = options; + const { db: DEFAULT_DB_OPTIONS, auth: DEFAULT_AUTH_OPTIONS, realtime: DEFAULT_REALTIME_OPTIONS, global: DEFAULT_GLOBAL_OPTIONS } = defaults; + const result = { + db: Object.assign(Object.assign({}, DEFAULT_DB_OPTIONS), dbOptions), + auth: Object.assign(Object.assign({}, DEFAULT_AUTH_OPTIONS), authOptions), + realtime: Object.assign(Object.assign({}, DEFAULT_REALTIME_OPTIONS), realtimeOptions), + storage: {}, + global: Object.assign(Object.assign(Object.assign({}, DEFAULT_GLOBAL_OPTIONS), globalOptions), { headers: Object.assign(Object.assign({}, (_a2 = DEFAULT_GLOBAL_OPTIONS === null || DEFAULT_GLOBAL_OPTIONS === void 0 ? void 0 : DEFAULT_GLOBAL_OPTIONS.headers) !== null && _a2 !== void 0 ? _a2 : {}), (_b = globalOptions === null || globalOptions === void 0 ? void 0 : globalOptions.headers) !== null && _b !== void 0 ? _b : {}) }), + accessToken: async () => "" + }; + if (options.accessToken) { + result.accessToken = options.accessToken; + } else { + delete result.accessToken; + } + return result; + } + function validateSupabaseUrl(supabaseUrl) { + const trimmedUrl = supabaseUrl === null || supabaseUrl === void 0 ? void 0 : supabaseUrl.trim(); + if (!trimmedUrl) { + throw new Error("supabaseUrl is required."); + } + if (!trimmedUrl.match(/^https?:\/\//i)) { + throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL."); + } + try { + return new URL(ensureTrailingSlash(trimmedUrl)); + } catch (_a2) { + throw Error("Invalid supabaseUrl: Provided URL is malformed."); + } + } + } +}); + +// node_modules/@supabase/auth-js/dist/main/lib/version.js +var require_version4 = __commonJS({ + "node_modules/@supabase/auth-js/dist/main/lib/version.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.version = void 0; + exports.version = "2.87.1"; + } +}); + +// node_modules/@supabase/auth-js/dist/main/lib/constants.js +var require_constants6 = __commonJS({ + "node_modules/@supabase/auth-js/dist/main/lib/constants.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.JWKS_TTL = exports.BASE64URL_REGEX = exports.API_VERSIONS = exports.API_VERSION_HEADER_NAME = exports.NETWORK_FAILURE = exports.DEFAULT_HEADERS = exports.AUDIENCE = exports.STORAGE_KEY = exports.GOTRUE_URL = exports.EXPIRY_MARGIN_MS = exports.AUTO_REFRESH_TICK_THRESHOLD = exports.AUTO_REFRESH_TICK_DURATION_MS = void 0; + var version_1 = require_version4(); + exports.AUTO_REFRESH_TICK_DURATION_MS = 30 * 1e3; + exports.AUTO_REFRESH_TICK_THRESHOLD = 3; + exports.EXPIRY_MARGIN_MS = exports.AUTO_REFRESH_TICK_THRESHOLD * exports.AUTO_REFRESH_TICK_DURATION_MS; + exports.GOTRUE_URL = "http://localhost:9999"; + exports.STORAGE_KEY = "supabase.auth.token"; + exports.AUDIENCE = ""; + exports.DEFAULT_HEADERS = { "X-Client-Info": `gotrue-js/${version_1.version}` }; + exports.NETWORK_FAILURE = { + MAX_RETRIES: 10, + RETRY_INTERVAL: 2 + // in deciseconds + }; + exports.API_VERSION_HEADER_NAME = "X-Supabase-Api-Version"; + exports.API_VERSIONS = { + "2024-01-01": { + timestamp: Date.parse("2024-01-01T00:00:00.0Z"), + name: "2024-01-01" + } + }; + exports.BASE64URL_REGEX = /^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i; + exports.JWKS_TTL = 10 * 60 * 1e3; + } +}); + +// node_modules/@supabase/auth-js/dist/main/lib/errors.js +var require_errors3 = __commonJS({ + "node_modules/@supabase/auth-js/dist/main/lib/errors.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AuthInvalidJwtError = exports.AuthWeakPasswordError = exports.AuthRetryableFetchError = exports.AuthPKCEGrantCodeExchangeError = exports.AuthImplicitGrantRedirectError = exports.AuthInvalidCredentialsError = exports.AuthInvalidTokenResponseError = exports.AuthSessionMissingError = exports.CustomAuthError = exports.AuthUnknownError = exports.AuthApiError = exports.AuthError = void 0; + exports.isAuthError = isAuthError2; + exports.isAuthApiError = isAuthApiError2; + exports.isAuthSessionMissingError = isAuthSessionMissingError2; + exports.isAuthImplicitGrantRedirectError = isAuthImplicitGrantRedirectError2; + exports.isAuthRetryableFetchError = isAuthRetryableFetchError2; + exports.isAuthWeakPasswordError = isAuthWeakPasswordError2; + var AuthError3 = class extends Error { + constructor(message, status, code) { + super(message); + this.__isAuthError = true; + this.name = "AuthError"; + this.status = status; + this.code = code; + } + }; + exports.AuthError = AuthError3; + function isAuthError2(error) { + return typeof error === "object" && error !== null && "__isAuthError" in error; + } + var AuthApiError2 = class extends AuthError3 { + constructor(message, status, code) { + super(message, status, code); + this.name = "AuthApiError"; + this.status = status; + this.code = code; + } + }; + exports.AuthApiError = AuthApiError2; + function isAuthApiError2(error) { + return isAuthError2(error) && error.name === "AuthApiError"; + } + var AuthUnknownError2 = class extends AuthError3 { + constructor(message, originalError) { + super(message); + this.name = "AuthUnknownError"; + this.originalError = originalError; + } + }; + exports.AuthUnknownError = AuthUnknownError2; + var CustomAuthError2 = class extends AuthError3 { + constructor(message, name, status, code) { + super(message, status, code); + this.name = name; + this.status = status; + } + }; + exports.CustomAuthError = CustomAuthError2; + var AuthSessionMissingError2 = class extends CustomAuthError2 { + constructor() { + super("Auth session missing!", "AuthSessionMissingError", 400, void 0); + } + }; + exports.AuthSessionMissingError = AuthSessionMissingError2; + function isAuthSessionMissingError2(error) { + return isAuthError2(error) && error.name === "AuthSessionMissingError"; + } + var AuthInvalidTokenResponseError2 = class extends CustomAuthError2 { + constructor() { + super("Auth session or user missing", "AuthInvalidTokenResponseError", 500, void 0); + } + }; + exports.AuthInvalidTokenResponseError = AuthInvalidTokenResponseError2; + var AuthInvalidCredentialsError2 = class extends CustomAuthError2 { + constructor(message) { + super(message, "AuthInvalidCredentialsError", 400, void 0); + } + }; + exports.AuthInvalidCredentialsError = AuthInvalidCredentialsError2; + var AuthImplicitGrantRedirectError2 = class extends CustomAuthError2 { + constructor(message, details = null) { + super(message, "AuthImplicitGrantRedirectError", 500, void 0); + this.details = null; + this.details = details; + } + toJSON() { + return { + name: this.name, + message: this.message, + status: this.status, + details: this.details + }; + } + }; + exports.AuthImplicitGrantRedirectError = AuthImplicitGrantRedirectError2; + function isAuthImplicitGrantRedirectError2(error) { + return isAuthError2(error) && error.name === "AuthImplicitGrantRedirectError"; + } + var AuthPKCEGrantCodeExchangeError2 = class extends CustomAuthError2 { + constructor(message, details = null) { + super(message, "AuthPKCEGrantCodeExchangeError", 500, void 0); + this.details = null; + this.details = details; + } + toJSON() { + return { + name: this.name, + message: this.message, + status: this.status, + details: this.details + }; + } + }; + exports.AuthPKCEGrantCodeExchangeError = AuthPKCEGrantCodeExchangeError2; + var AuthRetryableFetchError2 = class extends CustomAuthError2 { + constructor(message, status) { + super(message, "AuthRetryableFetchError", status, void 0); + } + }; + exports.AuthRetryableFetchError = AuthRetryableFetchError2; + function isAuthRetryableFetchError2(error) { + return isAuthError2(error) && error.name === "AuthRetryableFetchError"; + } + var AuthWeakPasswordError2 = class extends CustomAuthError2 { + constructor(message, status, reasons) { + super(message, "AuthWeakPasswordError", status, "weak_password"); + this.reasons = reasons; + } + }; + exports.AuthWeakPasswordError = AuthWeakPasswordError2; + function isAuthWeakPasswordError2(error) { + return isAuthError2(error) && error.name === "AuthWeakPasswordError"; + } + var AuthInvalidJwtError2 = class extends CustomAuthError2 { + constructor(message) { + super(message, "AuthInvalidJwtError", 400, "invalid_jwt"); + } + }; + exports.AuthInvalidJwtError = AuthInvalidJwtError2; + } +}); + +// node_modules/@supabase/auth-js/dist/main/lib/base64url.js +var require_base64url = __commonJS({ + "node_modules/@supabase/auth-js/dist/main/lib/base64url.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.byteToBase64URL = byteToBase64URL; + exports.byteFromBase64URL = byteFromBase64URL; + exports.stringToBase64URL = stringToBase64URL; + exports.stringFromBase64URL = stringFromBase64URL; + exports.codepointToUTF8 = codepointToUTF8; + exports.stringToUTF8 = stringToUTF8; + exports.stringFromUTF8 = stringFromUTF8; + exports.base64UrlToUint8Array = base64UrlToUint8Array; + exports.stringToUint8Array = stringToUint8Array; + exports.bytesToBase64URL = bytesToBase64URL; + var TO_BASE64URL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""); + var IGNORE_BASE64URL = " \n\r=".split(""); + var FROM_BASE64URL = (() => { + const charMap = new Array(128); + for (let i = 0; i < charMap.length; i += 1) { + charMap[i] = -1; + } + for (let i = 0; i < IGNORE_BASE64URL.length; i += 1) { + charMap[IGNORE_BASE64URL[i].charCodeAt(0)] = -2; + } + for (let i = 0; i < TO_BASE64URL.length; i += 1) { + charMap[TO_BASE64URL[i].charCodeAt(0)] = i; + } + return charMap; + })(); + function byteToBase64URL(byte, state, emit) { + if (byte !== null) { + state.queue = state.queue << 8 | byte; + state.queuedBits += 8; + while (state.queuedBits >= 6) { + const pos = state.queue >> state.queuedBits - 6 & 63; + emit(TO_BASE64URL[pos]); + state.queuedBits -= 6; + } + } else if (state.queuedBits > 0) { + state.queue = state.queue << 6 - state.queuedBits; + state.queuedBits = 6; + while (state.queuedBits >= 6) { + const pos = state.queue >> state.queuedBits - 6 & 63; + emit(TO_BASE64URL[pos]); + state.queuedBits -= 6; + } + } + } + function byteFromBase64URL(charCode, state, emit) { + const bits = FROM_BASE64URL[charCode]; + if (bits > -1) { + state.queue = state.queue << 6 | bits; + state.queuedBits += 6; + while (state.queuedBits >= 8) { + emit(state.queue >> state.queuedBits - 8 & 255); + state.queuedBits -= 8; + } + } else if (bits === -2) { + return; + } else { + throw new Error(`Invalid Base64-URL character "${String.fromCharCode(charCode)}"`); + } + } + function stringToBase64URL(str) { + const base642 = []; + const emitter = (char) => { + base642.push(char); + }; + const state = { queue: 0, queuedBits: 0 }; + stringToUTF8(str, (byte) => { + byteToBase64URL(byte, state, emitter); + }); + byteToBase64URL(null, state, emitter); + return base642.join(""); + } + function stringFromBase64URL(str) { + const conv = []; + const utf8Emit = (codepoint) => { + conv.push(String.fromCodePoint(codepoint)); + }; + const utf8State = { + utf8seq: 0, + codepoint: 0 + }; + const b64State = { queue: 0, queuedBits: 0 }; + const byteEmit = (byte) => { + stringFromUTF8(byte, utf8State, utf8Emit); + }; + for (let i = 0; i < str.length; i += 1) { + byteFromBase64URL(str.charCodeAt(i), b64State, byteEmit); + } + return conv.join(""); + } + function codepointToUTF8(codepoint, emit) { + if (codepoint <= 127) { + emit(codepoint); + return; + } else if (codepoint <= 2047) { + emit(192 | codepoint >> 6); + emit(128 | codepoint & 63); + return; + } else if (codepoint <= 65535) { + emit(224 | codepoint >> 12); + emit(128 | codepoint >> 6 & 63); + emit(128 | codepoint & 63); + return; + } else if (codepoint <= 1114111) { + emit(240 | codepoint >> 18); + emit(128 | codepoint >> 12 & 63); + emit(128 | codepoint >> 6 & 63); + emit(128 | codepoint & 63); + return; + } + throw new Error(`Unrecognized Unicode codepoint: ${codepoint.toString(16)}`); + } + function stringToUTF8(str, emit) { + for (let i = 0; i < str.length; i += 1) { + let codepoint = str.charCodeAt(i); + if (codepoint > 55295 && codepoint <= 56319) { + const highSurrogate = (codepoint - 55296) * 1024 & 65535; + const lowSurrogate = str.charCodeAt(i + 1) - 56320 & 65535; + codepoint = (lowSurrogate | highSurrogate) + 65536; + i += 1; + } + codepointToUTF8(codepoint, emit); + } + } + function stringFromUTF8(byte, state, emit) { + if (state.utf8seq === 0) { + if (byte <= 127) { + emit(byte); + return; + } + for (let leadingBit = 1; leadingBit < 6; leadingBit += 1) { + if ((byte >> 7 - leadingBit & 1) === 0) { + state.utf8seq = leadingBit; + break; + } + } + if (state.utf8seq === 2) { + state.codepoint = byte & 31; + } else if (state.utf8seq === 3) { + state.codepoint = byte & 15; + } else if (state.utf8seq === 4) { + state.codepoint = byte & 7; + } else { + throw new Error("Invalid UTF-8 sequence"); + } + state.utf8seq -= 1; + } else if (state.utf8seq > 0) { + if (byte <= 127) { + throw new Error("Invalid UTF-8 sequence"); + } + state.codepoint = state.codepoint << 6 | byte & 63; + state.utf8seq -= 1; + if (state.utf8seq === 0) { + emit(state.codepoint); + } + } + } + function base64UrlToUint8Array(str) { + const result = []; + const state = { queue: 0, queuedBits: 0 }; + const onByte = (byte) => { + result.push(byte); + }; + for (let i = 0; i < str.length; i += 1) { + byteFromBase64URL(str.charCodeAt(i), state, onByte); + } + return new Uint8Array(result); + } + function stringToUint8Array(str) { + const result = []; + stringToUTF8(str, (byte) => result.push(byte)); + return new Uint8Array(result); + } + function bytesToBase64URL(bytes) { + const result = []; + const state = { queue: 0, queuedBits: 0 }; + const onChar = (char) => { + result.push(char); + }; + bytes.forEach((byte) => byteToBase64URL(byte, state, onChar)); + byteToBase64URL(null, state, onChar); + return result.join(""); + } + } +}); + +// node_modules/@supabase/auth-js/dist/main/lib/helpers.js +var require_helpers4 = __commonJS({ + "node_modules/@supabase/auth-js/dist/main/lib/helpers.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Deferred = exports.removeItemAsync = exports.getItemAsync = exports.setItemAsync = exports.looksLikeFetchResponse = exports.resolveFetch = exports.supportsLocalStorage = exports.isBrowser = void 0; + exports.expiresAt = expiresAt; + exports.generateCallbackId = generateCallbackId; + exports.parseParametersFromURL = parseParametersFromURL; + exports.decodeJWT = decodeJWT; + exports.sleep = sleep; + exports.retryable = retryable; + exports.generatePKCEVerifier = generatePKCEVerifier; + exports.generatePKCEChallenge = generatePKCEChallenge; + exports.getCodeChallengeAndMethod = getCodeChallengeAndMethod; + exports.parseResponseAPIVersion = parseResponseAPIVersion; + exports.validateExp = validateExp; + exports.getAlgorithm = getAlgorithm; + exports.validateUUID = validateUUID; + exports.userNotAvailableProxy = userNotAvailableProxy; + exports.insecureUserWarningProxy = insecureUserWarningProxy; + exports.deepClone = deepClone2; + var constants_1 = require_constants6(); + var errors_1 = require_errors3(); + var base64url_1 = require_base64url(); + function expiresAt(expiresIn) { + const timeNow = Math.round(Date.now() / 1e3); + return timeNow + expiresIn; + } + function generateCallbackId() { + return Symbol("auth-callback"); + } + var isBrowser3 = () => typeof window !== "undefined" && typeof document !== "undefined"; + exports.isBrowser = isBrowser3; + var localStorageWriteTests = { + tested: false, + writable: false + }; + var supportsLocalStorage = () => { + if (!(0, exports.isBrowser)()) { + return false; + } + try { + if (typeof globalThis.localStorage !== "object") { + return false; + } + } catch (e) { + return false; + } + if (localStorageWriteTests.tested) { + return localStorageWriteTests.writable; + } + const randomKey = `lswt-${Math.random()}${Math.random()}`; + try { + globalThis.localStorage.setItem(randomKey, randomKey); + globalThis.localStorage.removeItem(randomKey); + localStorageWriteTests.tested = true; + localStorageWriteTests.writable = true; + } catch (e) { + localStorageWriteTests.tested = true; + localStorageWriteTests.writable = false; + } + return localStorageWriteTests.writable; + }; + exports.supportsLocalStorage = supportsLocalStorage; + function parseParametersFromURL(href) { + const result = {}; + const url = new URL(href); + if (url.hash && url.hash[0] === "#") { + try { + const hashSearchParams = new URLSearchParams(url.hash.substring(1)); + hashSearchParams.forEach((value, key) => { + result[key] = value; + }); + } catch (e) { + } + } + url.searchParams.forEach((value, key) => { + result[key] = value; + }); + return result; + } + var resolveFetch = (customFetch) => { + if (customFetch) { + return (...args) => customFetch(...args); + } + return (...args) => fetch(...args); + }; + exports.resolveFetch = resolveFetch; + var looksLikeFetchResponse = (maybeResponse) => { + return typeof maybeResponse === "object" && maybeResponse !== null && "status" in maybeResponse && "ok" in maybeResponse && "json" in maybeResponse && typeof maybeResponse.json === "function"; + }; + exports.looksLikeFetchResponse = looksLikeFetchResponse; + var setItemAsync = async (storage, key, data) => { + await storage.setItem(key, JSON.stringify(data)); + }; + exports.setItemAsync = setItemAsync; + var getItemAsync = async (storage, key) => { + const value = await storage.getItem(key); + if (!value) { + return null; + } + try { + return JSON.parse(value); + } catch (_a2) { + return value; + } + }; + exports.getItemAsync = getItemAsync; + var removeItemAsync = async (storage, key) => { + await storage.removeItem(key); + }; + exports.removeItemAsync = removeItemAsync; + var Deferred = class _Deferred { + constructor() { + ; + this.promise = new _Deferred.promiseConstructor((res, rej) => { + ; + this.resolve = res; + this.reject = rej; + }); + } + }; + exports.Deferred = Deferred; + Deferred.promiseConstructor = Promise; + function decodeJWT(token) { + const parts = token.split("."); + if (parts.length !== 3) { + throw new errors_1.AuthInvalidJwtError("Invalid JWT structure"); + } + for (let i = 0; i < parts.length; i++) { + if (!constants_1.BASE64URL_REGEX.test(parts[i])) { + throw new errors_1.AuthInvalidJwtError("JWT not in base64url format"); + } + } + const data = { + // using base64url lib + header: JSON.parse((0, base64url_1.stringFromBase64URL)(parts[0])), + payload: JSON.parse((0, base64url_1.stringFromBase64URL)(parts[1])), + signature: (0, base64url_1.base64UrlToUint8Array)(parts[2]), + raw: { + header: parts[0], + payload: parts[1] + } + }; + return data; + } + async function sleep(time2) { + return await new Promise((accept) => { + setTimeout(() => accept(null), time2); + }); + } + function retryable(fn, isRetryable) { + const promise = new Promise((accept, reject) => { + ; + (async () => { + for (let attempt = 0; attempt < Infinity; attempt++) { + try { + const result = await fn(attempt); + if (!isRetryable(attempt, null, result)) { + accept(result); + return; + } + } catch (e) { + if (!isRetryable(attempt, e)) { + reject(e); + return; + } + } + } + })(); + }); + return promise; + } + function dec2hex(dec) { + return ("0" + dec.toString(16)).substr(-2); + } + function generatePKCEVerifier() { + const verifierLength = 56; + const array = new Uint32Array(verifierLength); + if (typeof crypto === "undefined") { + const charSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"; + const charSetLen = charSet.length; + let verifier = ""; + for (let i = 0; i < verifierLength; i++) { + verifier += charSet.charAt(Math.floor(Math.random() * charSetLen)); + } + return verifier; + } + crypto.getRandomValues(array); + return Array.from(array, dec2hex).join(""); + } + async function sha2562(randomString2) { + const encoder2 = new TextEncoder(); + const encodedData = encoder2.encode(randomString2); + const hash = await crypto.subtle.digest("SHA-256", encodedData); + const bytes = new Uint8Array(hash); + return Array.from(bytes).map((c) => String.fromCharCode(c)).join(""); + } + async function generatePKCEChallenge(verifier) { + const hasCryptoSupport = typeof crypto !== "undefined" && typeof crypto.subtle !== "undefined" && typeof TextEncoder !== "undefined"; + if (!hasCryptoSupport) { + console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."); + return verifier; + } + const hashed = await sha2562(verifier); + return btoa(hashed).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); + } + async function getCodeChallengeAndMethod(storage, storageKey, isPasswordRecovery = false) { + const codeVerifier = generatePKCEVerifier(); + let storedCodeVerifier = codeVerifier; + if (isPasswordRecovery) { + storedCodeVerifier += "/PASSWORD_RECOVERY"; + } + await (0, exports.setItemAsync)(storage, `${storageKey}-code-verifier`, storedCodeVerifier); + const codeChallenge = await generatePKCEChallenge(codeVerifier); + const codeChallengeMethod = codeVerifier === codeChallenge ? "plain" : "s256"; + return [codeChallenge, codeChallengeMethod]; + } + var API_VERSION_REGEX = /^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i; + function parseResponseAPIVersion(response) { + const apiVersion = response.headers.get(constants_1.API_VERSION_HEADER_NAME); + if (!apiVersion) { + return null; + } + if (!apiVersion.match(API_VERSION_REGEX)) { + return null; + } + try { + const date3 = /* @__PURE__ */ new Date(`${apiVersion}T00:00:00.0Z`); + return date3; + } catch (e) { + return null; + } + } + function validateExp(exp) { + if (!exp) { + throw new Error("Missing exp claim"); + } + const timeNow = Math.floor(Date.now() / 1e3); + if (exp <= timeNow) { + throw new Error("JWT has expired"); + } + } + function getAlgorithm(alg) { + switch (alg) { + case "RS256": + return { + name: "RSASSA-PKCS1-v1_5", + hash: { name: "SHA-256" } + }; + case "ES256": + return { + name: "ECDSA", + namedCurve: "P-256", + hash: { name: "SHA-256" } + }; + default: + throw new Error("Invalid alg claim"); + } + } + var UUID_REGEX2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/; + function validateUUID(str) { + if (!UUID_REGEX2.test(str)) { + throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not"); + } + } + function userNotAvailableProxy() { + const proxyTarget = {}; + return new Proxy(proxyTarget, { + get: (target, prop) => { + if (prop === "__isUserNotAvailableProxy") { + return true; + } + if (typeof prop === "symbol") { + const sProp = prop.toString(); + if (sProp === "Symbol(Symbol.toPrimitive)" || sProp === "Symbol(Symbol.toStringTag)" || sProp === "Symbol(util.inspect.custom)") { + return void 0; + } + } + throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${prop}" property of the session object is not supported. Please use getUser() instead.`); + }, + set: (_target, prop) => { + throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${prop}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`); + }, + deleteProperty: (_target, prop) => { + throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${prop}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`); + } + }); + } + function insecureUserWarningProxy(user, suppressWarningRef) { + return new Proxy(user, { + get: (target, prop, receiver) => { + if (prop === "__isInsecureUserWarningProxy") { + return true; + } + if (typeof prop === "symbol") { + const sProp = prop.toString(); + if (sProp === "Symbol(Symbol.toPrimitive)" || sProp === "Symbol(Symbol.toStringTag)" || sProp === "Symbol(util.inspect.custom)" || sProp === "Symbol(nodejs.util.inspect.custom)") { + return Reflect.get(target, prop, receiver); + } + } + if (!suppressWarningRef.value && typeof prop === "string") { + console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."); + suppressWarningRef.value = true; + } + return Reflect.get(target, prop, receiver); + } + }); + } + function deepClone2(obj) { + return JSON.parse(JSON.stringify(obj)); + } + } +}); + +// node_modules/@supabase/auth-js/dist/main/lib/fetch.js +var require_fetch4 = __commonJS({ + "node_modules/@supabase/auth-js/dist/main/lib/fetch.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.handleError = handleError; + exports._request = _request; + exports._sessionResponse = _sessionResponse; + exports._sessionResponsePassword = _sessionResponsePassword; + exports._userResponse = _userResponse; + exports._ssoResponse = _ssoResponse; + exports._generateLinkResponse = _generateLinkResponse; + exports._noResolveJsonResponse = _noResolveJsonResponse; + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var constants_1 = require_constants6(); + var helpers_1 = require_helpers4(); + var errors_1 = require_errors3(); + var _getErrorMessage = (err) => err.msg || err.message || err.error_description || err.error || JSON.stringify(err); + var NETWORK_ERROR_CODES = [502, 503, 504]; + async function handleError(error) { + var _a2; + if (!(0, helpers_1.looksLikeFetchResponse)(error)) { + throw new errors_1.AuthRetryableFetchError(_getErrorMessage(error), 0); + } + if (NETWORK_ERROR_CODES.includes(error.status)) { + throw new errors_1.AuthRetryableFetchError(_getErrorMessage(error), error.status); + } + let data; + try { + data = await error.json(); + } catch (e) { + throw new errors_1.AuthUnknownError(_getErrorMessage(e), e); + } + let errorCode = void 0; + const responseAPIVersion = (0, helpers_1.parseResponseAPIVersion)(error); + if (responseAPIVersion && responseAPIVersion.getTime() >= constants_1.API_VERSIONS["2024-01-01"].timestamp && typeof data === "object" && data && typeof data.code === "string") { + errorCode = data.code; + } else if (typeof data === "object" && data && typeof data.error_code === "string") { + errorCode = data.error_code; + } + if (!errorCode) { + if (typeof data === "object" && data && typeof data.weak_password === "object" && data.weak_password && Array.isArray(data.weak_password.reasons) && data.weak_password.reasons.length && data.weak_password.reasons.reduce((a, i) => a && typeof i === "string", true)) { + throw new errors_1.AuthWeakPasswordError(_getErrorMessage(data), error.status, data.weak_password.reasons); + } + } else if (errorCode === "weak_password") { + throw new errors_1.AuthWeakPasswordError(_getErrorMessage(data), error.status, ((_a2 = data.weak_password) === null || _a2 === void 0 ? void 0 : _a2.reasons) || []); + } else if (errorCode === "session_not_found") { + throw new errors_1.AuthSessionMissingError(); + } + throw new errors_1.AuthApiError(_getErrorMessage(data), error.status || 500, errorCode); + } + var _getRequestParams = (method, options, parameters, body) => { + const params = { method, headers: (options === null || options === void 0 ? void 0 : options.headers) || {} }; + if (method === "GET") { + return params; + } + params.headers = Object.assign({ "Content-Type": "application/json;charset=UTF-8" }, options === null || options === void 0 ? void 0 : options.headers); + params.body = JSON.stringify(body); + return Object.assign(Object.assign({}, params), parameters); + }; + async function _request(fetcher, method, url, options) { + var _a2; + const headers = Object.assign({}, options === null || options === void 0 ? void 0 : options.headers); + if (!headers[constants_1.API_VERSION_HEADER_NAME]) { + headers[constants_1.API_VERSION_HEADER_NAME] = constants_1.API_VERSIONS["2024-01-01"].name; + } + if (options === null || options === void 0 ? void 0 : options.jwt) { + headers["Authorization"] = `Bearer ${options.jwt}`; + } + const qs = (_a2 = options === null || options === void 0 ? void 0 : options.query) !== null && _a2 !== void 0 ? _a2 : {}; + if (options === null || options === void 0 ? void 0 : options.redirectTo) { + qs["redirect_to"] = options.redirectTo; + } + const queryString = Object.keys(qs).length ? "?" + new URLSearchParams(qs).toString() : ""; + const data = await _handleRequest(fetcher, method, url + queryString, { + headers, + noResolveJson: options === null || options === void 0 ? void 0 : options.noResolveJson + }, {}, options === null || options === void 0 ? void 0 : options.body); + return (options === null || options === void 0 ? void 0 : options.xform) ? options === null || options === void 0 ? void 0 : options.xform(data) : { data: Object.assign({}, data), error: null }; + } + async function _handleRequest(fetcher, method, url, options, parameters, body) { + const requestParams = _getRequestParams(method, options, parameters, body); + let result; + try { + result = await fetcher(url, Object.assign({}, requestParams)); + } catch (e) { + console.error(e); + throw new errors_1.AuthRetryableFetchError(_getErrorMessage(e), 0); + } + if (!result.ok) { + await handleError(result); + } + if (options === null || options === void 0 ? void 0 : options.noResolveJson) { + return result; + } + try { + return await result.json(); + } catch (e) { + await handleError(e); + } + } + function _sessionResponse(data) { + var _a2; + let session = null; + if (hasSession(data)) { + session = Object.assign({}, data); + if (!data.expires_at) { + session.expires_at = (0, helpers_1.expiresAt)(data.expires_in); + } + } + const user = (_a2 = data.user) !== null && _a2 !== void 0 ? _a2 : data; + return { data: { session, user }, error: null }; + } + function _sessionResponsePassword(data) { + const response = _sessionResponse(data); + if (!response.error && data.weak_password && typeof data.weak_password === "object" && Array.isArray(data.weak_password.reasons) && data.weak_password.reasons.length && data.weak_password.message && typeof data.weak_password.message === "string" && data.weak_password.reasons.reduce((a, i) => a && typeof i === "string", true)) { + response.data.weak_password = data.weak_password; + } + return response; + } + function _userResponse(data) { + var _a2; + const user = (_a2 = data.user) !== null && _a2 !== void 0 ? _a2 : data; + return { data: { user }, error: null }; + } + function _ssoResponse(data) { + return { data, error: null }; + } + function _generateLinkResponse(data) { + const { action_link, email_otp, hashed_token, redirect_to, verification_type } = data, rest = tslib_1.__rest(data, ["action_link", "email_otp", "hashed_token", "redirect_to", "verification_type"]); + const properties = { + action_link, + email_otp, + hashed_token, + redirect_to, + verification_type + }; + const user = Object.assign({}, rest); + return { + data: { + properties, + user + }, + error: null + }; + } + function _noResolveJsonResponse(data) { + return data; + } + function hasSession(data) { + return data.access_token && data.refresh_token && data.expires_in; + } + } +}); + +// node_modules/@supabase/auth-js/dist/main/lib/types.js +var require_types3 = __commonJS({ + "node_modules/@supabase/auth-js/dist/main/lib/types.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SIGN_OUT_SCOPES = void 0; + exports.SIGN_OUT_SCOPES = ["global", "local", "others"]; + } +}); + +// node_modules/@supabase/auth-js/dist/main/GoTrueAdminApi.js +var require_GoTrueAdminApi = __commonJS({ + "node_modules/@supabase/auth-js/dist/main/GoTrueAdminApi.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var fetch_1 = require_fetch4(); + var helpers_1 = require_helpers4(); + var types_1 = require_types3(); + var errors_1 = require_errors3(); + var GoTrueAdminApi2 = class { + /** + * Creates an admin API client that can be used to manage users and OAuth clients. + * + * @example + * ```ts + * import { GoTrueAdminApi } from '@supabase/auth-js' + * + * const admin = new GoTrueAdminApi({ + * url: 'https://xyzcompany.supabase.co/auth/v1', + * headers: { Authorization: `Bearer ${process.env.SUPABASE_SERVICE_ROLE_KEY}` }, + * }) + * ``` + */ + constructor({ url = "", headers = {}, fetch: fetch2 }) { + this.url = url; + this.headers = headers; + this.fetch = (0, helpers_1.resolveFetch)(fetch2); + this.mfa = { + listFactors: this._listFactors.bind(this), + deleteFactor: this._deleteFactor.bind(this) + }; + this.oauth = { + listClients: this._listOAuthClients.bind(this), + createClient: this._createOAuthClient.bind(this), + getClient: this._getOAuthClient.bind(this), + updateClient: this._updateOAuthClient.bind(this), + deleteClient: this._deleteOAuthClient.bind(this), + regenerateClientSecret: this._regenerateOAuthClientSecret.bind(this) + }; + } + /** + * Removes a logged-in session. + * @param jwt A valid, logged-in JWT. + * @param scope The logout sope. + */ + async signOut(jwt, scope = types_1.SIGN_OUT_SCOPES[0]) { + if (types_1.SIGN_OUT_SCOPES.indexOf(scope) < 0) { + throw new Error(`@supabase/auth-js: Parameter scope must be one of ${types_1.SIGN_OUT_SCOPES.join(", ")}`); + } + try { + await (0, fetch_1._request)(this.fetch, "POST", `${this.url}/logout?scope=${scope}`, { + headers: this.headers, + jwt, + noResolveJson: true + }); + return { data: null, error: null }; + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; + } + throw error; + } + } + /** + * Sends an invite link to an email address. + * @param email The email address of the user. + * @param options Additional options to be included when inviting. + */ + async inviteUserByEmail(email, options = {}) { + try { + return await (0, fetch_1._request)(this.fetch, "POST", `${this.url}/invite`, { + body: { email, data: options.data }, + headers: this.headers, + redirectTo: options.redirectTo, + xform: fetch_1._userResponse + }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: { user: null }, error }; + } + throw error; + } + } + /** + * Generates email links and OTPs to be sent via a custom email provider. + * @param email The user's email. + * @param options.password User password. For signup only. + * @param options.data Optional user metadata. For signup only. + * @param options.redirectTo The redirect url which should be appended to the generated link + */ + async generateLink(params) { + try { + const { options } = params, rest = tslib_1.__rest(params, ["options"]); + const body = Object.assign(Object.assign({}, rest), options); + if ("newEmail" in rest) { + body.new_email = rest === null || rest === void 0 ? void 0 : rest.newEmail; + delete body["newEmail"]; + } + return await (0, fetch_1._request)(this.fetch, "POST", `${this.url}/admin/generate_link`, { + body, + headers: this.headers, + xform: fetch_1._generateLinkResponse, + redirectTo: options === null || options === void 0 ? void 0 : options.redirectTo + }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { + data: { + properties: null, + user: null + }, + error + }; + } + throw error; + } + } + // User Admin API + /** + * Creates a new user. + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async createUser(attributes) { + try { + return await (0, fetch_1._request)(this.fetch, "POST", `${this.url}/admin/users`, { + body: attributes, + headers: this.headers, + xform: fetch_1._userResponse + }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: { user: null }, error }; + } + throw error; + } + } + /** + * Get a list of users. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + * @param params An object which supports `page` and `perPage` as numbers, to alter the paginated results. + */ + async listUsers(params) { + var _a2, _b, _c, _d, _e, _f, _g; + try { + const pagination = { nextPage: null, lastPage: 0, total: 0 }; + const response = await (0, fetch_1._request)(this.fetch, "GET", `${this.url}/admin/users`, { + headers: this.headers, + noResolveJson: true, + query: { + page: (_b = (_a2 = params === null || params === void 0 ? void 0 : params.page) === null || _a2 === void 0 ? void 0 : _a2.toString()) !== null && _b !== void 0 ? _b : "", + per_page: (_d = (_c = params === null || params === void 0 ? void 0 : params.perPage) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : "" + }, + xform: fetch_1._noResolveJsonResponse + }); + if (response.error) + throw response.error; + const users = await response.json(); + const total = (_e = response.headers.get("x-total-count")) !== null && _e !== void 0 ? _e : 0; + const links = (_g = (_f = response.headers.get("link")) === null || _f === void 0 ? void 0 : _f.split(",")) !== null && _g !== void 0 ? _g : []; + if (links.length > 0) { + links.forEach((link) => { + const page = parseInt(link.split(";")[0].split("=")[1].substring(0, 1)); + const rel = JSON.parse(link.split(";")[1].split("=")[1]); + pagination[`${rel}Page`] = page; + }); + pagination.total = parseInt(total); + } + return { data: Object.assign(Object.assign({}, users), pagination), error: null }; + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: { users: [] }, error }; + } + throw error; + } + } + /** + * Get user by id. + * + * @param uid The user's unique identifier + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async getUserById(uid) { + (0, helpers_1.validateUUID)(uid); + try { + return await (0, fetch_1._request)(this.fetch, "GET", `${this.url}/admin/users/${uid}`, { + headers: this.headers, + xform: fetch_1._userResponse + }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: { user: null }, error }; + } + throw error; + } + } + /** + * Updates the user data. + * + * @param attributes The data you want to update. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async updateUserById(uid, attributes) { + (0, helpers_1.validateUUID)(uid); + try { + return await (0, fetch_1._request)(this.fetch, "PUT", `${this.url}/admin/users/${uid}`, { + body: attributes, + headers: this.headers, + xform: fetch_1._userResponse + }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: { user: null }, error }; + } + throw error; + } + } + /** + * Delete a user. Requires a `service_role` key. + * + * @param id The user id you want to remove. + * @param shouldSoftDelete If true, then the user will be soft-deleted from the auth schema. Soft deletion allows user identification from the hashed user ID but is not reversible. + * Defaults to false for backward compatibility. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async deleteUser(id, shouldSoftDelete = false) { + (0, helpers_1.validateUUID)(id); + try { + return await (0, fetch_1._request)(this.fetch, "DELETE", `${this.url}/admin/users/${id}`, { + headers: this.headers, + body: { + should_soft_delete: shouldSoftDelete + }, + xform: fetch_1._userResponse + }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: { user: null }, error }; + } + throw error; + } + } + async _listFactors(params) { + (0, helpers_1.validateUUID)(params.userId); + try { + const { data, error } = await (0, fetch_1._request)(this.fetch, "GET", `${this.url}/admin/users/${params.userId}/factors`, { + headers: this.headers, + xform: (factors) => { + return { data: { factors }, error: null }; + } + }); + return { data, error }; + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; + } + throw error; + } + } + async _deleteFactor(params) { + (0, helpers_1.validateUUID)(params.userId); + (0, helpers_1.validateUUID)(params.id); + try { + const data = await (0, fetch_1._request)(this.fetch, "DELETE", `${this.url}/admin/users/${params.userId}/factors/${params.id}`, { + headers: this.headers + }); + return { data, error: null }; + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; + } + throw error; + } + } + /** + * Lists all OAuth clients with optional pagination. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async _listOAuthClients(params) { + var _a2, _b, _c, _d, _e, _f, _g; + try { + const pagination = { nextPage: null, lastPage: 0, total: 0 }; + const response = await (0, fetch_1._request)(this.fetch, "GET", `${this.url}/admin/oauth/clients`, { + headers: this.headers, + noResolveJson: true, + query: { + page: (_b = (_a2 = params === null || params === void 0 ? void 0 : params.page) === null || _a2 === void 0 ? void 0 : _a2.toString()) !== null && _b !== void 0 ? _b : "", + per_page: (_d = (_c = params === null || params === void 0 ? void 0 : params.perPage) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : "" + }, + xform: fetch_1._noResolveJsonResponse + }); + if (response.error) + throw response.error; + const clients = await response.json(); + const total = (_e = response.headers.get("x-total-count")) !== null && _e !== void 0 ? _e : 0; + const links = (_g = (_f = response.headers.get("link")) === null || _f === void 0 ? void 0 : _f.split(",")) !== null && _g !== void 0 ? _g : []; + if (links.length > 0) { + links.forEach((link) => { + const page = parseInt(link.split(";")[0].split("=")[1].substring(0, 1)); + const rel = JSON.parse(link.split(";")[1].split("=")[1]); + pagination[`${rel}Page`] = page; + }); + pagination.total = parseInt(total); + } + return { data: Object.assign(Object.assign({}, clients), pagination), error: null }; + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: { clients: [] }, error }; + } + throw error; + } + } + /** + * Creates a new OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async _createOAuthClient(params) { + try { + return await (0, fetch_1._request)(this.fetch, "POST", `${this.url}/admin/oauth/clients`, { + body: params, + headers: this.headers, + xform: (client2) => { + return { data: client2, error: null }; + } + }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; + } + throw error; + } + } + /** + * Gets details of a specific OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async _getOAuthClient(clientId) { + try { + return await (0, fetch_1._request)(this.fetch, "GET", `${this.url}/admin/oauth/clients/${clientId}`, { + headers: this.headers, + xform: (client2) => { + return { data: client2, error: null }; + } + }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; + } + throw error; + } + } + /** + * Updates an existing OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async _updateOAuthClient(clientId, params) { + try { + return await (0, fetch_1._request)(this.fetch, "PUT", `${this.url}/admin/oauth/clients/${clientId}`, { + body: params, + headers: this.headers, + xform: (client2) => { + return { data: client2, error: null }; + } + }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; + } + throw error; + } + } + /** + * Deletes an OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async _deleteOAuthClient(clientId) { + try { + await (0, fetch_1._request)(this.fetch, "DELETE", `${this.url}/admin/oauth/clients/${clientId}`, { + headers: this.headers, + noResolveJson: true + }); + return { data: null, error: null }; + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; + } + throw error; + } + } + /** + * Regenerates the secret for an OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async _regenerateOAuthClientSecret(clientId) { + try { + return await (0, fetch_1._request)(this.fetch, "POST", `${this.url}/admin/oauth/clients/${clientId}/regenerate_secret`, { + headers: this.headers, + xform: (client2) => { + return { data: client2, error: null }; + } + }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; + } + throw error; + } + } + }; + exports.default = GoTrueAdminApi2; + } +}); + +// node_modules/@supabase/auth-js/dist/main/lib/local-storage.js +var require_local_storage = __commonJS({ + "node_modules/@supabase/auth-js/dist/main/lib/local-storage.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.memoryLocalStorageAdapter = memoryLocalStorageAdapter; + function memoryLocalStorageAdapter(store = {}) { + return { + getItem: (key) => { + return store[key] || null; + }, + setItem: (key, value) => { + store[key] = value; + }, + removeItem: (key) => { + delete store[key]; + } + }; + } + } +}); + +// node_modules/@supabase/auth-js/dist/main/lib/locks.js +var require_locks = __commonJS({ + "node_modules/@supabase/auth-js/dist/main/lib/locks.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ProcessLockAcquireTimeoutError = exports.NavigatorLockAcquireTimeoutError = exports.LockAcquireTimeoutError = exports.internals = void 0; + exports.navigatorLock = navigatorLock2; + exports.processLock = processLock2; + var helpers_1 = require_helpers4(); + exports.internals = { + /** + * @experimental + */ + debug: !!(globalThis && (0, helpers_1.supportsLocalStorage)() && globalThis.localStorage && globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug") === "true") + }; + var LockAcquireTimeoutError = class extends Error { + constructor(message) { + super(message); + this.isAcquireTimeout = true; + } + }; + exports.LockAcquireTimeoutError = LockAcquireTimeoutError; + var NavigatorLockAcquireTimeoutError2 = class extends LockAcquireTimeoutError { + }; + exports.NavigatorLockAcquireTimeoutError = NavigatorLockAcquireTimeoutError2; + var ProcessLockAcquireTimeoutError = class extends LockAcquireTimeoutError { + }; + exports.ProcessLockAcquireTimeoutError = ProcessLockAcquireTimeoutError; + async function navigatorLock2(name, acquireTimeout, fn) { + if (exports.internals.debug) { + console.log("@supabase/gotrue-js: navigatorLock: acquire lock", name, acquireTimeout); + } + const abortController = new globalThis.AbortController(); + if (acquireTimeout > 0) { + setTimeout(() => { + abortController.abort(); + if (exports.internals.debug) { + console.log("@supabase/gotrue-js: navigatorLock acquire timed out", name); + } + }, acquireTimeout); + } + return await Promise.resolve().then(() => globalThis.navigator.locks.request(name, acquireTimeout === 0 ? { + mode: "exclusive", + ifAvailable: true + } : { + mode: "exclusive", + signal: abortController.signal + }, async (lock) => { + if (lock) { + if (exports.internals.debug) { + console.log("@supabase/gotrue-js: navigatorLock: acquired", name, lock.name); + } + try { + return await fn(); + } finally { + if (exports.internals.debug) { + console.log("@supabase/gotrue-js: navigatorLock: released", name, lock.name); + } + } + } else { + if (acquireTimeout === 0) { + if (exports.internals.debug) { + console.log("@supabase/gotrue-js: navigatorLock: not immediately available", name); + } + throw new NavigatorLockAcquireTimeoutError2(`Acquiring an exclusive Navigator LockManager lock "${name}" immediately failed`); + } else { + if (exports.internals.debug) { + try { + const result = await globalThis.navigator.locks.query(); + console.log("@supabase/gotrue-js: Navigator LockManager state", JSON.stringify(result, null, " ")); + } catch (e) { + console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state", e); + } + } + console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"); + return await fn(); + } + } + })); + } + var PROCESS_LOCKS = {}; + async function processLock2(name, acquireTimeout, fn) { + var _a2; + const previousOperation = (_a2 = PROCESS_LOCKS[name]) !== null && _a2 !== void 0 ? _a2 : Promise.resolve(); + const currentOperation = Promise.race([ + previousOperation.catch(() => { + return null; + }), + acquireTimeout >= 0 ? new Promise((_, reject) => { + setTimeout(() => { + reject(new ProcessLockAcquireTimeoutError(`Acquring process lock with name "${name}" timed out`)); + }, acquireTimeout); + }) : null + ].filter((x) => x)).catch((e) => { + if (e && e.isAcquireTimeout) { + throw e; + } + return null; + }).then(async () => { + return await fn(); + }); + PROCESS_LOCKS[name] = currentOperation.catch(async (e) => { + if (e && e.isAcquireTimeout) { + await previousOperation; + return null; + } + throw e; + }); + return await currentOperation; + } + } +}); + +// node_modules/@supabase/auth-js/dist/main/lib/polyfills.js +var require_polyfills = __commonJS({ + "node_modules/@supabase/auth-js/dist/main/lib/polyfills.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.polyfillGlobalThis = polyfillGlobalThis; + function polyfillGlobalThis() { + if (typeof globalThis === "object") + return; + try { + Object.defineProperty(Object.prototype, "__magic__", { + get: function() { + return this; + }, + configurable: true + }); + __magic__.globalThis = __magic__; + delete Object.prototype.__magic__; + } catch (e) { + if (typeof self !== "undefined") { + self.globalThis = self; + } + } + } + } +}); + +// node_modules/@supabase/auth-js/dist/main/lib/web3/ethereum.js +var require_ethereum = __commonJS({ + "node_modules/@supabase/auth-js/dist/main/lib/web3/ethereum.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getAddress = getAddress; + exports.fromHex = fromHex; + exports.toHex = toHex; + exports.createSiweMessage = createSiweMessage; + function getAddress(address) { + if (!/^0x[a-fA-F0-9]{40}$/.test(address)) { + throw new Error(`@supabase/auth-js: Address "${address}" is invalid.`); + } + return address.toLowerCase(); + } + function fromHex(hex) { + return parseInt(hex, 16); + } + function toHex(value) { + const bytes = new TextEncoder().encode(value); + const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join(""); + return "0x" + hex; + } + function createSiweMessage(parameters) { + var _a2; + const { chainId, domain, expirationTime, issuedAt = /* @__PURE__ */ new Date(), nonce, notBefore, requestId, resources, scheme, uri: uri2, version: version2 } = parameters; + { + if (!Number.isInteger(chainId)) + throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${chainId}`); + if (!domain) + throw new Error(`@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.`); + if (nonce && nonce.length < 8) + throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${nonce}`); + if (!uri2) + throw new Error(`@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.`); + if (version2 !== "1") + throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${version2}`); + if ((_a2 = parameters.statement) === null || _a2 === void 0 ? void 0 : _a2.includes("\n")) + throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${parameters.statement}`); + } + const address = getAddress(parameters.address); + const origin = scheme ? `${scheme}://${domain}` : domain; + const statement = parameters.statement ? `${parameters.statement} +` : ""; + const prefix = `${origin} wants you to sign in with your Ethereum account: +${address} + +${statement}`; + let suffix = `URI: ${uri2} +Version: ${version2} +Chain ID: ${chainId}${nonce ? ` +Nonce: ${nonce}` : ""} +Issued At: ${issuedAt.toISOString()}`; + if (expirationTime) + suffix += ` +Expiration Time: ${expirationTime.toISOString()}`; + if (notBefore) + suffix += ` +Not Before: ${notBefore.toISOString()}`; + if (requestId) + suffix += ` +Request ID: ${requestId}`; + if (resources) { + let content = "\nResources:"; + for (const resource of resources) { + if (!resource || typeof resource !== "string") + throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${resource}`); + content += ` +- ${resource}`; + } + suffix += content; + } + return `${prefix} +${suffix}`; + } + } +}); + +// node_modules/@supabase/auth-js/dist/main/lib/webauthn.errors.js +var require_webauthn_errors = __commonJS({ + "node_modules/@supabase/auth-js/dist/main/lib/webauthn.errors.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.WebAuthnUnknownError = exports.WebAuthnError = void 0; + exports.isWebAuthnError = isWebAuthnError; + exports.identifyRegistrationError = identifyRegistrationError; + exports.identifyAuthenticationError = identifyAuthenticationError; + var webauthn_1 = require_webauthn(); + var WebAuthnError = class extends Error { + constructor({ message, code, cause, name }) { + var _a2; + super(message, { cause }); + this.__isWebAuthnError = true; + this.name = (_a2 = name !== null && name !== void 0 ? name : cause instanceof Error ? cause.name : void 0) !== null && _a2 !== void 0 ? _a2 : "Unknown Error"; + this.code = code; + } + }; + exports.WebAuthnError = WebAuthnError; + var WebAuthnUnknownError = class extends WebAuthnError { + constructor(message, originalError) { + super({ + code: "ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY", + cause: originalError, + message + }); + this.name = "WebAuthnUnknownError"; + this.originalError = originalError; + } + }; + exports.WebAuthnUnknownError = WebAuthnUnknownError; + function isWebAuthnError(error) { + return typeof error === "object" && error !== null && "__isWebAuthnError" in error; + } + function identifyRegistrationError({ error, options }) { + var _a2, _b, _c; + const { publicKey } = options; + if (!publicKey) { + throw Error("options was missing required publicKey property"); + } + if (error.name === "AbortError") { + if (options.signal instanceof AbortSignal) { + return new WebAuthnError({ + message: "Registration ceremony was sent an abort signal", + code: "ERROR_CEREMONY_ABORTED", + cause: error + }); + } + } else if (error.name === "ConstraintError") { + if (((_a2 = publicKey.authenticatorSelection) === null || _a2 === void 0 ? void 0 : _a2.requireResidentKey) === true) { + return new WebAuthnError({ + message: "Discoverable credentials were required but no available authenticator supported it", + code: "ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT", + cause: error + }); + } else if ( + // @ts-ignore: `mediation` doesn't yet exist on CredentialCreationOptions but it's possible as of Sept 2024 + options.mediation === "conditional" && ((_b = publicKey.authenticatorSelection) === null || _b === void 0 ? void 0 : _b.userVerification) === "required" + ) { + return new WebAuthnError({ + message: "User verification was required during automatic registration but it could not be performed", + code: "ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE", + cause: error + }); + } else if (((_c = publicKey.authenticatorSelection) === null || _c === void 0 ? void 0 : _c.userVerification) === "required") { + return new WebAuthnError({ + message: "User verification was required but no available authenticator supported it", + code: "ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT", + cause: error + }); + } + } else if (error.name === "InvalidStateError") { + return new WebAuthnError({ + message: "The authenticator was previously registered", + code: "ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED", + cause: error + }); + } else if (error.name === "NotAllowedError") { + return new WebAuthnError({ + message: error.message, + code: "ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY", + cause: error + }); + } else if (error.name === "NotSupportedError") { + const validPubKeyCredParams = publicKey.pubKeyCredParams.filter((param) => param.type === "public-key"); + if (validPubKeyCredParams.length === 0) { + return new WebAuthnError({ + message: 'No entry in pubKeyCredParams was of type "public-key"', + code: "ERROR_MALFORMED_PUBKEYCREDPARAMS", + cause: error + }); + } + return new WebAuthnError({ + message: "No available authenticator supported any of the specified pubKeyCredParams algorithms", + code: "ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG", + cause: error + }); + } else if (error.name === "SecurityError") { + const effectiveDomain = window.location.hostname; + if (!(0, webauthn_1.isValidDomain)(effectiveDomain)) { + return new WebAuthnError({ + message: `${window.location.hostname} is an invalid domain`, + code: "ERROR_INVALID_DOMAIN", + cause: error + }); + } else if (publicKey.rp.id !== effectiveDomain) { + return new WebAuthnError({ + message: `The RP ID "${publicKey.rp.id}" is invalid for this domain`, + code: "ERROR_INVALID_RP_ID", + cause: error + }); + } + } else if (error.name === "TypeError") { + if (publicKey.user.id.byteLength < 1 || publicKey.user.id.byteLength > 64) { + return new WebAuthnError({ + message: "User ID was not between 1 and 64 characters", + code: "ERROR_INVALID_USER_ID_LENGTH", + cause: error + }); + } + } else if (error.name === "UnknownError") { + return new WebAuthnError({ + message: "The authenticator was unable to process the specified options, or could not create a new credential", + code: "ERROR_AUTHENTICATOR_GENERAL_ERROR", + cause: error + }); + } + return new WebAuthnError({ + message: "a Non-Webauthn related error has occurred", + code: "ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY", + cause: error + }); + } + function identifyAuthenticationError({ error, options }) { + const { publicKey } = options; + if (!publicKey) { + throw Error("options was missing required publicKey property"); + } + if (error.name === "AbortError") { + if (options.signal instanceof AbortSignal) { + return new WebAuthnError({ + message: "Authentication ceremony was sent an abort signal", + code: "ERROR_CEREMONY_ABORTED", + cause: error + }); + } + } else if (error.name === "NotAllowedError") { + return new WebAuthnError({ + message: error.message, + code: "ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY", + cause: error + }); + } else if (error.name === "SecurityError") { + const effectiveDomain = window.location.hostname; + if (!(0, webauthn_1.isValidDomain)(effectiveDomain)) { + return new WebAuthnError({ + message: `${window.location.hostname} is an invalid domain`, + code: "ERROR_INVALID_DOMAIN", + cause: error + }); + } else if (publicKey.rpId !== effectiveDomain) { + return new WebAuthnError({ + message: `The RP ID "${publicKey.rpId}" is invalid for this domain`, + code: "ERROR_INVALID_RP_ID", + cause: error + }); + } + } else if (error.name === "UnknownError") { + return new WebAuthnError({ + message: "The authenticator was unable to process the specified options, or could not create a new assertion signature", + code: "ERROR_AUTHENTICATOR_GENERAL_ERROR", + cause: error + }); + } + return new WebAuthnError({ + message: "a Non-Webauthn related error has occurred", + code: "ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY", + cause: error + }); + } + } +}); + +// node_modules/@supabase/auth-js/dist/main/lib/webauthn.js +var require_webauthn = __commonJS({ + "node_modules/@supabase/auth-js/dist/main/lib/webauthn.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.WebAuthnApi = exports.DEFAULT_REQUEST_OPTIONS = exports.DEFAULT_CREATION_OPTIONS = exports.webAuthnAbortService = exports.WebAuthnAbortService = exports.identifyAuthenticationError = exports.identifyRegistrationError = exports.isWebAuthnError = exports.WebAuthnError = void 0; + exports.deserializeCredentialCreationOptions = deserializeCredentialCreationOptions; + exports.deserializeCredentialRequestOptions = deserializeCredentialRequestOptions; + exports.serializeCredentialCreationResponse = serializeCredentialCreationResponse; + exports.serializeCredentialRequestResponse = serializeCredentialRequestResponse; + exports.isValidDomain = isValidDomain; + exports.createCredential = createCredential; + exports.getCredential = getCredential; + exports.mergeCredentialCreationOptions = mergeCredentialCreationOptions; + exports.mergeCredentialRequestOptions = mergeCredentialRequestOptions; + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var base64url_1 = require_base64url(); + var errors_1 = require_errors3(); + var helpers_1 = require_helpers4(); + var webauthn_errors_1 = require_webauthn_errors(); + Object.defineProperty(exports, "identifyAuthenticationError", { enumerable: true, get: function() { + return webauthn_errors_1.identifyAuthenticationError; + } }); + Object.defineProperty(exports, "identifyRegistrationError", { enumerable: true, get: function() { + return webauthn_errors_1.identifyRegistrationError; + } }); + Object.defineProperty(exports, "isWebAuthnError", { enumerable: true, get: function() { + return webauthn_errors_1.isWebAuthnError; + } }); + Object.defineProperty(exports, "WebAuthnError", { enumerable: true, get: function() { + return webauthn_errors_1.WebAuthnError; + } }); + var WebAuthnAbortService = class { + /** + * Create an abort signal for a new WebAuthn operation. + * Automatically cancels any existing operation. + * + * @returns {AbortSignal} Signal to pass to navigator.credentials.create() or .get() + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal MDN - AbortSignal} + */ + createNewAbortSignal() { + if (this.controller) { + const abortError = new Error("Cancelling existing WebAuthn API call for new one"); + abortError.name = "AbortError"; + this.controller.abort(abortError); + } + const newController = new AbortController(); + this.controller = newController; + return newController.signal; + } + /** + * Manually cancel the current WebAuthn operation. + * Useful for cleaning up when user cancels or navigates away. + * + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort MDN - AbortController.abort} + */ + cancelCeremony() { + if (this.controller) { + const abortError = new Error("Manually cancelling existing WebAuthn API call"); + abortError.name = "AbortError"; + this.controller.abort(abortError); + this.controller = void 0; + } + } + }; + exports.WebAuthnAbortService = WebAuthnAbortService; + exports.webAuthnAbortService = new WebAuthnAbortService(); + function deserializeCredentialCreationOptions(options) { + if (!options) { + throw new Error("Credential creation options are required"); + } + if (typeof PublicKeyCredential !== "undefined" && "parseCreationOptionsFromJSON" in PublicKeyCredential && typeof PublicKeyCredential.parseCreationOptionsFromJSON === "function") { + return PublicKeyCredential.parseCreationOptionsFromJSON( + /** we assert the options here as typescript still doesn't know about future webauthn types */ + options + ); + } + const { challenge: challengeStr, user: userOpts, excludeCredentials } = options, restOptions = tslib_1.__rest( + options, + ["challenge", "user", "excludeCredentials"] + ); + const challenge = (0, base64url_1.base64UrlToUint8Array)(challengeStr).buffer; + const user = Object.assign(Object.assign({}, userOpts), { id: (0, base64url_1.base64UrlToUint8Array)(userOpts.id).buffer }); + const result = Object.assign(Object.assign({}, restOptions), { + challenge, + user + }); + if (excludeCredentials && excludeCredentials.length > 0) { + result.excludeCredentials = new Array(excludeCredentials.length); + for (let i = 0; i < excludeCredentials.length; i++) { + const cred = excludeCredentials[i]; + result.excludeCredentials[i] = Object.assign(Object.assign({}, cred), { + id: (0, base64url_1.base64UrlToUint8Array)(cred.id).buffer, + type: cred.type || "public-key", + // Cast transports to handle future transport types like "cable" + transports: cred.transports + }); + } + } + return result; + } + function deserializeCredentialRequestOptions(options) { + if (!options) { + throw new Error("Credential request options are required"); + } + if (typeof PublicKeyCredential !== "undefined" && "parseRequestOptionsFromJSON" in PublicKeyCredential && typeof PublicKeyCredential.parseRequestOptionsFromJSON === "function") { + return PublicKeyCredential.parseRequestOptionsFromJSON(options); + } + const { challenge: challengeStr, allowCredentials } = options, restOptions = tslib_1.__rest( + options, + ["challenge", "allowCredentials"] + ); + const challenge = (0, base64url_1.base64UrlToUint8Array)(challengeStr).buffer; + const result = Object.assign(Object.assign({}, restOptions), { challenge }); + if (allowCredentials && allowCredentials.length > 0) { + result.allowCredentials = new Array(allowCredentials.length); + for (let i = 0; i < allowCredentials.length; i++) { + const cred = allowCredentials[i]; + result.allowCredentials[i] = Object.assign(Object.assign({}, cred), { + id: (0, base64url_1.base64UrlToUint8Array)(cred.id).buffer, + type: cred.type || "public-key", + // Cast transports to handle future transport types like "cable" + transports: cred.transports + }); + } + } + return result; + } + function serializeCredentialCreationResponse(credential) { + var _a2; + if ("toJSON" in credential && typeof credential.toJSON === "function") { + return credential.toJSON(); + } + const credentialWithAttachment = credential; + return { + id: credential.id, + rawId: credential.id, + response: { + attestationObject: (0, base64url_1.bytesToBase64URL)(new Uint8Array(credential.response.attestationObject)), + clientDataJSON: (0, base64url_1.bytesToBase64URL)(new Uint8Array(credential.response.clientDataJSON)) + }, + type: "public-key", + clientExtensionResults: credential.getClientExtensionResults(), + // Convert null to undefined and cast to AuthenticatorAttachment type + authenticatorAttachment: (_a2 = credentialWithAttachment.authenticatorAttachment) !== null && _a2 !== void 0 ? _a2 : void 0 + }; + } + function serializeCredentialRequestResponse(credential) { + var _a2; + if ("toJSON" in credential && typeof credential.toJSON === "function") { + return credential.toJSON(); + } + const credentialWithAttachment = credential; + const clientExtensionResults = credential.getClientExtensionResults(); + const assertionResponse = credential.response; + return { + id: credential.id, + rawId: credential.id, + // W3C spec expects rawId to match id for JSON format + response: { + authenticatorData: (0, base64url_1.bytesToBase64URL)(new Uint8Array(assertionResponse.authenticatorData)), + clientDataJSON: (0, base64url_1.bytesToBase64URL)(new Uint8Array(assertionResponse.clientDataJSON)), + signature: (0, base64url_1.bytesToBase64URL)(new Uint8Array(assertionResponse.signature)), + userHandle: assertionResponse.userHandle ? (0, base64url_1.bytesToBase64URL)(new Uint8Array(assertionResponse.userHandle)) : void 0 + }, + type: "public-key", + clientExtensionResults, + // Convert null to undefined and cast to AuthenticatorAttachment type + authenticatorAttachment: (_a2 = credentialWithAttachment.authenticatorAttachment) !== null && _a2 !== void 0 ? _a2 : void 0 + }; + } + function isValidDomain(hostname) { + return ( + // Consider localhost valid as well since it's okay wrt Secure Contexts + hostname === "localhost" || /^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(hostname) + ); + } + function browserSupportsWebAuthn() { + var _a2, _b; + return !!((0, helpers_1.isBrowser)() && "PublicKeyCredential" in window && window.PublicKeyCredential && "credentials" in navigator && typeof ((_a2 = navigator === null || navigator === void 0 ? void 0 : navigator.credentials) === null || _a2 === void 0 ? void 0 : _a2.create) === "function" && typeof ((_b = navigator === null || navigator === void 0 ? void 0 : navigator.credentials) === null || _b === void 0 ? void 0 : _b.get) === "function"); + } + async function createCredential(options) { + try { + const response = await navigator.credentials.create( + /** we assert the type here until typescript types are updated */ + options + ); + if (!response) { + return { + data: null, + error: new webauthn_errors_1.WebAuthnUnknownError("Empty credential response", response) + }; + } + if (!(response instanceof PublicKeyCredential)) { + return { + data: null, + error: new webauthn_errors_1.WebAuthnUnknownError("Browser returned unexpected credential type", response) + }; + } + return { data: response, error: null }; + } catch (err) { + return { + data: null, + error: (0, webauthn_errors_1.identifyRegistrationError)({ + error: err, + options + }) + }; + } + } + async function getCredential(options) { + try { + const response = await navigator.credentials.get( + /** we assert the type here until typescript types are updated */ + options + ); + if (!response) { + return { + data: null, + error: new webauthn_errors_1.WebAuthnUnknownError("Empty credential response", response) + }; + } + if (!(response instanceof PublicKeyCredential)) { + return { + data: null, + error: new webauthn_errors_1.WebAuthnUnknownError("Browser returned unexpected credential type", response) + }; + } + return { data: response, error: null }; + } catch (err) { + return { + data: null, + error: (0, webauthn_errors_1.identifyAuthenticationError)({ + error: err, + options + }) + }; + } + } + exports.DEFAULT_CREATION_OPTIONS = { + hints: ["security-key"], + authenticatorSelection: { + authenticatorAttachment: "cross-platform", + requireResidentKey: false, + /** set to preferred because older yubikeys don't have PIN/Biometric */ + userVerification: "preferred", + residentKey: "discouraged" + }, + attestation: "direct" + }; + exports.DEFAULT_REQUEST_OPTIONS = { + /** set to preferred because older yubikeys don't have PIN/Biometric */ + userVerification: "preferred", + hints: ["security-key"], + attestation: "direct" + }; + function deepMerge(...sources) { + const isObject2 = (val) => val !== null && typeof val === "object" && !Array.isArray(val); + const isArrayBufferLike = (val) => val instanceof ArrayBuffer || ArrayBuffer.isView(val); + const result = {}; + for (const source of sources) { + if (!source) + continue; + for (const key in source) { + const value = source[key]; + if (value === void 0) + continue; + if (Array.isArray(value)) { + result[key] = value; + } else if (isArrayBufferLike(value)) { + result[key] = value; + } else if (isObject2(value)) { + const existing = result[key]; + if (isObject2(existing)) { + result[key] = deepMerge(existing, value); + } else { + result[key] = deepMerge(value); + } + } else { + result[key] = value; + } + } + } + return result; + } + function mergeCredentialCreationOptions(baseOptions, overrides) { + return deepMerge(exports.DEFAULT_CREATION_OPTIONS, baseOptions, overrides || {}); + } + function mergeCredentialRequestOptions(baseOptions, overrides) { + return deepMerge(exports.DEFAULT_REQUEST_OPTIONS, baseOptions, overrides || {}); + } + var WebAuthnApi = class { + constructor(client2) { + this.client = client2; + this.enroll = this._enroll.bind(this); + this.challenge = this._challenge.bind(this); + this.verify = this._verify.bind(this); + this.authenticate = this._authenticate.bind(this); + this.register = this._register.bind(this); + } + /** + * Enroll a new WebAuthn factor. + * Creates an unverified WebAuthn factor that must be verified with a credential. + * + * @experimental This method is experimental and may change in future releases + * @param {Omit} params - Enrollment parameters (friendlyName required) + * @returns {Promise} Enrolled factor details or error + * @see {@link https://w3c.github.io/webauthn/#sctn-registering-a-new-credential W3C WebAuthn Spec - Registering a New Credential} + */ + async _enroll(params) { + return this.client.mfa.enroll(Object.assign(Object.assign({}, params), { factorType: "webauthn" })); + } + /** + * Challenge for WebAuthn credential creation or authentication. + * Combines server challenge with browser credential operations. + * Handles both registration (create) and authentication (request) flows. + * + * @experimental This method is experimental and may change in future releases + * @param {MFAChallengeWebauthnParams & { friendlyName?: string; signal?: AbortSignal }} params - Challenge parameters including factorId + * @param {Object} overrides - Allows you to override the parameters passed to navigator.credentials + * @param {PublicKeyCredentialCreationOptionsFuture} overrides.create - Override options for credential creation + * @param {PublicKeyCredentialRequestOptionsFuture} overrides.request - Override options for credential request + * @returns {Promise} Challenge response with credential or error + * @see {@link https://w3c.github.io/webauthn/#sctn-credential-creation W3C WebAuthn Spec - Credential Creation} + * @see {@link https://w3c.github.io/webauthn/#sctn-verifying-assertion W3C WebAuthn Spec - Verifying Assertion} + */ + async _challenge({ factorId, webauthn, friendlyName, signal }, overrides) { + try { + const { data: challengeResponse, error: challengeError } = await this.client.mfa.challenge({ + factorId, + webauthn + }); + if (!challengeResponse) { + return { data: null, error: challengeError }; + } + const abortSignal = signal !== null && signal !== void 0 ? signal : exports.webAuthnAbortService.createNewAbortSignal(); + if (challengeResponse.webauthn.type === "create") { + const { user } = challengeResponse.webauthn.credential_options.publicKey; + if (!user.name) { + user.name = `${user.id}:${friendlyName}`; + } + if (!user.displayName) { + user.displayName = user.name; + } + } + switch (challengeResponse.webauthn.type) { + case "create": { + const options = mergeCredentialCreationOptions(challengeResponse.webauthn.credential_options.publicKey, overrides === null || overrides === void 0 ? void 0 : overrides.create); + const { data, error } = await createCredential({ + publicKey: options, + signal: abortSignal + }); + if (data) { + return { + data: { + factorId, + challengeId: challengeResponse.id, + webauthn: { + type: challengeResponse.webauthn.type, + credential_response: data + } + }, + error: null + }; + } + return { data: null, error }; + } + case "request": { + const options = mergeCredentialRequestOptions(challengeResponse.webauthn.credential_options.publicKey, overrides === null || overrides === void 0 ? void 0 : overrides.request); + const { data, error } = await getCredential(Object.assign(Object.assign({}, challengeResponse.webauthn.credential_options), { publicKey: options, signal: abortSignal })); + if (data) { + return { + data: { + factorId, + challengeId: challengeResponse.id, + webauthn: { + type: challengeResponse.webauthn.type, + credential_response: data + } + }, + error: null + }; + } + return { data: null, error }; + } + } + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; + } + return { + data: null, + error: new errors_1.AuthUnknownError("Unexpected error in challenge", error) + }; + } + } + /** + * Verify a WebAuthn credential with the server. + * Completes the WebAuthn ceremony by sending the credential to the server for verification. + * + * @experimental This method is experimental and may change in future releases + * @param {Object} params - Verification parameters + * @param {string} params.challengeId - ID of the challenge being verified + * @param {string} params.factorId - ID of the WebAuthn factor + * @param {MFAVerifyWebauthnParams['webauthn']} params.webauthn - WebAuthn credential response + * @returns {Promise} Verification result with session or error + * @see {@link https://w3c.github.io/webauthn/#sctn-verifying-assertion W3C WebAuthn Spec - Verifying an Authentication Assertion} + * */ + async _verify({ challengeId, factorId, webauthn }) { + return this.client.mfa.verify({ + factorId, + challengeId, + webauthn + }); + } + /** + * Complete WebAuthn authentication flow. + * Performs challenge and verification in a single operation for existing credentials. + * + * @experimental This method is experimental and may change in future releases + * @param {Object} params - Authentication parameters + * @param {string} params.factorId - ID of the WebAuthn factor to authenticate with + * @param {Object} params.webauthn - WebAuthn configuration + * @param {string} params.webauthn.rpId - Relying Party ID (defaults to current hostname) + * @param {string[]} params.webauthn.rpOrigins - Allowed origins (defaults to current origin) + * @param {AbortSignal} params.webauthn.signal - Optional abort signal + * @param {PublicKeyCredentialRequestOptionsFuture} overrides - Override options for navigator.credentials.get + * @returns {Promise>} Authentication result + * @see {@link https://w3c.github.io/webauthn/#sctn-authentication W3C WebAuthn Spec - Authentication Ceremony} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialRequestOptions MDN - PublicKeyCredentialRequestOptions} + */ + async _authenticate({ factorId, webauthn: { rpId = typeof window !== "undefined" ? window.location.hostname : void 0, rpOrigins = typeof window !== "undefined" ? [window.location.origin] : void 0, signal } = {} }, overrides) { + if (!rpId) { + return { + data: null, + error: new errors_1.AuthError("rpId is required for WebAuthn authentication") + }; + } + try { + if (!browserSupportsWebAuthn()) { + return { + data: null, + error: new errors_1.AuthUnknownError("Browser does not support WebAuthn", null) + }; + } + const { data: challengeResponse, error: challengeError } = await this.challenge({ + factorId, + webauthn: { rpId, rpOrigins }, + signal + }, { request: overrides }); + if (!challengeResponse) { + return { data: null, error: challengeError }; + } + const { webauthn } = challengeResponse; + return this._verify({ + factorId, + challengeId: challengeResponse.challengeId, + webauthn: { + type: webauthn.type, + rpId, + rpOrigins, + credential_response: webauthn.credential_response + } + }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; + } + return { + data: null, + error: new errors_1.AuthUnknownError("Unexpected error in authenticate", error) + }; + } + } + /** + * Complete WebAuthn registration flow. + * Performs enrollment, challenge, and verification in a single operation for new credentials. + * + * @experimental This method is experimental and may change in future releases + * @param {Object} params - Registration parameters + * @param {string} params.friendlyName - User-friendly name for the credential + * @param {string} params.rpId - Relying Party ID (defaults to current hostname) + * @param {string[]} params.rpOrigins - Allowed origins (defaults to current origin) + * @param {AbortSignal} params.signal - Optional abort signal + * @param {PublicKeyCredentialCreationOptionsFuture} overrides - Override options for navigator.credentials.create + * @returns {Promise>} Registration result + * @see {@link https://w3c.github.io/webauthn/#sctn-registering-a-new-credential W3C WebAuthn Spec - Registration Ceremony} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialCreationOptions MDN - PublicKeyCredentialCreationOptions} + */ + async _register({ friendlyName, webauthn: { rpId = typeof window !== "undefined" ? window.location.hostname : void 0, rpOrigins = typeof window !== "undefined" ? [window.location.origin] : void 0, signal } = {} }, overrides) { + if (!rpId) { + return { + data: null, + error: new errors_1.AuthError("rpId is required for WebAuthn registration") + }; + } + try { + if (!browserSupportsWebAuthn()) { + return { + data: null, + error: new errors_1.AuthUnknownError("Browser does not support WebAuthn", null) + }; + } + const { data: factor, error: enrollError } = await this._enroll({ + friendlyName + }); + if (!factor) { + await this.client.mfa.listFactors().then((factors) => { + var _a2; + return (_a2 = factors.data) === null || _a2 === void 0 ? void 0 : _a2.all.find((v) => v.factor_type === "webauthn" && v.friendly_name === friendlyName && v.status !== "unverified"); + }).then((factor2) => factor2 ? this.client.mfa.unenroll({ factorId: factor2 === null || factor2 === void 0 ? void 0 : factor2.id }) : void 0); + return { data: null, error: enrollError }; + } + const { data: challengeResponse, error: challengeError } = await this._challenge({ + factorId: factor.id, + friendlyName: factor.friendly_name, + webauthn: { rpId, rpOrigins }, + signal + }, { + create: overrides + }); + if (!challengeResponse) { + return { data: null, error: challengeError }; + } + return this._verify({ + factorId: factor.id, + challengeId: challengeResponse.challengeId, + webauthn: { + rpId, + rpOrigins, + type: challengeResponse.webauthn.type, + credential_response: challengeResponse.webauthn.credential_response + } + }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; + } + return { + data: null, + error: new errors_1.AuthUnknownError("Unexpected error in register", error) + }; + } + } + }; + exports.WebAuthnApi = WebAuthnApi; + } +}); + +// node_modules/@supabase/auth-js/dist/main/GoTrueClient.js +var require_GoTrueClient = __commonJS({ + "node_modules/@supabase/auth-js/dist/main/GoTrueClient.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var GoTrueAdminApi_1 = tslib_1.__importDefault(require_GoTrueAdminApi()); + var constants_1 = require_constants6(); + var errors_1 = require_errors3(); + var fetch_1 = require_fetch4(); + var helpers_1 = require_helpers4(); + var local_storage_1 = require_local_storage(); + var locks_1 = require_locks(); + var polyfills_1 = require_polyfills(); + var version_1 = require_version4(); + var base64url_1 = require_base64url(); + var ethereum_1 = require_ethereum(); + var webauthn_1 = require_webauthn(); + (0, polyfills_1.polyfillGlobalThis)(); + var DEFAULT_OPTIONS = { + url: constants_1.GOTRUE_URL, + storageKey: constants_1.STORAGE_KEY, + autoRefreshToken: true, + persistSession: true, + detectSessionInUrl: true, + headers: constants_1.DEFAULT_HEADERS, + flowType: "implicit", + debug: false, + hasCustomAuthorizationHeader: false, + throwOnError: false + }; + async function lockNoOp(name, acquireTimeout, fn) { + return await fn(); + } + var GLOBAL_JWKS = {}; + var GoTrueClient2 = class _GoTrueClient { + /** + * The JWKS used for verifying asymmetric JWTs + */ + get jwks() { + var _a2, _b; + return (_b = (_a2 = GLOBAL_JWKS[this.storageKey]) === null || _a2 === void 0 ? void 0 : _a2.jwks) !== null && _b !== void 0 ? _b : { keys: [] }; + } + set jwks(value) { + GLOBAL_JWKS[this.storageKey] = Object.assign(Object.assign({}, GLOBAL_JWKS[this.storageKey]), { jwks: value }); + } + get jwks_cached_at() { + var _a2, _b; + return (_b = (_a2 = GLOBAL_JWKS[this.storageKey]) === null || _a2 === void 0 ? void 0 : _a2.cachedAt) !== null && _b !== void 0 ? _b : Number.MIN_SAFE_INTEGER; + } + set jwks_cached_at(value) { + GLOBAL_JWKS[this.storageKey] = Object.assign(Object.assign({}, GLOBAL_JWKS[this.storageKey]), { cachedAt: value }); + } + /** + * Create a new client for use in the browser. + * + * @example + * ```ts + * import { GoTrueClient } from '@supabase/auth-js' + * + * const auth = new GoTrueClient({ + * url: 'https://xyzcompany.supabase.co/auth/v1', + * headers: { apikey: 'public-anon-key' }, + * storageKey: 'supabase-auth', + * }) + * ``` + */ + constructor(options) { + var _a2, _b, _c; + this.userStorage = null; + this.memoryStorage = null; + this.stateChangeEmitters = /* @__PURE__ */ new Map(); + this.autoRefreshTicker = null; + this.visibilityChangedCallback = null; + this.refreshingDeferred = null; + this.initializePromise = null; + this.detectSessionInUrl = true; + this.hasCustomAuthorizationHeader = false; + this.suppressGetSessionWarning = false; + this.lockAcquired = false; + this.pendingInLock = []; + this.broadcastChannel = null; + this.logger = console.log; + const settings = Object.assign(Object.assign({}, DEFAULT_OPTIONS), options); + this.storageKey = settings.storageKey; + this.instanceID = (_a2 = _GoTrueClient.nextInstanceID[this.storageKey]) !== null && _a2 !== void 0 ? _a2 : 0; + _GoTrueClient.nextInstanceID[this.storageKey] = this.instanceID + 1; + this.logDebugMessages = !!settings.debug; + if (typeof settings.debug === "function") { + this.logger = settings.debug; + } + if (this.instanceID > 0 && (0, helpers_1.isBrowser)()) { + const message = `${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`; + console.warn(message); + if (this.logDebugMessages) { + console.trace(message); + } + } + this.persistSession = settings.persistSession; + this.autoRefreshToken = settings.autoRefreshToken; + this.admin = new GoTrueAdminApi_1.default({ + url: settings.url, + headers: settings.headers, + fetch: settings.fetch + }); + this.url = settings.url; + this.headers = settings.headers; + this.fetch = (0, helpers_1.resolveFetch)(settings.fetch); + this.lock = settings.lock || lockNoOp; + this.detectSessionInUrl = settings.detectSessionInUrl; + this.flowType = settings.flowType; + this.hasCustomAuthorizationHeader = settings.hasCustomAuthorizationHeader; + this.throwOnError = settings.throwOnError; + if (settings.lock) { + this.lock = settings.lock; + } else if (this.persistSession && (0, helpers_1.isBrowser)() && ((_b = globalThis === null || globalThis === void 0 ? void 0 : globalThis.navigator) === null || _b === void 0 ? void 0 : _b.locks)) { + this.lock = locks_1.navigatorLock; + } else { + this.lock = lockNoOp; + } + if (!this.jwks) { + this.jwks = { keys: [] }; + this.jwks_cached_at = Number.MIN_SAFE_INTEGER; + } + this.mfa = { + verify: this._verify.bind(this), + enroll: this._enroll.bind(this), + unenroll: this._unenroll.bind(this), + challenge: this._challenge.bind(this), + listFactors: this._listFactors.bind(this), + challengeAndVerify: this._challengeAndVerify.bind(this), + getAuthenticatorAssuranceLevel: this._getAuthenticatorAssuranceLevel.bind(this), + webauthn: new webauthn_1.WebAuthnApi(this) + }; + this.oauth = { + getAuthorizationDetails: this._getAuthorizationDetails.bind(this), + approveAuthorization: this._approveAuthorization.bind(this), + denyAuthorization: this._denyAuthorization.bind(this), + listGrants: this._listOAuthGrants.bind(this), + revokeGrant: this._revokeOAuthGrant.bind(this) + }; + if (this.persistSession) { + if (settings.storage) { + this.storage = settings.storage; + } else { + if ((0, helpers_1.supportsLocalStorage)()) { + this.storage = globalThis.localStorage; + } else { + this.memoryStorage = {}; + this.storage = (0, local_storage_1.memoryLocalStorageAdapter)(this.memoryStorage); + } + } + if (settings.userStorage) { + this.userStorage = settings.userStorage; + } + } else { + this.memoryStorage = {}; + this.storage = (0, local_storage_1.memoryLocalStorageAdapter)(this.memoryStorage); + } + if ((0, helpers_1.isBrowser)() && globalThis.BroadcastChannel && this.persistSession && this.storageKey) { + try { + this.broadcastChannel = new globalThis.BroadcastChannel(this.storageKey); + } catch (e) { + console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available", e); + } + (_c = this.broadcastChannel) === null || _c === void 0 ? void 0 : _c.addEventListener("message", async (event) => { + this._debug("received broadcast notification from other tab or client", event); + await this._notifyAllSubscribers(event.data.event, event.data.session, false); + }); + } + this.initialize(); + } + /** + * Returns whether error throwing mode is enabled for this client. + */ + isThrowOnErrorEnabled() { + return this.throwOnError; + } + /** + * Centralizes return handling with optional error throwing. When `throwOnError` is enabled + * and the provided result contains a non-nullish error, the error is thrown instead of + * being returned. This ensures consistent behavior across all public API methods. + */ + _returnResult(result) { + if (this.throwOnError && result && result.error) { + throw result.error; + } + return result; + } + _logPrefix() { + return `GoTrueClient@${this.storageKey}:${this.instanceID} (${version_1.version}) ${(/* @__PURE__ */ new Date()).toISOString()}`; + } + _debug(...args) { + if (this.logDebugMessages) { + this.logger(this._logPrefix(), ...args); + } + return this; + } + /** + * Initializes the client session either from the url or from storage. + * This method is automatically called when instantiating the client, but should also be called + * manually when checking for an error from an auth redirect (oauth, magiclink, password recovery, etc). + */ + async initialize() { + if (this.initializePromise) { + return await this.initializePromise; + } + this.initializePromise = (async () => { + return await this._acquireLock(-1, async () => { + return await this._initialize(); + }); + })(); + return await this.initializePromise; + } + /** + * IMPORTANT: + * 1. Never throw in this method, as it is called from the constructor + * 2. Never return a session from this method as it would be cached over + * the whole lifetime of the client + */ + async _initialize() { + var _a2; + try { + let params = {}; + let callbackUrlType = "none"; + if ((0, helpers_1.isBrowser)()) { + params = (0, helpers_1.parseParametersFromURL)(window.location.href); + if (this._isImplicitGrantCallback(params)) { + callbackUrlType = "implicit"; + } else if (await this._isPKCECallback(params)) { + callbackUrlType = "pkce"; + } + } + if ((0, helpers_1.isBrowser)() && this.detectSessionInUrl && callbackUrlType !== "none") { + const { data, error } = await this._getSessionFromURL(params, callbackUrlType); + if (error) { + this._debug("#_initialize()", "error detecting session from URL", error); + if ((0, errors_1.isAuthImplicitGrantRedirectError)(error)) { + const errorCode = (_a2 = error.details) === null || _a2 === void 0 ? void 0 : _a2.code; + if (errorCode === "identity_already_exists" || errorCode === "identity_not_found" || errorCode === "single_identity_not_deletable") { + return { error }; + } + } + await this._removeSession(); + return { error }; + } + const { session, redirectType } = data; + this._debug("#_initialize()", "detected session in URL", session, "redirect type", redirectType); + await this._saveSession(session); + setTimeout(async () => { + if (redirectType === "recovery") { + await this._notifyAllSubscribers("PASSWORD_RECOVERY", session); + } else { + await this._notifyAllSubscribers("SIGNED_IN", session); + } + }, 0); + return { error: null }; + } + await this._recoverAndRefresh(); + return { error: null }; + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ error }); + } + return this._returnResult({ + error: new errors_1.AuthUnknownError("Unexpected error during initialization", error) + }); + } finally { + await this._handleVisibilityChange(); + this._debug("#_initialize()", "end"); + } + } + /** + * Creates a new anonymous user. + * + * @returns A session where the is_anonymous claim in the access token JWT set to true + */ + async signInAnonymously(credentials) { + var _a2, _b, _c; + try { + const res = await (0, fetch_1._request)(this.fetch, "POST", `${this.url}/signup`, { + headers: this.headers, + body: { + data: (_b = (_a2 = credentials === null || credentials === void 0 ? void 0 : credentials.options) === null || _a2 === void 0 ? void 0 : _a2.data) !== null && _b !== void 0 ? _b : {}, + gotrue_meta_security: { captcha_token: (_c = credentials === null || credentials === void 0 ? void 0 : credentials.options) === null || _c === void 0 ? void 0 : _c.captchaToken } + }, + xform: fetch_1._sessionResponse + }); + const { data, error } = res; + if (error || !data) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + const session = data.session; + const user = data.user; + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers("SIGNED_IN", session); + } + return this._returnResult({ data: { user, session }, error: null }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } + } + /** + * Creates a new user. + * + * Be aware that if a user account exists in the system you may get back an + * error message that attempts to hide this information from the user. + * This method has support for PKCE via email signups. The PKCE flow cannot be used when autoconfirm is enabled. + * + * @returns A logged-in session if the server has "autoconfirm" ON + * @returns A user if the server has "autoconfirm" OFF + */ + async signUp(credentials) { + var _a2, _b, _c; + try { + let res; + if ("email" in credentials) { + const { email, password, options } = credentials; + let codeChallenge = null; + let codeChallengeMethod = null; + if (this.flowType === "pkce") { + ; + [codeChallenge, codeChallengeMethod] = await (0, helpers_1.getCodeChallengeAndMethod)(this.storage, this.storageKey); + } + res = await (0, fetch_1._request)(this.fetch, "POST", `${this.url}/signup`, { + headers: this.headers, + redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo, + body: { + email, + password, + data: (_a2 = options === null || options === void 0 ? void 0 : options.data) !== null && _a2 !== void 0 ? _a2 : {}, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + code_challenge: codeChallenge, + code_challenge_method: codeChallengeMethod + }, + xform: fetch_1._sessionResponse + }); + } else if ("phone" in credentials) { + const { phone, password, options } = credentials; + res = await (0, fetch_1._request)(this.fetch, "POST", `${this.url}/signup`, { + headers: this.headers, + body: { + phone, + password, + data: (_b = options === null || options === void 0 ? void 0 : options.data) !== null && _b !== void 0 ? _b : {}, + channel: (_c = options === null || options === void 0 ? void 0 : options.channel) !== null && _c !== void 0 ? _c : "sms", + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken } + }, + xform: fetch_1._sessionResponse + }); + } else { + throw new errors_1.AuthInvalidCredentialsError("You must provide either an email or phone number and a password"); + } + const { data, error } = res; + if (error || !data) { + await (0, helpers_1.removeItemAsync)(this.storage, `${this.storageKey}-code-verifier`); + return this._returnResult({ data: { user: null, session: null }, error }); + } + const session = data.session; + const user = data.user; + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers("SIGNED_IN", session); + } + return this._returnResult({ data: { user, session }, error: null }); + } catch (error) { + await (0, helpers_1.removeItemAsync)(this.storage, `${this.storageKey}-code-verifier`); + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } + } + /** + * Log in an existing user with an email and password or phone and password. + * + * Be aware that you may get back an error message that will not distinguish + * between the cases where the account does not exist or that the + * email/phone and password combination is wrong or that the account can only + * be accessed via social login. + */ + async signInWithPassword(credentials) { + try { + let res; + if ("email" in credentials) { + const { email, password, options } = credentials; + res = await (0, fetch_1._request)(this.fetch, "POST", `${this.url}/token?grant_type=password`, { + headers: this.headers, + body: { + email, + password, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken } + }, + xform: fetch_1._sessionResponsePassword + }); + } else if ("phone" in credentials) { + const { phone, password, options } = credentials; + res = await (0, fetch_1._request)(this.fetch, "POST", `${this.url}/token?grant_type=password`, { + headers: this.headers, + body: { + phone, + password, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken } + }, + xform: fetch_1._sessionResponsePassword + }); + } else { + throw new errors_1.AuthInvalidCredentialsError("You must provide either an email or phone number and a password"); + } + const { data, error } = res; + if (error) { + return this._returnResult({ data: { user: null, session: null }, error }); + } else if (!data || !data.session || !data.user) { + const invalidTokenError = new errors_1.AuthInvalidTokenResponseError(); + return this._returnResult({ data: { user: null, session: null }, error: invalidTokenError }); + } + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers("SIGNED_IN", data.session); + } + return this._returnResult({ + data: Object.assign({ user: data.user, session: data.session }, data.weak_password ? { weakPassword: data.weak_password } : null), + error + }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } + } + /** + * Log in an existing user via a third-party provider. + * This method supports the PKCE flow. + */ + async signInWithOAuth(credentials) { + var _a2, _b, _c, _d; + return await this._handleProviderSignIn(credentials.provider, { + redirectTo: (_a2 = credentials.options) === null || _a2 === void 0 ? void 0 : _a2.redirectTo, + scopes: (_b = credentials.options) === null || _b === void 0 ? void 0 : _b.scopes, + queryParams: (_c = credentials.options) === null || _c === void 0 ? void 0 : _c.queryParams, + skipBrowserRedirect: (_d = credentials.options) === null || _d === void 0 ? void 0 : _d.skipBrowserRedirect + }); + } + /** + * Log in an existing user by exchanging an Auth Code issued during the PKCE flow. + */ + async exchangeCodeForSession(authCode) { + await this.initializePromise; + return this._acquireLock(-1, async () => { + return this._exchangeCodeForSession(authCode); + }); + } + /** + * Signs in a user by verifying a message signed by the user's private key. + * Supports Ethereum (via Sign-In-With-Ethereum) & Solana (Sign-In-With-Solana) standards, + * both of which derive from the EIP-4361 standard + * With slight variation on Solana's side. + * @reference https://eips.ethereum.org/EIPS/eip-4361 + */ + async signInWithWeb3(credentials) { + const { chain } = credentials; + switch (chain) { + case "ethereum": + return await this.signInWithEthereum(credentials); + case "solana": + return await this.signInWithSolana(credentials); + default: + throw new Error(`@supabase/auth-js: Unsupported chain "${chain}"`); + } + } + async signInWithEthereum(credentials) { + var _a2, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l; + let message; + let signature; + if ("message" in credentials) { + message = credentials.message; + signature = credentials.signature; + } else { + const { chain, wallet, statement, options } = credentials; + let resolvedWallet; + if (!(0, helpers_1.isBrowser)()) { + if (typeof wallet !== "object" || !(options === null || options === void 0 ? void 0 : options.url)) { + throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments."); + } + resolvedWallet = wallet; + } else if (typeof wallet === "object") { + resolvedWallet = wallet; + } else { + const windowAny = window; + if ("ethereum" in windowAny && typeof windowAny.ethereum === "object" && "request" in windowAny.ethereum && typeof windowAny.ethereum.request === "function") { + resolvedWallet = windowAny.ethereum; + } else { + throw new Error(`@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.`); + } + } + const url = new URL((_a2 = options === null || options === void 0 ? void 0 : options.url) !== null && _a2 !== void 0 ? _a2 : window.location.href); + const accounts = await resolvedWallet.request({ + method: "eth_requestAccounts" + }).then((accs) => accs).catch(() => { + throw new Error(`@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid`); + }); + if (!accounts || accounts.length === 0) { + throw new Error(`@supabase/auth-js: No accounts available. Please ensure the wallet is connected.`); + } + const address = (0, ethereum_1.getAddress)(accounts[0]); + let chainId = (_b = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _b === void 0 ? void 0 : _b.chainId; + if (!chainId) { + const chainIdHex = await resolvedWallet.request({ + method: "eth_chainId" + }); + chainId = (0, ethereum_1.fromHex)(chainIdHex); + } + const siweMessage = { + domain: url.host, + address, + statement, + uri: url.href, + version: "1", + chainId, + nonce: (_c = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _c === void 0 ? void 0 : _c.nonce, + issuedAt: (_e = (_d = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _d === void 0 ? void 0 : _d.issuedAt) !== null && _e !== void 0 ? _e : /* @__PURE__ */ new Date(), + expirationTime: (_f = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _f === void 0 ? void 0 : _f.expirationTime, + notBefore: (_g = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _g === void 0 ? void 0 : _g.notBefore, + requestId: (_h = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _h === void 0 ? void 0 : _h.requestId, + resources: (_j = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _j === void 0 ? void 0 : _j.resources + }; + message = (0, ethereum_1.createSiweMessage)(siweMessage); + signature = await resolvedWallet.request({ + method: "personal_sign", + params: [(0, ethereum_1.toHex)(message), address] + }); + } + try { + const { data, error } = await (0, fetch_1._request)(this.fetch, "POST", `${this.url}/token?grant_type=web3`, { + headers: this.headers, + body: Object.assign({ + chain: "ethereum", + message, + signature + }, ((_k = credentials.options) === null || _k === void 0 ? void 0 : _k.captchaToken) ? { gotrue_meta_security: { captcha_token: (_l = credentials.options) === null || _l === void 0 ? void 0 : _l.captchaToken } } : null), + xform: fetch_1._sessionResponse + }); + if (error) { + throw error; + } + if (!data || !data.session || !data.user) { + const invalidTokenError = new errors_1.AuthInvalidTokenResponseError(); + return this._returnResult({ data: { user: null, session: null }, error: invalidTokenError }); + } + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers("SIGNED_IN", data.session); + } + return this._returnResult({ data: Object.assign({}, data), error }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } + } + async signInWithSolana(credentials) { + var _a2, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m; + let message; + let signature; + if ("message" in credentials) { + message = credentials.message; + signature = credentials.signature; + } else { + const { chain, wallet, statement, options } = credentials; + let resolvedWallet; + if (!(0, helpers_1.isBrowser)()) { + if (typeof wallet !== "object" || !(options === null || options === void 0 ? void 0 : options.url)) { + throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments."); + } + resolvedWallet = wallet; + } else if (typeof wallet === "object") { + resolvedWallet = wallet; + } else { + const windowAny = window; + if ("solana" in windowAny && typeof windowAny.solana === "object" && ("signIn" in windowAny.solana && typeof windowAny.solana.signIn === "function" || "signMessage" in windowAny.solana && typeof windowAny.solana.signMessage === "function")) { + resolvedWallet = windowAny.solana; + } else { + throw new Error(`@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.`); + } + } + const url = new URL((_a2 = options === null || options === void 0 ? void 0 : options.url) !== null && _a2 !== void 0 ? _a2 : window.location.href); + if ("signIn" in resolvedWallet && resolvedWallet.signIn) { + const output = await resolvedWallet.signIn(Object.assign(Object.assign(Object.assign({ issuedAt: (/* @__PURE__ */ new Date()).toISOString() }, options === null || options === void 0 ? void 0 : options.signInWithSolana), { + // non-overridable properties + version: "1", + domain: url.host, + uri: url.href + }), statement ? { statement } : null)); + let outputToProcess; + if (Array.isArray(output) && output[0] && typeof output[0] === "object") { + outputToProcess = output[0]; + } else if (output && typeof output === "object" && "signedMessage" in output && "signature" in output) { + outputToProcess = output; + } else { + throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value"); + } + if ("signedMessage" in outputToProcess && "signature" in outputToProcess && (typeof outputToProcess.signedMessage === "string" || outputToProcess.signedMessage instanceof Uint8Array) && outputToProcess.signature instanceof Uint8Array) { + message = typeof outputToProcess.signedMessage === "string" ? outputToProcess.signedMessage : new TextDecoder().decode(outputToProcess.signedMessage); + signature = outputToProcess.signature; + } else { + throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields"); + } + } else { + if (!("signMessage" in resolvedWallet) || typeof resolvedWallet.signMessage !== "function" || !("publicKey" in resolvedWallet) || typeof resolvedWallet !== "object" || !resolvedWallet.publicKey || !("toBase58" in resolvedWallet.publicKey) || typeof resolvedWallet.publicKey.toBase58 !== "function") { + throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API"); + } + message = [ + `${url.host} wants you to sign in with your Solana account:`, + resolvedWallet.publicKey.toBase58(), + ...statement ? ["", statement, ""] : [""], + "Version: 1", + `URI: ${url.href}`, + `Issued At: ${(_c = (_b = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _b === void 0 ? void 0 : _b.issuedAt) !== null && _c !== void 0 ? _c : (/* @__PURE__ */ new Date()).toISOString()}`, + ...((_d = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _d === void 0 ? void 0 : _d.notBefore) ? [`Not Before: ${options.signInWithSolana.notBefore}`] : [], + ...((_e = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _e === void 0 ? void 0 : _e.expirationTime) ? [`Expiration Time: ${options.signInWithSolana.expirationTime}`] : [], + ...((_f = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _f === void 0 ? void 0 : _f.chainId) ? [`Chain ID: ${options.signInWithSolana.chainId}`] : [], + ...((_g = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _g === void 0 ? void 0 : _g.nonce) ? [`Nonce: ${options.signInWithSolana.nonce}`] : [], + ...((_h = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _h === void 0 ? void 0 : _h.requestId) ? [`Request ID: ${options.signInWithSolana.requestId}`] : [], + ...((_k = (_j = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _j === void 0 ? void 0 : _j.resources) === null || _k === void 0 ? void 0 : _k.length) ? [ + "Resources", + ...options.signInWithSolana.resources.map((resource) => `- ${resource}`) + ] : [] + ].join("\n"); + const maybeSignature = await resolvedWallet.signMessage(new TextEncoder().encode(message), "utf8"); + if (!maybeSignature || !(maybeSignature instanceof Uint8Array)) { + throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value"); + } + signature = maybeSignature; + } + } + try { + const { data, error } = await (0, fetch_1._request)(this.fetch, "POST", `${this.url}/token?grant_type=web3`, { + headers: this.headers, + body: Object.assign({ chain: "solana", message, signature: (0, base64url_1.bytesToBase64URL)(signature) }, ((_l = credentials.options) === null || _l === void 0 ? void 0 : _l.captchaToken) ? { gotrue_meta_security: { captcha_token: (_m = credentials.options) === null || _m === void 0 ? void 0 : _m.captchaToken } } : null), + xform: fetch_1._sessionResponse + }); + if (error) { + throw error; + } + if (!data || !data.session || !data.user) { + const invalidTokenError = new errors_1.AuthInvalidTokenResponseError(); + return this._returnResult({ data: { user: null, session: null }, error: invalidTokenError }); + } + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers("SIGNED_IN", data.session); + } + return this._returnResult({ data: Object.assign({}, data), error }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } + } + async _exchangeCodeForSession(authCode) { + const storageItem = await (0, helpers_1.getItemAsync)(this.storage, `${this.storageKey}-code-verifier`); + const [codeVerifier, redirectType] = (storageItem !== null && storageItem !== void 0 ? storageItem : "").split("/"); + try { + const { data, error } = await (0, fetch_1._request)(this.fetch, "POST", `${this.url}/token?grant_type=pkce`, { + headers: this.headers, + body: { + auth_code: authCode, + code_verifier: codeVerifier + }, + xform: fetch_1._sessionResponse + }); + await (0, helpers_1.removeItemAsync)(this.storage, `${this.storageKey}-code-verifier`); + if (error) { + throw error; + } + if (!data || !data.session || !data.user) { + const invalidTokenError = new errors_1.AuthInvalidTokenResponseError(); + return this._returnResult({ + data: { user: null, session: null, redirectType: null }, + error: invalidTokenError + }); + } + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers("SIGNED_IN", data.session); + } + return this._returnResult({ data: Object.assign(Object.assign({}, data), { redirectType: redirectType !== null && redirectType !== void 0 ? redirectType : null }), error }); + } catch (error) { + await (0, helpers_1.removeItemAsync)(this.storage, `${this.storageKey}-code-verifier`); + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ + data: { user: null, session: null, redirectType: null }, + error + }); + } + throw error; + } + } + /** + * Allows signing in with an OIDC ID token. The authentication provider used + * should be enabled and configured. + */ + async signInWithIdToken(credentials) { + try { + const { options, provider, token, access_token, nonce } = credentials; + const res = await (0, fetch_1._request)(this.fetch, "POST", `${this.url}/token?grant_type=id_token`, { + headers: this.headers, + body: { + provider, + id_token: token, + access_token, + nonce, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken } + }, + xform: fetch_1._sessionResponse + }); + const { data, error } = res; + if (error) { + return this._returnResult({ data: { user: null, session: null }, error }); + } else if (!data || !data.session || !data.user) { + const invalidTokenError = new errors_1.AuthInvalidTokenResponseError(); + return this._returnResult({ data: { user: null, session: null }, error: invalidTokenError }); + } + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers("SIGNED_IN", data.session); + } + return this._returnResult({ data, error }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } + } + /** + * Log in a user using magiclink or a one-time password (OTP). + * + * If the `{{ .ConfirmationURL }}` variable is specified in the email template, a magiclink will be sent. + * If the `{{ .Token }}` variable is specified in the email template, an OTP will be sent. + * If you're using phone sign-ins, only an OTP will be sent. You won't be able to send a magiclink for phone sign-ins. + * + * Be aware that you may get back an error message that will not distinguish + * between the cases where the account does not exist or, that the account + * can only be accessed via social login. + * + * Do note that you will need to configure a Whatsapp sender on Twilio + * if you are using phone sign in with the 'whatsapp' channel. The whatsapp + * channel is not supported on other providers + * at this time. + * This method supports PKCE when an email is passed. + */ + async signInWithOtp(credentials) { + var _a2, _b, _c, _d, _e; + try { + if ("email" in credentials) { + const { email, options } = credentials; + let codeChallenge = null; + let codeChallengeMethod = null; + if (this.flowType === "pkce") { + ; + [codeChallenge, codeChallengeMethod] = await (0, helpers_1.getCodeChallengeAndMethod)(this.storage, this.storageKey); + } + const { error } = await (0, fetch_1._request)(this.fetch, "POST", `${this.url}/otp`, { + headers: this.headers, + body: { + email, + data: (_a2 = options === null || options === void 0 ? void 0 : options.data) !== null && _a2 !== void 0 ? _a2 : {}, + create_user: (_b = options === null || options === void 0 ? void 0 : options.shouldCreateUser) !== null && _b !== void 0 ? _b : true, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + code_challenge: codeChallenge, + code_challenge_method: codeChallengeMethod + }, + redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo + }); + return this._returnResult({ data: { user: null, session: null }, error }); + } + if ("phone" in credentials) { + const { phone, options } = credentials; + const { data, error } = await (0, fetch_1._request)(this.fetch, "POST", `${this.url}/otp`, { + headers: this.headers, + body: { + phone, + data: (_c = options === null || options === void 0 ? void 0 : options.data) !== null && _c !== void 0 ? _c : {}, + create_user: (_d = options === null || options === void 0 ? void 0 : options.shouldCreateUser) !== null && _d !== void 0 ? _d : true, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + channel: (_e = options === null || options === void 0 ? void 0 : options.channel) !== null && _e !== void 0 ? _e : "sms" + } + }); + return this._returnResult({ + data: { user: null, session: null, messageId: data === null || data === void 0 ? void 0 : data.message_id }, + error + }); + } + throw new errors_1.AuthInvalidCredentialsError("You must provide either an email or phone number."); + } catch (error) { + await (0, helpers_1.removeItemAsync)(this.storage, `${this.storageKey}-code-verifier`); + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } + } + /** + * Log in a user given a User supplied OTP or TokenHash received through mobile or email. + */ + async verifyOtp(params) { + var _a2, _b; + try { + let redirectTo = void 0; + let captchaToken = void 0; + if ("options" in params) { + redirectTo = (_a2 = params.options) === null || _a2 === void 0 ? void 0 : _a2.redirectTo; + captchaToken = (_b = params.options) === null || _b === void 0 ? void 0 : _b.captchaToken; + } + const { data, error } = await (0, fetch_1._request)(this.fetch, "POST", `${this.url}/verify`, { + headers: this.headers, + body: Object.assign(Object.assign({}, params), { gotrue_meta_security: { captcha_token: captchaToken } }), + redirectTo, + xform: fetch_1._sessionResponse + }); + if (error) { + throw error; + } + if (!data) { + const tokenVerificationError = new Error("An error occurred on token verification."); + throw tokenVerificationError; + } + const session = data.session; + const user = data.user; + if (session === null || session === void 0 ? void 0 : session.access_token) { + await this._saveSession(session); + await this._notifyAllSubscribers(params.type == "recovery" ? "PASSWORD_RECOVERY" : "SIGNED_IN", session); + } + return this._returnResult({ data: { user, session }, error: null }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } + } + /** + * Attempts a single-sign on using an enterprise Identity Provider. A + * successful SSO attempt will redirect the current page to the identity + * provider authorization page. The redirect URL is implementation and SSO + * protocol specific. + * + * You can use it by providing a SSO domain. Typically you can extract this + * domain by asking users for their email address. If this domain is + * registered on the Auth instance the redirect will use that organization's + * currently active SSO Identity Provider for the login. + * + * If you have built an organization-specific login page, you can use the + * organization's SSO Identity Provider UUID directly instead. + */ + async signInWithSSO(params) { + var _a2, _b, _c, _d, _e; + try { + let codeChallenge = null; + let codeChallengeMethod = null; + if (this.flowType === "pkce") { + ; + [codeChallenge, codeChallengeMethod] = await (0, helpers_1.getCodeChallengeAndMethod)(this.storage, this.storageKey); + } + const result = await (0, fetch_1._request)(this.fetch, "POST", `${this.url}/sso`, { + body: Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, "providerId" in params ? { provider_id: params.providerId } : null), "domain" in params ? { domain: params.domain } : null), { redirect_to: (_b = (_a2 = params.options) === null || _a2 === void 0 ? void 0 : _a2.redirectTo) !== null && _b !== void 0 ? _b : void 0 }), ((_c = params === null || params === void 0 ? void 0 : params.options) === null || _c === void 0 ? void 0 : _c.captchaToken) ? { gotrue_meta_security: { captcha_token: params.options.captchaToken } } : null), { skip_http_redirect: true, code_challenge: codeChallenge, code_challenge_method: codeChallengeMethod }), + headers: this.headers, + xform: fetch_1._ssoResponse + }); + if (((_d = result.data) === null || _d === void 0 ? void 0 : _d.url) && (0, helpers_1.isBrowser)() && !((_e = params.options) === null || _e === void 0 ? void 0 : _e.skipBrowserRedirect)) { + window.location.assign(result.data.url); + } + return this._returnResult(result); + } catch (error) { + await (0, helpers_1.removeItemAsync)(this.storage, `${this.storageKey}-code-verifier`); + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + } + /** + * Sends a reauthentication OTP to the user's email or phone number. + * Requires the user to be signed-in. + */ + async reauthenticate() { + await this.initializePromise; + return await this._acquireLock(-1, async () => { + return await this._reauthenticate(); + }); + } + async _reauthenticate() { + try { + return await this._useSession(async (result) => { + const { data: { session }, error: sessionError } = result; + if (sessionError) + throw sessionError; + if (!session) + throw new errors_1.AuthSessionMissingError(); + const { error } = await (0, fetch_1._request)(this.fetch, "GET", `${this.url}/reauthenticate`, { + headers: this.headers, + jwt: session.access_token + }); + return this._returnResult({ data: { user: null, session: null }, error }); + }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } + } + /** + * Resends an existing signup confirmation email, email change email, SMS OTP or phone change OTP. + */ + async resend(credentials) { + try { + const endpoint = `${this.url}/resend`; + if ("email" in credentials) { + const { email, type, options } = credentials; + const { error } = await (0, fetch_1._request)(this.fetch, "POST", endpoint, { + headers: this.headers, + body: { + email, + type, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken } + }, + redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo + }); + return this._returnResult({ data: { user: null, session: null }, error }); + } else if ("phone" in credentials) { + const { phone, type, options } = credentials; + const { data, error } = await (0, fetch_1._request)(this.fetch, "POST", endpoint, { + headers: this.headers, + body: { + phone, + type, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken } + } + }); + return this._returnResult({ + data: { user: null, session: null, messageId: data === null || data === void 0 ? void 0 : data.message_id }, + error + }); + } + throw new errors_1.AuthInvalidCredentialsError("You must provide either an email or phone number and a type"); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } + } + /** + * Returns the session, refreshing it if necessary. + * + * The session returned can be null if the session is not detected which can happen in the event a user is not signed-in or has logged out. + * + * **IMPORTANT:** This method loads values directly from the storage attached + * to the client. If that storage is based on request cookies for example, + * the values in it may not be authentic and therefore it's strongly advised + * against using this method and its results in such circumstances. A warning + * will be emitted if this is detected. Use {@link #getUser()} instead. + */ + async getSession() { + await this.initializePromise; + const result = await this._acquireLock(-1, async () => { + return this._useSession(async (result2) => { + return result2; + }); + }); + return result; + } + /** + * Acquires a global lock based on the storage key. + */ + async _acquireLock(acquireTimeout, fn) { + this._debug("#_acquireLock", "begin", acquireTimeout); + try { + if (this.lockAcquired) { + const last2 = this.pendingInLock.length ? this.pendingInLock[this.pendingInLock.length - 1] : Promise.resolve(); + const result = (async () => { + await last2; + return await fn(); + })(); + this.pendingInLock.push((async () => { + try { + await result; + } catch (e) { + } + })()); + return result; + } + return await this.lock(`lock:${this.storageKey}`, acquireTimeout, async () => { + this._debug("#_acquireLock", "lock acquired for storage key", this.storageKey); + try { + this.lockAcquired = true; + const result = fn(); + this.pendingInLock.push((async () => { + try { + await result; + } catch (e) { + } + })()); + await result; + while (this.pendingInLock.length) { + const waitOn = [...this.pendingInLock]; + await Promise.all(waitOn); + this.pendingInLock.splice(0, waitOn.length); + } + return await result; + } finally { + this._debug("#_acquireLock", "lock released for storage key", this.storageKey); + this.lockAcquired = false; + } + }); + } finally { + this._debug("#_acquireLock", "end"); + } + } + /** + * Use instead of {@link #getSession} inside the library. It is + * semantically usually what you want, as getting a session involves some + * processing afterwards that requires only one client operating on the + * session at once across multiple tabs or processes. + */ + async _useSession(fn) { + this._debug("#_useSession", "begin"); + try { + const result = await this.__loadSession(); + return await fn(result); + } finally { + this._debug("#_useSession", "end"); + } + } + /** + * NEVER USE DIRECTLY! + * + * Always use {@link #_useSession}. + */ + async __loadSession() { + this._debug("#__loadSession()", "begin"); + if (!this.lockAcquired) { + this._debug("#__loadSession()", "used outside of an acquired lock!", new Error().stack); + } + try { + let currentSession = null; + const maybeSession = await (0, helpers_1.getItemAsync)(this.storage, this.storageKey); + this._debug("#getSession()", "session from storage", maybeSession); + if (maybeSession !== null) { + if (this._isValidSession(maybeSession)) { + currentSession = maybeSession; + } else { + this._debug("#getSession()", "session from storage is not valid"); + await this._removeSession(); + } + } + if (!currentSession) { + return { data: { session: null }, error: null }; + } + const hasExpired = currentSession.expires_at ? currentSession.expires_at * 1e3 - Date.now() < constants_1.EXPIRY_MARGIN_MS : false; + this._debug("#__loadSession()", `session has${hasExpired ? "" : " not"} expired`, "expires_at", currentSession.expires_at); + if (!hasExpired) { + if (this.userStorage) { + const maybeUser = await (0, helpers_1.getItemAsync)(this.userStorage, this.storageKey + "-user"); + if (maybeUser === null || maybeUser === void 0 ? void 0 : maybeUser.user) { + currentSession.user = maybeUser.user; + } else { + currentSession.user = (0, helpers_1.userNotAvailableProxy)(); + } + } + if (this.storage.isServer && currentSession.user && !currentSession.user.__isUserNotAvailableProxy) { + const suppressWarningRef = { value: this.suppressGetSessionWarning }; + currentSession.user = (0, helpers_1.insecureUserWarningProxy)(currentSession.user, suppressWarningRef); + if (suppressWarningRef.value) { + this.suppressGetSessionWarning = true; + } + } + return { data: { session: currentSession }, error: null }; + } + const { data: session, error } = await this._callRefreshToken(currentSession.refresh_token); + if (error) { + return this._returnResult({ data: { session: null }, error }); + } + return this._returnResult({ data: { session }, error: null }); + } finally { + this._debug("#__loadSession()", "end"); + } + } + /** + * Gets the current user details if there is an existing session. This method + * performs a network request to the Supabase Auth server, so the returned + * value is authentic and can be used to base authorization rules on. + * + * @param jwt Takes in an optional access token JWT. If no JWT is provided, the JWT from the current session is used. + */ + async getUser(jwt) { + if (jwt) { + return await this._getUser(jwt); + } + await this.initializePromise; + const result = await this._acquireLock(-1, async () => { + return await this._getUser(); + }); + if (result.data.user) { + this.suppressGetSessionWarning = true; + } + return result; + } + async _getUser(jwt) { + try { + if (jwt) { + return await (0, fetch_1._request)(this.fetch, "GET", `${this.url}/user`, { + headers: this.headers, + jwt, + xform: fetch_1._userResponse + }); + } + return await this._useSession(async (result) => { + var _a2, _b, _c; + const { data, error } = result; + if (error) { + throw error; + } + if (!((_a2 = data.session) === null || _a2 === void 0 ? void 0 : _a2.access_token) && !this.hasCustomAuthorizationHeader) { + return { data: { user: null }, error: new errors_1.AuthSessionMissingError() }; + } + return await (0, fetch_1._request)(this.fetch, "GET", `${this.url}/user`, { + headers: this.headers, + jwt: (_c = (_b = data.session) === null || _b === void 0 ? void 0 : _b.access_token) !== null && _c !== void 0 ? _c : void 0, + xform: fetch_1._userResponse + }); + }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + if ((0, errors_1.isAuthSessionMissingError)(error)) { + await this._removeSession(); + await (0, helpers_1.removeItemAsync)(this.storage, `${this.storageKey}-code-verifier`); + } + return this._returnResult({ data: { user: null }, error }); + } + throw error; + } + } + /** + * Updates user data for a logged in user. + */ + async updateUser(attributes, options = {}) { + await this.initializePromise; + return await this._acquireLock(-1, async () => { + return await this._updateUser(attributes, options); + }); + } + async _updateUser(attributes, options = {}) { + try { + return await this._useSession(async (result) => { + const { data: sessionData, error: sessionError } = result; + if (sessionError) { + throw sessionError; + } + if (!sessionData.session) { + throw new errors_1.AuthSessionMissingError(); + } + const session = sessionData.session; + let codeChallenge = null; + let codeChallengeMethod = null; + if (this.flowType === "pkce" && attributes.email != null) { + ; + [codeChallenge, codeChallengeMethod] = await (0, helpers_1.getCodeChallengeAndMethod)(this.storage, this.storageKey); + } + const { data, error: userError } = await (0, fetch_1._request)(this.fetch, "PUT", `${this.url}/user`, { + headers: this.headers, + redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo, + body: Object.assign(Object.assign({}, attributes), { code_challenge: codeChallenge, code_challenge_method: codeChallengeMethod }), + jwt: session.access_token, + xform: fetch_1._userResponse + }); + if (userError) { + throw userError; + } + session.user = data.user; + await this._saveSession(session); + await this._notifyAllSubscribers("USER_UPDATED", session); + return this._returnResult({ data: { user: session.user }, error: null }); + }); + } catch (error) { + await (0, helpers_1.removeItemAsync)(this.storage, `${this.storageKey}-code-verifier`); + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null }, error }); + } + throw error; + } + } + /** + * Sets the session data from the current session. If the current session is expired, setSession will take care of refreshing it to obtain a new session. + * If the refresh token or access token in the current session is invalid, an error will be thrown. + * @param currentSession The current session that minimally contains an access token and refresh token. + */ + async setSession(currentSession) { + await this.initializePromise; + return await this._acquireLock(-1, async () => { + return await this._setSession(currentSession); + }); + } + async _setSession(currentSession) { + try { + if (!currentSession.access_token || !currentSession.refresh_token) { + throw new errors_1.AuthSessionMissingError(); + } + const timeNow = Date.now() / 1e3; + let expiresAt = timeNow; + let hasExpired = true; + let session = null; + const { payload } = (0, helpers_1.decodeJWT)(currentSession.access_token); + if (payload.exp) { + expiresAt = payload.exp; + hasExpired = expiresAt <= timeNow; + } + if (hasExpired) { + const { data: refreshedSession, error } = await this._callRefreshToken(currentSession.refresh_token); + if (error) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + if (!refreshedSession) { + return { data: { user: null, session: null }, error: null }; + } + session = refreshedSession; + } else { + const { data, error } = await this._getUser(currentSession.access_token); + if (error) { + throw error; + } + session = { + access_token: currentSession.access_token, + refresh_token: currentSession.refresh_token, + user: data.user, + token_type: "bearer", + expires_in: expiresAt - timeNow, + expires_at: expiresAt + }; + await this._saveSession(session); + await this._notifyAllSubscribers("SIGNED_IN", session); + } + return this._returnResult({ data: { user: session.user, session }, error: null }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { session: null, user: null }, error }); + } + throw error; + } + } + /** + * Returns a new session, regardless of expiry status. + * Takes in an optional current session. If not passed in, then refreshSession() will attempt to retrieve it from getSession(). + * If the current session's refresh token is invalid, an error will be thrown. + * @param currentSession The current session. If passed in, it must contain a refresh token. + */ + async refreshSession(currentSession) { + await this.initializePromise; + return await this._acquireLock(-1, async () => { + return await this._refreshSession(currentSession); + }); + } + async _refreshSession(currentSession) { + try { + return await this._useSession(async (result) => { + var _a2; + if (!currentSession) { + const { data, error: error2 } = result; + if (error2) { + throw error2; + } + currentSession = (_a2 = data.session) !== null && _a2 !== void 0 ? _a2 : void 0; + } + if (!(currentSession === null || currentSession === void 0 ? void 0 : currentSession.refresh_token)) { + throw new errors_1.AuthSessionMissingError(); + } + const { data: session, error } = await this._callRefreshToken(currentSession.refresh_token); + if (error) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + if (!session) { + return this._returnResult({ data: { user: null, session: null }, error: null }); + } + return this._returnResult({ data: { user: session.user, session }, error: null }); + }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } + } + /** + * Gets the session data from a URL string + */ + async _getSessionFromURL(params, callbackUrlType) { + try { + if (!(0, helpers_1.isBrowser)()) + throw new errors_1.AuthImplicitGrantRedirectError("No browser detected."); + if (params.error || params.error_description || params.error_code) { + throw new errors_1.AuthImplicitGrantRedirectError(params.error_description || "Error in URL with unspecified error_description", { + error: params.error || "unspecified_error", + code: params.error_code || "unspecified_code" + }); + } + switch (callbackUrlType) { + case "implicit": + if (this.flowType === "pkce") { + throw new errors_1.AuthPKCEGrantCodeExchangeError("Not a valid PKCE flow url."); + } + break; + case "pkce": + if (this.flowType === "implicit") { + throw new errors_1.AuthImplicitGrantRedirectError("Not a valid implicit grant flow url."); + } + break; + default: + } + if (callbackUrlType === "pkce") { + this._debug("#_initialize()", "begin", "is PKCE flow", true); + if (!params.code) + throw new errors_1.AuthPKCEGrantCodeExchangeError("No code detected."); + const { data: data2, error: error2 } = await this._exchangeCodeForSession(params.code); + if (error2) + throw error2; + const url = new URL(window.location.href); + url.searchParams.delete("code"); + window.history.replaceState(window.history.state, "", url.toString()); + return { data: { session: data2.session, redirectType: null }, error: null }; + } + const { provider_token, provider_refresh_token, access_token, refresh_token, expires_in, expires_at, token_type } = params; + if (!access_token || !expires_in || !refresh_token || !token_type) { + throw new errors_1.AuthImplicitGrantRedirectError("No session defined in URL"); + } + const timeNow = Math.round(Date.now() / 1e3); + const expiresIn = parseInt(expires_in); + let expiresAt = timeNow + expiresIn; + if (expires_at) { + expiresAt = parseInt(expires_at); + } + const actuallyExpiresIn = expiresAt - timeNow; + if (actuallyExpiresIn * 1e3 <= constants_1.AUTO_REFRESH_TICK_DURATION_MS) { + console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${actuallyExpiresIn}s, should have been closer to ${expiresIn}s`); + } + const issuedAt = expiresAt - expiresIn; + if (timeNow - issuedAt >= 120) { + console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale", issuedAt, expiresAt, timeNow); + } else if (timeNow - issuedAt < 0) { + console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew", issuedAt, expiresAt, timeNow); + } + const { data, error } = await this._getUser(access_token); + if (error) + throw error; + const session = { + provider_token, + provider_refresh_token, + access_token, + expires_in: expiresIn, + expires_at: expiresAt, + refresh_token, + token_type, + user: data.user + }; + window.location.hash = ""; + this._debug("#_getSessionFromURL()", "clearing window.location.hash"); + return this._returnResult({ data: { session, redirectType: params.type }, error: null }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { session: null, redirectType: null }, error }); + } + throw error; + } + } + /** + * Checks if the current URL contains parameters given by an implicit oauth grant flow (https://www.rfc-editor.org/rfc/rfc6749.html#section-4.2) + */ + _isImplicitGrantCallback(params) { + return Boolean(params.access_token || params.error_description); + } + /** + * Checks if the current URL and backing storage contain parameters given by a PKCE flow + */ + async _isPKCECallback(params) { + const currentStorageContent = await (0, helpers_1.getItemAsync)(this.storage, `${this.storageKey}-code-verifier`); + return !!(params.code && currentStorageContent); + } + /** + * Inside a browser context, `signOut()` will remove the logged in user from the browser session and log them out - removing all items from localstorage and then trigger a `"SIGNED_OUT"` event. + * + * For server-side management, you can revoke all refresh tokens for a user by passing a user's JWT through to `auth.api.signOut(JWT: string)`. + * There is no way to revoke a user's access token jwt until it expires. It is recommended to set a shorter expiry on the jwt for this reason. + * + * If using `others` scope, no `SIGNED_OUT` event is fired! + */ + async signOut(options = { scope: "global" }) { + await this.initializePromise; + return await this._acquireLock(-1, async () => { + return await this._signOut(options); + }); + } + async _signOut({ scope } = { scope: "global" }) { + return await this._useSession(async (result) => { + var _a2; + const { data, error: sessionError } = result; + if (sessionError) { + return this._returnResult({ error: sessionError }); + } + const accessToken = (_a2 = data.session) === null || _a2 === void 0 ? void 0 : _a2.access_token; + if (accessToken) { + const { error } = await this.admin.signOut(accessToken, scope); + if (error) { + if (!((0, errors_1.isAuthApiError)(error) && (error.status === 404 || error.status === 401 || error.status === 403))) { + return this._returnResult({ error }); + } + } + } + if (scope !== "others") { + await this._removeSession(); + await (0, helpers_1.removeItemAsync)(this.storage, `${this.storageKey}-code-verifier`); + } + return this._returnResult({ error: null }); + }); + } + onAuthStateChange(callback) { + const id = (0, helpers_1.generateCallbackId)(); + const subscription = { + id, + callback, + unsubscribe: () => { + this._debug("#unsubscribe()", "state change callback with id removed", id); + this.stateChangeEmitters.delete(id); + } + }; + this._debug("#onAuthStateChange()", "registered callback with id", id); + this.stateChangeEmitters.set(id, subscription); + (async () => { + await this.initializePromise; + await this._acquireLock(-1, async () => { + this._emitInitialSession(id); + }); + })(); + return { data: { subscription } }; + } + async _emitInitialSession(id) { + return await this._useSession(async (result) => { + var _a2, _b; + try { + const { data: { session }, error } = result; + if (error) + throw error; + await ((_a2 = this.stateChangeEmitters.get(id)) === null || _a2 === void 0 ? void 0 : _a2.callback("INITIAL_SESSION", session)); + this._debug("INITIAL_SESSION", "callback id", id, "session", session); + } catch (err) { + await ((_b = this.stateChangeEmitters.get(id)) === null || _b === void 0 ? void 0 : _b.callback("INITIAL_SESSION", null)); + this._debug("INITIAL_SESSION", "callback id", id, "error", err); + console.error(err); + } + }); + } + /** + * Sends a password reset request to an email address. This method supports the PKCE flow. + * + * @param email The email address of the user. + * @param options.redirectTo The URL to send the user to after they click the password reset link. + * @param options.captchaToken Verification token received when the user completes the captcha on the site. + */ + async resetPasswordForEmail(email, options = {}) { + let codeChallenge = null; + let codeChallengeMethod = null; + if (this.flowType === "pkce") { + ; + [codeChallenge, codeChallengeMethod] = await (0, helpers_1.getCodeChallengeAndMethod)( + this.storage, + this.storageKey, + true + // isPasswordRecovery + ); + } + try { + return await (0, fetch_1._request)(this.fetch, "POST", `${this.url}/recover`, { + body: { + email, + code_challenge: codeChallenge, + code_challenge_method: codeChallengeMethod, + gotrue_meta_security: { captcha_token: options.captchaToken } + }, + headers: this.headers, + redirectTo: options.redirectTo + }); + } catch (error) { + await (0, helpers_1.removeItemAsync)(this.storage, `${this.storageKey}-code-verifier`); + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + } + /** + * Gets all the identities linked to a user. + */ + async getUserIdentities() { + var _a2; + try { + const { data, error } = await this.getUser(); + if (error) + throw error; + return this._returnResult({ data: { identities: (_a2 = data.user.identities) !== null && _a2 !== void 0 ? _a2 : [] }, error: null }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + } + async linkIdentity(credentials) { + if ("token" in credentials) { + return this.linkIdentityIdToken(credentials); + } + return this.linkIdentityOAuth(credentials); + } + async linkIdentityOAuth(credentials) { + var _a2; + try { + const { data, error } = await this._useSession(async (result) => { + var _a3, _b, _c, _d, _e; + const { data: data2, error: error2 } = result; + if (error2) + throw error2; + const url = await this._getUrlForProvider(`${this.url}/user/identities/authorize`, credentials.provider, { + redirectTo: (_a3 = credentials.options) === null || _a3 === void 0 ? void 0 : _a3.redirectTo, + scopes: (_b = credentials.options) === null || _b === void 0 ? void 0 : _b.scopes, + queryParams: (_c = credentials.options) === null || _c === void 0 ? void 0 : _c.queryParams, + skipBrowserRedirect: true + }); + return await (0, fetch_1._request)(this.fetch, "GET", url, { + headers: this.headers, + jwt: (_e = (_d = data2.session) === null || _d === void 0 ? void 0 : _d.access_token) !== null && _e !== void 0 ? _e : void 0 + }); + }); + if (error) + throw error; + if ((0, helpers_1.isBrowser)() && !((_a2 = credentials.options) === null || _a2 === void 0 ? void 0 : _a2.skipBrowserRedirect)) { + window.location.assign(data === null || data === void 0 ? void 0 : data.url); + } + return this._returnResult({ + data: { provider: credentials.provider, url: data === null || data === void 0 ? void 0 : data.url }, + error: null + }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { provider: credentials.provider, url: null }, error }); + } + throw error; + } + } + async linkIdentityIdToken(credentials) { + return await this._useSession(async (result) => { + var _a2; + try { + const { error: sessionError, data: { session } } = result; + if (sessionError) + throw sessionError; + const { options, provider, token, access_token, nonce } = credentials; + const res = await (0, fetch_1._request)(this.fetch, "POST", `${this.url}/token?grant_type=id_token`, { + headers: this.headers, + jwt: (_a2 = session === null || session === void 0 ? void 0 : session.access_token) !== null && _a2 !== void 0 ? _a2 : void 0, + body: { + provider, + id_token: token, + access_token, + nonce, + link_identity: true, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken } + }, + xform: fetch_1._sessionResponse + }); + const { data, error } = res; + if (error) { + return this._returnResult({ data: { user: null, session: null }, error }); + } else if (!data || !data.session || !data.user) { + return this._returnResult({ + data: { user: null, session: null }, + error: new errors_1.AuthInvalidTokenResponseError() + }); + } + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers("USER_UPDATED", data.session); + } + return this._returnResult({ data, error }); + } catch (error) { + await (0, helpers_1.removeItemAsync)(this.storage, `${this.storageKey}-code-verifier`); + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } + }); + } + /** + * Unlinks an identity from a user by deleting it. The user will no longer be able to sign in with that identity once it's unlinked. + */ + async unlinkIdentity(identity) { + try { + return await this._useSession(async (result) => { + var _a2, _b; + const { data, error } = result; + if (error) { + throw error; + } + return await (0, fetch_1._request)(this.fetch, "DELETE", `${this.url}/user/identities/${identity.identity_id}`, { + headers: this.headers, + jwt: (_b = (_a2 = data.session) === null || _a2 === void 0 ? void 0 : _a2.access_token) !== null && _b !== void 0 ? _b : void 0 + }); + }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + } + /** + * Generates a new JWT. + * @param refreshToken A valid refresh token that was returned on login. + */ + async _refreshAccessToken(refreshToken) { + const debugName = `#_refreshAccessToken(${refreshToken.substring(0, 5)}...)`; + this._debug(debugName, "begin"); + try { + const startedAt = Date.now(); + return await (0, helpers_1.retryable)(async (attempt) => { + if (attempt > 0) { + await (0, helpers_1.sleep)(200 * Math.pow(2, attempt - 1)); + } + this._debug(debugName, "refreshing attempt", attempt); + return await (0, fetch_1._request)(this.fetch, "POST", `${this.url}/token?grant_type=refresh_token`, { + body: { refresh_token: refreshToken }, + headers: this.headers, + xform: fetch_1._sessionResponse + }); + }, (attempt, error) => { + const nextBackOffInterval = 200 * Math.pow(2, attempt); + return error && (0, errors_1.isAuthRetryableFetchError)(error) && // retryable only if the request can be sent before the backoff overflows the tick duration + Date.now() + nextBackOffInterval - startedAt < constants_1.AUTO_REFRESH_TICK_DURATION_MS; + }); + } catch (error) { + this._debug(debugName, "error", error); + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { session: null, user: null }, error }); + } + throw error; + } finally { + this._debug(debugName, "end"); + } + } + _isValidSession(maybeSession) { + const isValidSession = typeof maybeSession === "object" && maybeSession !== null && "access_token" in maybeSession && "refresh_token" in maybeSession && "expires_at" in maybeSession; + return isValidSession; + } + async _handleProviderSignIn(provider, options) { + const url = await this._getUrlForProvider(`${this.url}/authorize`, provider, { + redirectTo: options.redirectTo, + scopes: options.scopes, + queryParams: options.queryParams + }); + this._debug("#_handleProviderSignIn()", "provider", provider, "options", options, "url", url); + if ((0, helpers_1.isBrowser)() && !options.skipBrowserRedirect) { + window.location.assign(url); + } + return { data: { provider, url }, error: null }; + } + /** + * Recovers the session from LocalStorage and refreshes the token + * Note: this method is async to accommodate for AsyncStorage e.g. in React native. + */ + async _recoverAndRefresh() { + var _a2, _b; + const debugName = "#_recoverAndRefresh()"; + this._debug(debugName, "begin"); + try { + const currentSession = await (0, helpers_1.getItemAsync)(this.storage, this.storageKey); + if (currentSession && this.userStorage) { + let maybeUser = await (0, helpers_1.getItemAsync)(this.userStorage, this.storageKey + "-user"); + if (!this.storage.isServer && Object.is(this.storage, this.userStorage) && !maybeUser) { + maybeUser = { user: currentSession.user }; + await (0, helpers_1.setItemAsync)(this.userStorage, this.storageKey + "-user", maybeUser); + } + currentSession.user = (_a2 = maybeUser === null || maybeUser === void 0 ? void 0 : maybeUser.user) !== null && _a2 !== void 0 ? _a2 : (0, helpers_1.userNotAvailableProxy)(); + } else if (currentSession && !currentSession.user) { + if (!currentSession.user) { + const separateUser = await (0, helpers_1.getItemAsync)(this.storage, this.storageKey + "-user"); + if (separateUser && (separateUser === null || separateUser === void 0 ? void 0 : separateUser.user)) { + currentSession.user = separateUser.user; + await (0, helpers_1.removeItemAsync)(this.storage, this.storageKey + "-user"); + await (0, helpers_1.setItemAsync)(this.storage, this.storageKey, currentSession); + } else { + currentSession.user = (0, helpers_1.userNotAvailableProxy)(); + } + } + } + this._debug(debugName, "session from storage", currentSession); + if (!this._isValidSession(currentSession)) { + this._debug(debugName, "session is not valid"); + if (currentSession !== null) { + await this._removeSession(); + } + return; + } + const expiresWithMargin = ((_b = currentSession.expires_at) !== null && _b !== void 0 ? _b : Infinity) * 1e3 - Date.now() < constants_1.EXPIRY_MARGIN_MS; + this._debug(debugName, `session has${expiresWithMargin ? "" : " not"} expired with margin of ${constants_1.EXPIRY_MARGIN_MS}s`); + if (expiresWithMargin) { + if (this.autoRefreshToken && currentSession.refresh_token) { + const { error } = await this._callRefreshToken(currentSession.refresh_token); + if (error) { + console.error(error); + if (!(0, errors_1.isAuthRetryableFetchError)(error)) { + this._debug(debugName, "refresh failed with a non-retryable error, removing the session", error); + await this._removeSession(); + } + } + } + } else if (currentSession.user && currentSession.user.__isUserNotAvailableProxy === true) { + try { + const { data, error: userError } = await this._getUser(currentSession.access_token); + if (!userError && (data === null || data === void 0 ? void 0 : data.user)) { + currentSession.user = data.user; + await this._saveSession(currentSession); + await this._notifyAllSubscribers("SIGNED_IN", currentSession); + } else { + this._debug(debugName, "could not get user data, skipping SIGNED_IN notification"); + } + } catch (getUserError) { + console.error("Error getting user data:", getUserError); + this._debug(debugName, "error getting user data, skipping SIGNED_IN notification", getUserError); + } + } else { + await this._notifyAllSubscribers("SIGNED_IN", currentSession); + } + } catch (err) { + this._debug(debugName, "error", err); + console.error(err); + return; + } finally { + this._debug(debugName, "end"); + } + } + async _callRefreshToken(refreshToken) { + var _a2, _b; + if (!refreshToken) { + throw new errors_1.AuthSessionMissingError(); + } + if (this.refreshingDeferred) { + return this.refreshingDeferred.promise; + } + const debugName = `#_callRefreshToken(${refreshToken.substring(0, 5)}...)`; + this._debug(debugName, "begin"); + try { + this.refreshingDeferred = new helpers_1.Deferred(); + const { data, error } = await this._refreshAccessToken(refreshToken); + if (error) + throw error; + if (!data.session) + throw new errors_1.AuthSessionMissingError(); + await this._saveSession(data.session); + await this._notifyAllSubscribers("TOKEN_REFRESHED", data.session); + const result = { data: data.session, error: null }; + this.refreshingDeferred.resolve(result); + return result; + } catch (error) { + this._debug(debugName, "error", error); + if ((0, errors_1.isAuthError)(error)) { + const result = { data: null, error }; + if (!(0, errors_1.isAuthRetryableFetchError)(error)) { + await this._removeSession(); + } + (_a2 = this.refreshingDeferred) === null || _a2 === void 0 ? void 0 : _a2.resolve(result); + return result; + } + (_b = this.refreshingDeferred) === null || _b === void 0 ? void 0 : _b.reject(error); + throw error; + } finally { + this.refreshingDeferred = null; + this._debug(debugName, "end"); + } + } + async _notifyAllSubscribers(event, session, broadcast = true) { + const debugName = `#_notifyAllSubscribers(${event})`; + this._debug(debugName, "begin", session, `broadcast = ${broadcast}`); + try { + if (this.broadcastChannel && broadcast) { + this.broadcastChannel.postMessage({ event, session }); + } + const errors = []; + const promises = Array.from(this.stateChangeEmitters.values()).map(async (x) => { + try { + await x.callback(event, session); + } catch (e) { + errors.push(e); + } + }); + await Promise.all(promises); + if (errors.length > 0) { + for (let i = 0; i < errors.length; i += 1) { + console.error(errors[i]); + } + throw errors[0]; + } + } finally { + this._debug(debugName, "end"); + } + } + /** + * set currentSession and currentUser + * process to _startAutoRefreshToken if possible + */ + async _saveSession(session) { + this._debug("#_saveSession()", session); + this.suppressGetSessionWarning = true; + await (0, helpers_1.removeItemAsync)(this.storage, `${this.storageKey}-code-verifier`); + const sessionToProcess = Object.assign({}, session); + const userIsProxy = sessionToProcess.user && sessionToProcess.user.__isUserNotAvailableProxy === true; + if (this.userStorage) { + if (!userIsProxy && sessionToProcess.user) { + await (0, helpers_1.setItemAsync)(this.userStorage, this.storageKey + "-user", { + user: sessionToProcess.user + }); + } else if (userIsProxy) { + } + const mainSessionData = Object.assign({}, sessionToProcess); + delete mainSessionData.user; + const clonedMainSessionData = (0, helpers_1.deepClone)(mainSessionData); + await (0, helpers_1.setItemAsync)(this.storage, this.storageKey, clonedMainSessionData); + } else { + const clonedSession = (0, helpers_1.deepClone)(sessionToProcess); + await (0, helpers_1.setItemAsync)(this.storage, this.storageKey, clonedSession); + } + } + async _removeSession() { + this._debug("#_removeSession()"); + this.suppressGetSessionWarning = false; + await (0, helpers_1.removeItemAsync)(this.storage, this.storageKey); + await (0, helpers_1.removeItemAsync)(this.storage, this.storageKey + "-code-verifier"); + await (0, helpers_1.removeItemAsync)(this.storage, this.storageKey + "-user"); + if (this.userStorage) { + await (0, helpers_1.removeItemAsync)(this.userStorage, this.storageKey + "-user"); + } + await this._notifyAllSubscribers("SIGNED_OUT", null); + } + /** + * Removes any registered visibilitychange callback. + * + * {@see #startAutoRefresh} + * {@see #stopAutoRefresh} + */ + _removeVisibilityChangedCallback() { + this._debug("#_removeVisibilityChangedCallback()"); + const callback = this.visibilityChangedCallback; + this.visibilityChangedCallback = null; + try { + if (callback && (0, helpers_1.isBrowser)() && (window === null || window === void 0 ? void 0 : window.removeEventListener)) { + window.removeEventListener("visibilitychange", callback); + } + } catch (e) { + console.error("removing visibilitychange callback failed", e); + } + } + /** + * This is the private implementation of {@link #startAutoRefresh}. Use this + * within the library. + */ + async _startAutoRefresh() { + await this._stopAutoRefresh(); + this._debug("#_startAutoRefresh()"); + const ticker = setInterval(() => this._autoRefreshTokenTick(), constants_1.AUTO_REFRESH_TICK_DURATION_MS); + this.autoRefreshTicker = ticker; + if (ticker && typeof ticker === "object" && typeof ticker.unref === "function") { + ticker.unref(); + } else if (typeof Deno !== "undefined" && typeof Deno.unrefTimer === "function") { + Deno.unrefTimer(ticker); + } + setTimeout(async () => { + await this.initializePromise; + await this._autoRefreshTokenTick(); + }, 0); + } + /** + * This is the private implementation of {@link #stopAutoRefresh}. Use this + * within the library. + */ + async _stopAutoRefresh() { + this._debug("#_stopAutoRefresh()"); + const ticker = this.autoRefreshTicker; + this.autoRefreshTicker = null; + if (ticker) { + clearInterval(ticker); + } + } + /** + * Starts an auto-refresh process in the background. The session is checked + * every few seconds. Close to the time of expiration a process is started to + * refresh the session. If refreshing fails it will be retried for as long as + * necessary. + * + * If you set the {@link GoTrueClientOptions#autoRefreshToken} you don't need + * to call this function, it will be called for you. + * + * On browsers the refresh process works only when the tab/window is in the + * foreground to conserve resources as well as prevent race conditions and + * flooding auth with requests. If you call this method any managed + * visibility change callback will be removed and you must manage visibility + * changes on your own. + * + * On non-browser platforms the refresh process works *continuously* in the + * background, which may not be desirable. You should hook into your + * platform's foreground indication mechanism and call these methods + * appropriately to conserve resources. + * + * {@see #stopAutoRefresh} + */ + async startAutoRefresh() { + this._removeVisibilityChangedCallback(); + await this._startAutoRefresh(); + } + /** + * Stops an active auto refresh process running in the background (if any). + * + * If you call this method any managed visibility change callback will be + * removed and you must manage visibility changes on your own. + * + * See {@link #startAutoRefresh} for more details. + */ + async stopAutoRefresh() { + this._removeVisibilityChangedCallback(); + await this._stopAutoRefresh(); + } + /** + * Runs the auto refresh token tick. + */ + async _autoRefreshTokenTick() { + this._debug("#_autoRefreshTokenTick()", "begin"); + try { + await this._acquireLock(0, async () => { + try { + const now = Date.now(); + try { + return await this._useSession(async (result) => { + const { data: { session } } = result; + if (!session || !session.refresh_token || !session.expires_at) { + this._debug("#_autoRefreshTokenTick()", "no session"); + return; + } + const expiresInTicks = Math.floor((session.expires_at * 1e3 - now) / constants_1.AUTO_REFRESH_TICK_DURATION_MS); + this._debug("#_autoRefreshTokenTick()", `access token expires in ${expiresInTicks} ticks, a tick lasts ${constants_1.AUTO_REFRESH_TICK_DURATION_MS}ms, refresh threshold is ${constants_1.AUTO_REFRESH_TICK_THRESHOLD} ticks`); + if (expiresInTicks <= constants_1.AUTO_REFRESH_TICK_THRESHOLD) { + await this._callRefreshToken(session.refresh_token); + } + }); + } catch (e) { + console.error("Auto refresh tick failed with error. This is likely a transient error.", e); + } + } finally { + this._debug("#_autoRefreshTokenTick()", "end"); + } + }); + } catch (e) { + if (e.isAcquireTimeout || e instanceof locks_1.LockAcquireTimeoutError) { + this._debug("auto refresh token tick lock not available"); + } else { + throw e; + } + } + } + /** + * Registers callbacks on the browser / platform, which in-turn run + * algorithms when the browser window/tab are in foreground. On non-browser + * platforms it assumes always foreground. + */ + async _handleVisibilityChange() { + this._debug("#_handleVisibilityChange()"); + if (!(0, helpers_1.isBrowser)() || !(window === null || window === void 0 ? void 0 : window.addEventListener)) { + if (this.autoRefreshToken) { + this.startAutoRefresh(); + } + return false; + } + try { + this.visibilityChangedCallback = async () => await this._onVisibilityChanged(false); + window === null || window === void 0 ? void 0 : window.addEventListener("visibilitychange", this.visibilityChangedCallback); + await this._onVisibilityChanged(true); + } catch (error) { + console.error("_handleVisibilityChange", error); + } + } + /** + * Callback registered with `window.addEventListener('visibilitychange')`. + */ + async _onVisibilityChanged(calledFromInitialize) { + const methodName = `#_onVisibilityChanged(${calledFromInitialize})`; + this._debug(methodName, "visibilityState", document.visibilityState); + if (document.visibilityState === "visible") { + if (this.autoRefreshToken) { + this._startAutoRefresh(); + } + if (!calledFromInitialize) { + await this.initializePromise; + await this._acquireLock(-1, async () => { + if (document.visibilityState !== "visible") { + this._debug(methodName, "acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting"); + return; + } + await this._recoverAndRefresh(); + }); + } + } else if (document.visibilityState === "hidden") { + if (this.autoRefreshToken) { + this._stopAutoRefresh(); + } + } + } + /** + * Generates the relevant login URL for a third-party provider. + * @param options.redirectTo A URL or mobile address to send the user to after they are confirmed. + * @param options.scopes A space-separated list of scopes granted to the OAuth application. + * @param options.queryParams An object of key-value pairs containing query parameters granted to the OAuth application. + */ + async _getUrlForProvider(url, provider, options) { + const urlParams = [`provider=${encodeURIComponent(provider)}`]; + if (options === null || options === void 0 ? void 0 : options.redirectTo) { + urlParams.push(`redirect_to=${encodeURIComponent(options.redirectTo)}`); + } + if (options === null || options === void 0 ? void 0 : options.scopes) { + urlParams.push(`scopes=${encodeURIComponent(options.scopes)}`); + } + if (this.flowType === "pkce") { + const [codeChallenge, codeChallengeMethod] = await (0, helpers_1.getCodeChallengeAndMethod)(this.storage, this.storageKey); + const flowParams = new URLSearchParams({ + code_challenge: `${encodeURIComponent(codeChallenge)}`, + code_challenge_method: `${encodeURIComponent(codeChallengeMethod)}` + }); + urlParams.push(flowParams.toString()); + } + if (options === null || options === void 0 ? void 0 : options.queryParams) { + const query = new URLSearchParams(options.queryParams); + urlParams.push(query.toString()); + } + if (options === null || options === void 0 ? void 0 : options.skipBrowserRedirect) { + urlParams.push(`skip_http_redirect=${options.skipBrowserRedirect}`); + } + return `${url}?${urlParams.join("&")}`; + } + async _unenroll(params) { + try { + return await this._useSession(async (result) => { + var _a2; + const { data: sessionData, error: sessionError } = result; + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }); + } + return await (0, fetch_1._request)(this.fetch, "DELETE", `${this.url}/factors/${params.factorId}`, { + headers: this.headers, + jwt: (_a2 = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a2 === void 0 ? void 0 : _a2.access_token + }); + }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + } + async _enroll(params) { + try { + return await this._useSession(async (result) => { + var _a2, _b; + const { data: sessionData, error: sessionError } = result; + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }); + } + const body = Object.assign({ friendly_name: params.friendlyName, factor_type: params.factorType }, params.factorType === "phone" ? { phone: params.phone } : params.factorType === "totp" ? { issuer: params.issuer } : {}); + const { data, error } = await (0, fetch_1._request)(this.fetch, "POST", `${this.url}/factors`, { + body, + headers: this.headers, + jwt: (_a2 = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a2 === void 0 ? void 0 : _a2.access_token + }); + if (error) { + return this._returnResult({ data: null, error }); + } + if (params.factorType === "totp" && data.type === "totp" && ((_b = data === null || data === void 0 ? void 0 : data.totp) === null || _b === void 0 ? void 0 : _b.qr_code)) { + data.totp.qr_code = `data:image/svg+xml;utf-8,${data.totp.qr_code}`; + } + return this._returnResult({ data, error: null }); + }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + } + async _verify(params) { + return this._acquireLock(-1, async () => { + try { + return await this._useSession(async (result) => { + var _a2; + const { data: sessionData, error: sessionError } = result; + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }); + } + const body = Object.assign({ challenge_id: params.challengeId }, "webauthn" in params ? { + webauthn: Object.assign(Object.assign({}, params.webauthn), { credential_response: params.webauthn.type === "create" ? (0, webauthn_1.serializeCredentialCreationResponse)(params.webauthn.credential_response) : (0, webauthn_1.serializeCredentialRequestResponse)(params.webauthn.credential_response) }) + } : { code: params.code }); + const { data, error } = await (0, fetch_1._request)(this.fetch, "POST", `${this.url}/factors/${params.factorId}/verify`, { + body, + headers: this.headers, + jwt: (_a2 = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a2 === void 0 ? void 0 : _a2.access_token + }); + if (error) { + return this._returnResult({ data: null, error }); + } + await this._saveSession(Object.assign({ expires_at: Math.round(Date.now() / 1e3) + data.expires_in }, data)); + await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED", data); + return this._returnResult({ data, error }); + }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + }); + } + async _challenge(params) { + return this._acquireLock(-1, async () => { + try { + return await this._useSession(async (result) => { + var _a2; + const { data: sessionData, error: sessionError } = result; + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }); + } + const response = await (0, fetch_1._request)(this.fetch, "POST", `${this.url}/factors/${params.factorId}/challenge`, { + body: params, + headers: this.headers, + jwt: (_a2 = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a2 === void 0 ? void 0 : _a2.access_token + }); + if (response.error) { + return response; + } + const { data } = response; + if (data.type !== "webauthn") { + return { data, error: null }; + } + switch (data.webauthn.type) { + case "create": + return { + data: Object.assign(Object.assign({}, data), { webauthn: Object.assign(Object.assign({}, data.webauthn), { credential_options: Object.assign(Object.assign({}, data.webauthn.credential_options), { publicKey: (0, webauthn_1.deserializeCredentialCreationOptions)(data.webauthn.credential_options.publicKey) }) }) }), + error: null + }; + case "request": + return { + data: Object.assign(Object.assign({}, data), { webauthn: Object.assign(Object.assign({}, data.webauthn), { credential_options: Object.assign(Object.assign({}, data.webauthn.credential_options), { publicKey: (0, webauthn_1.deserializeCredentialRequestOptions)(data.webauthn.credential_options.publicKey) }) }) }), + error: null + }; + } + }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + }); + } + /** + * {@see GoTrueMFAApi#challengeAndVerify} + */ + async _challengeAndVerify(params) { + const { data: challengeData, error: challengeError } = await this._challenge({ + factorId: params.factorId + }); + if (challengeError) { + return this._returnResult({ data: null, error: challengeError }); + } + return await this._verify({ + factorId: params.factorId, + challengeId: challengeData.id, + code: params.code + }); + } + /** + * {@see GoTrueMFAApi#listFactors} + */ + async _listFactors() { + var _a2; + const { data: { user }, error: userError } = await this.getUser(); + if (userError) { + return { data: null, error: userError }; + } + const data = { + all: [], + phone: [], + totp: [], + webauthn: [] + }; + for (const factor of (_a2 = user === null || user === void 0 ? void 0 : user.factors) !== null && _a2 !== void 0 ? _a2 : []) { + data.all.push(factor); + if (factor.status === "verified") { + ; + data[factor.factor_type].push(factor); + } + } + return { + data, + error: null + }; + } + /** + * {@see GoTrueMFAApi#getAuthenticatorAssuranceLevel} + */ + async _getAuthenticatorAssuranceLevel() { + var _a2, _b; + const { data: { session }, error: sessionError } = await this.getSession(); + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }); + } + if (!session) { + return { + data: { currentLevel: null, nextLevel: null, currentAuthenticationMethods: [] }, + error: null + }; + } + const { payload } = (0, helpers_1.decodeJWT)(session.access_token); + let currentLevel = null; + if (payload.aal) { + currentLevel = payload.aal; + } + let nextLevel = currentLevel; + const verifiedFactors = (_b = (_a2 = session.user.factors) === null || _a2 === void 0 ? void 0 : _a2.filter((factor) => factor.status === "verified")) !== null && _b !== void 0 ? _b : []; + if (verifiedFactors.length > 0) { + nextLevel = "aal2"; + } + const currentAuthenticationMethods = payload.amr || []; + return { data: { currentLevel, nextLevel, currentAuthenticationMethods }, error: null }; + } + /** + * Retrieves details about an OAuth authorization request. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * Returns authorization details including client info, scopes, and user information. + * If the API returns a redirect_uri, it means consent was already given - the caller + * should handle the redirect manually if needed. + */ + async _getAuthorizationDetails(authorizationId) { + try { + return await this._useSession(async (result) => { + const { data: { session }, error: sessionError } = result; + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }); + } + if (!session) { + return this._returnResult({ data: null, error: new errors_1.AuthSessionMissingError() }); + } + return await (0, fetch_1._request)(this.fetch, "GET", `${this.url}/oauth/authorizations/${authorizationId}`, { + headers: this.headers, + jwt: session.access_token, + xform: (data) => ({ data, error: null }) + }); + }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + } + /** + * Approves an OAuth authorization request. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ + async _approveAuthorization(authorizationId, options) { + try { + return await this._useSession(async (result) => { + const { data: { session }, error: sessionError } = result; + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }); + } + if (!session) { + return this._returnResult({ data: null, error: new errors_1.AuthSessionMissingError() }); + } + const response = await (0, fetch_1._request)(this.fetch, "POST", `${this.url}/oauth/authorizations/${authorizationId}/consent`, { + headers: this.headers, + jwt: session.access_token, + body: { action: "approve" }, + xform: (data) => ({ data, error: null }) + }); + if (response.data && response.data.redirect_url) { + if ((0, helpers_1.isBrowser)() && !(options === null || options === void 0 ? void 0 : options.skipBrowserRedirect)) { + window.location.assign(response.data.redirect_url); + } + } + return response; + }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + } + /** + * Denies an OAuth authorization request. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ + async _denyAuthorization(authorizationId, options) { + try { + return await this._useSession(async (result) => { + const { data: { session }, error: sessionError } = result; + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }); + } + if (!session) { + return this._returnResult({ data: null, error: new errors_1.AuthSessionMissingError() }); + } + const response = await (0, fetch_1._request)(this.fetch, "POST", `${this.url}/oauth/authorizations/${authorizationId}/consent`, { + headers: this.headers, + jwt: session.access_token, + body: { action: "deny" }, + xform: (data) => ({ data, error: null }) + }); + if (response.data && response.data.redirect_url) { + if ((0, helpers_1.isBrowser)() && !(options === null || options === void 0 ? void 0 : options.skipBrowserRedirect)) { + window.location.assign(response.data.redirect_url); + } + } + return response; + }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + } + /** + * Lists all OAuth grants that the authenticated user has authorized. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ + async _listOAuthGrants() { + try { + return await this._useSession(async (result) => { + const { data: { session }, error: sessionError } = result; + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }); + } + if (!session) { + return this._returnResult({ data: null, error: new errors_1.AuthSessionMissingError() }); + } + return await (0, fetch_1._request)(this.fetch, "GET", `${this.url}/user/oauth/grants`, { + headers: this.headers, + jwt: session.access_token, + xform: (data) => ({ data, error: null }) + }); + }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + } + /** + * Revokes a user's OAuth grant for a specific client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ + async _revokeOAuthGrant(options) { + try { + return await this._useSession(async (result) => { + const { data: { session }, error: sessionError } = result; + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }); + } + if (!session) { + return this._returnResult({ data: null, error: new errors_1.AuthSessionMissingError() }); + } + await (0, fetch_1._request)(this.fetch, "DELETE", `${this.url}/user/oauth/grants`, { + headers: this.headers, + jwt: session.access_token, + query: { client_id: options.clientId }, + noResolveJson: true + }); + return { data: {}, error: null }; + }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + } + async fetchJwk(kid, jwks = { keys: [] }) { + let jwk = jwks.keys.find((key) => key.kid === kid); + if (jwk) { + return jwk; + } + const now = Date.now(); + jwk = this.jwks.keys.find((key) => key.kid === kid); + if (jwk && this.jwks_cached_at + constants_1.JWKS_TTL > now) { + return jwk; + } + const { data, error } = await (0, fetch_1._request)(this.fetch, "GET", `${this.url}/.well-known/jwks.json`, { + headers: this.headers + }); + if (error) { + throw error; + } + if (!data.keys || data.keys.length === 0) { + return null; + } + this.jwks = data; + this.jwks_cached_at = now; + jwk = data.keys.find((key) => key.kid === kid); + if (!jwk) { + return null; + } + return jwk; + } + /** + * Extracts the JWT claims present in the access token by first verifying the + * JWT against the server's JSON Web Key Set endpoint + * `/.well-known/jwks.json` which is often cached, resulting in significantly + * faster responses. Prefer this method over {@link #getUser} which always + * sends a request to the Auth server for each JWT. + * + * If the project is not using an asymmetric JWT signing key (like ECC or + * RSA) it always sends a request to the Auth server (similar to {@link + * #getUser}) to verify the JWT. + * + * @param jwt An optional specific JWT you wish to verify, not the one you + * can obtain from {@link #getSession}. + * @param options Various additional options that allow you to customize the + * behavior of this method. + */ + async getClaims(jwt, options = {}) { + try { + let token = jwt; + if (!token) { + const { data, error } = await this.getSession(); + if (error || !data.session) { + return this._returnResult({ data: null, error }); + } + token = data.session.access_token; + } + const { header, payload, signature, raw: { header: rawHeader, payload: rawPayload } } = (0, helpers_1.decodeJWT)(token); + if (!(options === null || options === void 0 ? void 0 : options.allowExpired)) { + (0, helpers_1.validateExp)(payload.exp); + } + const signingKey = !header.alg || header.alg.startsWith("HS") || !header.kid || !("crypto" in globalThis && "subtle" in globalThis.crypto) ? null : await this.fetchJwk(header.kid, (options === null || options === void 0 ? void 0 : options.keys) ? { keys: options.keys } : options === null || options === void 0 ? void 0 : options.jwks); + if (!signingKey) { + const { error } = await this.getUser(token); + if (error) { + throw error; + } + return { + data: { + claims: payload, + header, + signature + }, + error: null + }; + } + const algorithm = (0, helpers_1.getAlgorithm)(header.alg); + const publicKey = await crypto.subtle.importKey("jwk", signingKey, algorithm, true, [ + "verify" + ]); + const isValid2 = await crypto.subtle.verify(algorithm, publicKey, signature, (0, base64url_1.stringToUint8Array)(`${rawHeader}.${rawPayload}`)); + if (!isValid2) { + throw new errors_1.AuthInvalidJwtError("Invalid JWT signature"); + } + return { + data: { + claims: payload, + header, + signature + }, + error: null + }; + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + } + }; + GoTrueClient2.nextInstanceID = {}; + exports.default = GoTrueClient2; + } +}); + +// node_modules/@supabase/auth-js/dist/main/AuthAdminApi.js +var require_AuthAdminApi = __commonJS({ + "node_modules/@supabase/auth-js/dist/main/AuthAdminApi.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var GoTrueAdminApi_1 = tslib_1.__importDefault(require_GoTrueAdminApi()); + var AuthAdminApi2 = GoTrueAdminApi_1.default; + exports.default = AuthAdminApi2; + } +}); + +// node_modules/@supabase/auth-js/dist/main/AuthClient.js +var require_AuthClient = __commonJS({ + "node_modules/@supabase/auth-js/dist/main/AuthClient.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var GoTrueClient_1 = tslib_1.__importDefault(require_GoTrueClient()); + var AuthClient2 = GoTrueClient_1.default; + exports.default = AuthClient2; + } +}); + +// node_modules/@supabase/auth-js/dist/main/index.js +var require_main4 = __commonJS({ + "node_modules/@supabase/auth-js/dist/main/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.processLock = exports.lockInternals = exports.NavigatorLockAcquireTimeoutError = exports.navigatorLock = exports.AuthClient = exports.AuthAdminApi = exports.GoTrueClient = exports.GoTrueAdminApi = void 0; + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var GoTrueAdminApi_1 = tslib_1.__importDefault(require_GoTrueAdminApi()); + exports.GoTrueAdminApi = GoTrueAdminApi_1.default; + var GoTrueClient_1 = tslib_1.__importDefault(require_GoTrueClient()); + exports.GoTrueClient = GoTrueClient_1.default; + var AuthAdminApi_1 = tslib_1.__importDefault(require_AuthAdminApi()); + exports.AuthAdminApi = AuthAdminApi_1.default; + var AuthClient_1 = tslib_1.__importDefault(require_AuthClient()); + exports.AuthClient = AuthClient_1.default; + tslib_1.__exportStar(require_types3(), exports); + tslib_1.__exportStar(require_errors3(), exports); + var locks_1 = require_locks(); + Object.defineProperty(exports, "navigatorLock", { enumerable: true, get: function() { + return locks_1.navigatorLock; + } }); + Object.defineProperty(exports, "NavigatorLockAcquireTimeoutError", { enumerable: true, get: function() { + return locks_1.NavigatorLockAcquireTimeoutError; + } }); + Object.defineProperty(exports, "lockInternals", { enumerable: true, get: function() { + return locks_1.internals; + } }); + Object.defineProperty(exports, "processLock", { enumerable: true, get: function() { + return locks_1.processLock; + } }); + } +}); + +// node_modules/@supabase/supabase-js/dist/main/lib/SupabaseAuthClient.js +var require_SupabaseAuthClient = __commonJS({ + "node_modules/@supabase/supabase-js/dist/main/lib/SupabaseAuthClient.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SupabaseAuthClient = void 0; + var auth_js_1 = require_main4(); + var SupabaseAuthClient = class extends auth_js_1.AuthClient { + constructor(options) { + super(options); + } + }; + exports.SupabaseAuthClient = SupabaseAuthClient; + } +}); + +// node_modules/@supabase/supabase-js/dist/main/SupabaseClient.js +var require_SupabaseClient = __commonJS({ + "node_modules/@supabase/supabase-js/dist/main/SupabaseClient.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var functions_js_1 = require_main(); + var postgrest_js_1 = require_cjs(); + var realtime_js_1 = require_main2(); + var storage_js_1 = require_main3(); + var constants_1 = require_constants5(); + var fetch_1 = require_fetch3(); + var helpers_1 = require_helpers3(); + var SupabaseAuthClient_1 = require_SupabaseAuthClient(); + var SupabaseClient3 = class { + /** + * Create a new client for use in the browser. + * @param supabaseUrl The unique Supabase URL which is supplied when you create a new project in your project dashboard. + * @param supabaseKey The unique Supabase Key which is supplied when you create a new project in your project dashboard. + * @param options.db.schema You can switch in between schemas. The schema needs to be on the list of exposed schemas inside Supabase. + * @param options.auth.autoRefreshToken Set to "true" if you want to automatically refresh the token before expiring. + * @param options.auth.persistSession Set to "true" if you want to automatically save the user session into local storage. + * @param options.auth.detectSessionInUrl Set to "true" if you want to automatically detects OAuth grants in the URL and signs in the user. + * @param options.realtime Options passed along to realtime-js constructor. + * @param options.storage Options passed along to the storage-js constructor. + * @param options.global.fetch A custom fetch implementation. + * @param options.global.headers Any additional headers to send with each network request. + * @example + * ```ts + * import { createClient } from '@supabase/supabase-js' + * + * const supabase = createClient('https://xyzcompany.supabase.co', 'public-anon-key') + * const { data } = await supabase.from('profiles').select('*') + * ``` + */ + constructor(supabaseUrl, supabaseKey, options) { + var _a2, _b, _c; + this.supabaseUrl = supabaseUrl; + this.supabaseKey = supabaseKey; + const baseUrl = (0, helpers_1.validateSupabaseUrl)(supabaseUrl); + if (!supabaseKey) + throw new Error("supabaseKey is required."); + this.realtimeUrl = new URL("realtime/v1", baseUrl); + this.realtimeUrl.protocol = this.realtimeUrl.protocol.replace("http", "ws"); + this.authUrl = new URL("auth/v1", baseUrl); + this.storageUrl = new URL("storage/v1", baseUrl); + this.functionsUrl = new URL("functions/v1", baseUrl); + const defaultStorageKey = `sb-${baseUrl.hostname.split(".")[0]}-auth-token`; + const DEFAULTS = { + db: constants_1.DEFAULT_DB_OPTIONS, + realtime: constants_1.DEFAULT_REALTIME_OPTIONS, + auth: Object.assign(Object.assign({}, constants_1.DEFAULT_AUTH_OPTIONS), { storageKey: defaultStorageKey }), + global: constants_1.DEFAULT_GLOBAL_OPTIONS + }; + const settings = (0, helpers_1.applySettingDefaults)(options !== null && options !== void 0 ? options : {}, DEFAULTS); + this.storageKey = (_a2 = settings.auth.storageKey) !== null && _a2 !== void 0 ? _a2 : ""; + this.headers = (_b = settings.global.headers) !== null && _b !== void 0 ? _b : {}; + if (!settings.accessToken) { + this.auth = this._initSupabaseAuthClient((_c = settings.auth) !== null && _c !== void 0 ? _c : {}, this.headers, settings.global.fetch); + } else { + this.accessToken = settings.accessToken; + this.auth = new Proxy({}, { + get: (_, prop) => { + throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(prop)} is not possible`); + } + }); + } + this.fetch = (0, fetch_1.fetchWithAuth)(supabaseKey, this._getAccessToken.bind(this), settings.global.fetch); + this.realtime = this._initRealtimeClient(Object.assign({ headers: this.headers, accessToken: this._getAccessToken.bind(this) }, settings.realtime)); + if (this.accessToken) { + this.accessToken().then((token) => this.realtime.setAuth(token)).catch((e) => console.warn("Failed to set initial Realtime auth token:", e)); + } + this.rest = new postgrest_js_1.PostgrestClient(new URL("rest/v1", baseUrl).href, { + headers: this.headers, + schema: settings.db.schema, + fetch: this.fetch + }); + this.storage = new storage_js_1.StorageClient(this.storageUrl.href, this.headers, this.fetch, options === null || options === void 0 ? void 0 : options.storage); + if (!settings.accessToken) { + this._listenForAuthEvents(); + } + } + /** + * Supabase Functions allows you to deploy and invoke edge functions. + */ + get functions() { + return new functions_js_1.FunctionsClient(this.functionsUrl.href, { + headers: this.headers, + customFetch: this.fetch + }); + } + /** + * Perform a query on a table or a view. + * + * @param relation - The table or view name to query + */ + from(relation) { + return this.rest.from(relation); + } + // NOTE: signatures must be kept in sync with PostgrestClient.schema + /** + * Select a schema to query or perform an function (rpc) call. + * + * The schema needs to be on the list of exposed schemas inside Supabase. + * + * @param schema - The schema to query + */ + schema(schema) { + return this.rest.schema(schema); + } + // NOTE: signatures must be kept in sync with PostgrestClient.rpc + /** + * Perform a function call. + * + * @param fn - The function name to call + * @param args - The arguments to pass to the function call + * @param options - Named parameters + * @param options.head - When set to `true`, `data` will not be returned. + * Useful if you only need the count. + * @param options.get - When set to `true`, the function will be called with + * read-only access mode. + * @param options.count - Count algorithm to use to count rows returned by the + * function. Only applicable for [set-returning + * functions](https://www.postgresql.org/docs/current/functions-srf.html). + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + rpc(fn, args = {}, options = { + head: false, + get: false, + count: void 0 + }) { + return this.rest.rpc(fn, args, options); + } + /** + * Creates a Realtime channel with Broadcast, Presence, and Postgres Changes. + * + * @param {string} name - The name of the Realtime channel. + * @param {Object} opts - The options to pass to the Realtime channel. + * + */ + channel(name, opts = { config: {} }) { + return this.realtime.channel(name, opts); + } + /** + * Returns all Realtime channels. + */ + getChannels() { + return this.realtime.getChannels(); + } + /** + * Unsubscribes and removes Realtime channel from Realtime client. + * + * @param {RealtimeChannel} channel - The name of the Realtime channel. + * + */ + removeChannel(channel) { + return this.realtime.removeChannel(channel); + } + /** + * Unsubscribes and removes all Realtime channels from Realtime client. + */ + removeAllChannels() { + return this.realtime.removeAllChannels(); + } + async _getAccessToken() { + var _a2, _b; + if (this.accessToken) { + return await this.accessToken(); + } + const { data } = await this.auth.getSession(); + return (_b = (_a2 = data.session) === null || _a2 === void 0 ? void 0 : _a2.access_token) !== null && _b !== void 0 ? _b : this.supabaseKey; + } + _initSupabaseAuthClient({ autoRefreshToken, persistSession, detectSessionInUrl, storage, userStorage, storageKey, flowType, lock, debug, throwOnError }, headers, fetch2) { + const authHeaders = { + Authorization: `Bearer ${this.supabaseKey}`, + apikey: `${this.supabaseKey}` + }; + return new SupabaseAuthClient_1.SupabaseAuthClient({ + url: this.authUrl.href, + headers: Object.assign(Object.assign({}, authHeaders), headers), + storageKey, + autoRefreshToken, + persistSession, + detectSessionInUrl, + storage, + userStorage, + flowType, + lock, + debug, + throwOnError, + fetch: fetch2, + // auth checks if there is a custom authorizaiton header using this flag + // so it knows whether to return an error when getUser is called with no session + hasCustomAuthorizationHeader: Object.keys(this.headers).some((key) => key.toLowerCase() === "authorization") + }); + } + _initRealtimeClient(options) { + return new realtime_js_1.RealtimeClient(this.realtimeUrl.href, Object.assign(Object.assign({}, options), { params: Object.assign({ apikey: this.supabaseKey }, options === null || options === void 0 ? void 0 : options.params) })); + } + _listenForAuthEvents() { + const data = this.auth.onAuthStateChange((event, session) => { + this._handleTokenChanged(event, "CLIENT", session === null || session === void 0 ? void 0 : session.access_token); + }); + return data; + } + _handleTokenChanged(event, source, token) { + if ((event === "TOKEN_REFRESHED" || event === "SIGNED_IN") && this.changedAccessToken !== token) { + this.changedAccessToken = token; + this.realtime.setAuth(token); + } else if (event === "SIGNED_OUT") { + this.realtime.setAuth(); + if (source == "STORAGE") + this.auth.signOut(); + this.changedAccessToken = void 0; + } + } + }; + exports.default = SupabaseClient3; + } +}); + +// node_modules/@supabase/supabase-js/dist/main/index.js +var require_main5 = __commonJS({ + "node_modules/@supabase/supabase-js/dist/main/index.js"(exports) { + "use strict"; + var __createBinding2 = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __exportStar2 = exports && exports.__exportStar || function(m, exports2) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p)) __createBinding2(exports2, m, p); + }; + var __importDefault2 = exports && exports.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { "default": mod }; + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createClient = exports.SupabaseClient = exports.FunctionRegion = exports.FunctionsError = exports.FunctionsRelayError = exports.FunctionsFetchError = exports.FunctionsHttpError = exports.PostgrestError = void 0; + var SupabaseClient_1 = __importDefault2(require_SupabaseClient()); + __exportStar2(require_main4(), exports); + var postgrest_js_1 = require_cjs(); + Object.defineProperty(exports, "PostgrestError", { enumerable: true, get: function() { + return postgrest_js_1.PostgrestError; + } }); + var functions_js_1 = require_main(); + Object.defineProperty(exports, "FunctionsHttpError", { enumerable: true, get: function() { + return functions_js_1.FunctionsHttpError; + } }); + Object.defineProperty(exports, "FunctionsFetchError", { enumerable: true, get: function() { + return functions_js_1.FunctionsFetchError; + } }); + Object.defineProperty(exports, "FunctionsRelayError", { enumerable: true, get: function() { + return functions_js_1.FunctionsRelayError; + } }); + Object.defineProperty(exports, "FunctionsError", { enumerable: true, get: function() { + return functions_js_1.FunctionsError; + } }); + Object.defineProperty(exports, "FunctionRegion", { enumerable: true, get: function() { + return functions_js_1.FunctionRegion; + } }); + __exportStar2(require_main2(), exports); + var SupabaseClient_2 = require_SupabaseClient(); + Object.defineProperty(exports, "SupabaseClient", { enumerable: true, get: function() { + return __importDefault2(SupabaseClient_2).default; + } }); + var createClient2 = (supabaseUrl, supabaseKey, options) => { + return new SupabaseClient_1.default(supabaseUrl, supabaseKey, options); + }; + exports.createClient = createClient2; + function shouldShowDeprecationWarning() { + if (typeof window !== "undefined") { + return false; + } + if (typeof process === "undefined") { + return false; + } + const processVersion = process["version"]; + if (processVersion === void 0 || processVersion === null) { + return false; + } + const versionMatch = processVersion.match(/^v(\d+)\./); + if (!versionMatch) { + return false; + } + const majorVersion = parseInt(versionMatch[1], 10); + return majorVersion <= 18; + } + if (shouldShowDeprecationWarning()) { + console.warn(`\u26A0\uFE0F Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217`); + } + } +}); + +// node_modules/@langchain/langgraph/dist/errors.js +var BaseLangGraphError = class extends Error { + constructor(message, fields) { + let finalMessage = message ?? ""; + if (fields?.lc_error_code) { + finalMessage = `${finalMessage} + +Troubleshooting URL: https://langchain-ai.github.io/langgraphjs/troubleshooting/errors/${fields.lc_error_code}/ +`; + } + super(finalMessage); + Object.defineProperty(this, "lc_error_code", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.lc_error_code = fields?.lc_error_code; + } +}; +var GraphBubbleUp = class extends BaseLangGraphError { + get is_bubble_up() { + return true; + } +}; +var GraphRecursionError = class extends BaseLangGraphError { + constructor(message, fields) { + super(message, fields); + this.name = "GraphRecursionError"; + } + static get unminifiable_name() { + return "GraphRecursionError"; + } +}; +var GraphValueError = class extends BaseLangGraphError { + constructor(message, fields) { + super(message, fields); + this.name = "GraphValueError"; + } + static get unminifiable_name() { + return "GraphValueError"; + } +}; +var GraphInterrupt = class extends GraphBubbleUp { + constructor(interrupts, fields) { + super(JSON.stringify(interrupts, null, 2), fields); + Object.defineProperty(this, "interrupts", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.name = "GraphInterrupt"; + this.interrupts = interrupts ?? []; + } + static get unminifiable_name() { + return "GraphInterrupt"; + } +}; +var NodeInterrupt = class extends GraphInterrupt { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + constructor(message, fields) { + super([{ value: message }], fields); + this.name = "NodeInterrupt"; + } + static get unminifiable_name() { + return "NodeInterrupt"; + } +}; +var ParentCommand = class extends GraphBubbleUp { + constructor(command) { + super(); + Object.defineProperty(this, "command", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.name = "ParentCommand"; + this.command = command; + } + static get unminifiable_name() { + return "ParentCommand"; + } +}; +function isParentCommand(e) { + return e !== void 0 && e.name === ParentCommand.unminifiable_name; +} +function isGraphBubbleUp(e) { + return e !== void 0 && e.is_bubble_up === true; +} +function isGraphInterrupt(e) { + return e !== void 0 && [ + GraphInterrupt.unminifiable_name, + NodeInterrupt.unminifiable_name + ].includes(e.name); +} +var EmptyInputError = class extends BaseLangGraphError { + constructor(message, fields) { + super(message, fields); + this.name = "EmptyInputError"; + } + static get unminifiable_name() { + return "EmptyInputError"; + } +}; +var EmptyChannelError = class extends BaseLangGraphError { + constructor(message, fields) { + super(message, fields); + this.name = "EmptyChannelError"; + } + static get unminifiable_name() { + return "EmptyChannelError"; + } +}; +var InvalidUpdateError = class extends BaseLangGraphError { + constructor(message, fields) { + super(message, fields); + this.name = "InvalidUpdateError"; + } + static get unminifiable_name() { + return "InvalidUpdateError"; + } +}; +var UnreachableNodeError = class extends BaseLangGraphError { + constructor(message, fields) { + super(message, fields); + this.name = "UnreachableNodeError"; + } + static get unminifiable_name() { + return "UnreachableNodeError"; + } +}; + +// node_modules/@langchain/langgraph-checkpoint/dist/id.js +init_esm_browser(); +function uuid6(clockseq) { + return v6({ clockseq }); +} +function uuid5(name, namespace) { + const namespaceBytes = namespace.replace(/-/g, "").match(/.{2}/g).map((byte) => parseInt(byte, 16)); + return v5_default(name, new Uint8Array(namespaceBytes)); +} + +// node_modules/@langchain/langgraph-checkpoint/dist/serde/types.js +var ERROR2 = "__error__"; +var SCHEDULED = "__scheduled__"; +var INTERRUPT = "__interrupt__"; +var RESUME = "__resume__"; + +// node_modules/@langchain/core/dist/load/index.js +init_serializable(); + +// node_modules/@langchain/core/dist/load/import_constants.js +var optionalImportEntrypoints = []; + +// node_modules/@langchain/core/dist/load/import_map.js +var import_map_exports = {}; +__export(import_map_exports, { + agents: () => agents_exports, + caches: () => base_exports, + callbacks__base: () => base_exports2, + callbacks__manager: () => manager_exports, + callbacks__promises: () => promises_exports, + chat_history: () => chat_history_exports, + documents: () => documents_exports, + embeddings: () => embeddings_exports, + example_selectors: () => example_selectors_exports, + language_models__base: () => base_exports4, + language_models__chat_models: () => chat_models_exports, + language_models__llms: () => llms_exports, + load__serializable: () => serializable_exports, + memory: () => memory_exports, + messages: () => messages_exports, + output_parsers: () => output_parsers_exports, + outputs: () => outputs_exports, + prompt_values: () => prompt_values_exports, + prompts: () => prompts_exports, + retrievers: () => retrievers_exports, + runnables: () => runnables_exports, + stores: () => stores_exports, + tools: () => tools_exports, + tracers__base: () => base_exports3, + tracers__console: () => console_exports, + tracers__initialize: () => initialize_exports, + tracers__log_stream: () => log_stream_exports, + tracers__run_collector: () => run_collector_exports, + tracers__tracer_langchain: () => tracer_langchain_exports, + tracers__tracer_langchain_v1: () => tracer_langchain_v1_exports, + utils__async_caller: () => async_caller_exports, + utils__chunk_array: () => chunk_array_exports, + utils__env: () => env_exports, + utils__function_calling: () => function_calling_exports, + utils__hash: () => hash_exports, + utils__json_patch: () => json_patch_exports, + utils__json_schema: () => json_schema_exports2, + utils__math: () => math_exports, + utils__stream: () => stream_exports, + utils__testing: () => testing_exports, + utils__tiktoken: () => tiktoken_exports, + utils__types: () => types_exports, + vectorstores: () => vectorstores_exports +}); + +// node_modules/@langchain/core/dist/agents.js +var agents_exports = {}; + +// node_modules/@langchain/core/dist/caches/base.js +var base_exports = {}; +__export(base_exports, { + BaseCache: () => BaseCache, + InMemoryCache: () => InMemoryCache, + deserializeStoredGeneration: () => deserializeStoredGeneration, + getCacheKey: () => getCacheKey, + serializeGeneration: () => serializeGeneration +}); + +// node_modules/@langchain/core/dist/utils/hash.js +var hash_exports = {}; +__export(hash_exports, { + insecureHash: () => insecureHash, + sha256: () => sha256 +}); + +// node_modules/@langchain/core/dist/utils/js-sha1/hash.js +var root = typeof window === "object" ? window : {}; +var HEX_CHARS = "0123456789abcdef".split(""); +var EXTRA = [-2147483648, 8388608, 32768, 128]; +var SHIFT = [24, 16, 8, 0]; +var blocks = []; +function Sha1(sharedMemory) { + if (sharedMemory) { + blocks[0] = blocks[16] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0; + this.blocks = blocks; + } else { + this.blocks = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + } + this.h0 = 1732584193; + this.h1 = 4023233417; + this.h2 = 2562383102; + this.h3 = 271733878; + this.h4 = 3285377520; + this.block = this.start = this.bytes = this.hBytes = 0; + this.finalized = this.hashed = false; + this.first = true; +} +Sha1.prototype.update = function(message) { + if (this.finalized) { + return; + } + var notString = typeof message !== "string"; + if (notString && message.constructor === root.ArrayBuffer) { + message = new Uint8Array(message); + } + var code, index2 = 0, i, length = message.length || 0, blocks3 = this.blocks; + while (index2 < length) { + if (this.hashed) { + this.hashed = false; + blocks3[0] = this.block; + blocks3[16] = blocks3[1] = blocks3[2] = blocks3[3] = blocks3[4] = blocks3[5] = blocks3[6] = blocks3[7] = blocks3[8] = blocks3[9] = blocks3[10] = blocks3[11] = blocks3[12] = blocks3[13] = blocks3[14] = blocks3[15] = 0; + } + if (notString) { + for (i = this.start; index2 < length && i < 64; ++index2) { + blocks3[i >> 2] |= message[index2] << SHIFT[i++ & 3]; + } + } else { + for (i = this.start; index2 < length && i < 64; ++index2) { + code = message.charCodeAt(index2); + if (code < 128) { + blocks3[i >> 2] |= code << SHIFT[i++ & 3]; + } else if (code < 2048) { + blocks3[i >> 2] |= (192 | code >> 6) << SHIFT[i++ & 3]; + blocks3[i >> 2] |= (128 | code & 63) << SHIFT[i++ & 3]; + } else if (code < 55296 || code >= 57344) { + blocks3[i >> 2] |= (224 | code >> 12) << SHIFT[i++ & 3]; + blocks3[i >> 2] |= (128 | code >> 6 & 63) << SHIFT[i++ & 3]; + blocks3[i >> 2] |= (128 | code & 63) << SHIFT[i++ & 3]; + } else { + code = 65536 + ((code & 1023) << 10 | message.charCodeAt(++index2) & 1023); + blocks3[i >> 2] |= (240 | code >> 18) << SHIFT[i++ & 3]; + blocks3[i >> 2] |= (128 | code >> 12 & 63) << SHIFT[i++ & 3]; + blocks3[i >> 2] |= (128 | code >> 6 & 63) << SHIFT[i++ & 3]; + blocks3[i >> 2] |= (128 | code & 63) << SHIFT[i++ & 3]; + } + } + } + this.lastByteIndex = i; + this.bytes += i - this.start; + if (i >= 64) { + this.block = blocks3[16]; + this.start = i - 64; + this.hash(); + this.hashed = true; + } else { + this.start = i; + } + } + if (this.bytes > 4294967295) { + this.hBytes += this.bytes / 4294967296 << 0; + this.bytes = this.bytes % 4294967296; + } + return this; +}; +Sha1.prototype.finalize = function() { + if (this.finalized) { + return; + } + this.finalized = true; + var blocks3 = this.blocks, i = this.lastByteIndex; + blocks3[16] = this.block; + blocks3[i >> 2] |= EXTRA[i & 3]; + this.block = blocks3[16]; + if (i >= 56) { + if (!this.hashed) { + this.hash(); + } + blocks3[0] = this.block; + blocks3[16] = blocks3[1] = blocks3[2] = blocks3[3] = blocks3[4] = blocks3[5] = blocks3[6] = blocks3[7] = blocks3[8] = blocks3[9] = blocks3[10] = blocks3[11] = blocks3[12] = blocks3[13] = blocks3[14] = blocks3[15] = 0; + } + blocks3[14] = this.hBytes << 3 | this.bytes >>> 29; + blocks3[15] = this.bytes << 3; + this.hash(); +}; +Sha1.prototype.hash = function() { + var a = this.h0, b = this.h1, c = this.h2, d = this.h3, e = this.h4; + var f2, j, t, blocks3 = this.blocks; + for (j = 16; j < 80; ++j) { + t = blocks3[j - 3] ^ blocks3[j - 8] ^ blocks3[j - 14] ^ blocks3[j - 16]; + blocks3[j] = t << 1 | t >>> 31; + } + for (j = 0; j < 20; j += 5) { + f2 = b & c | ~b & d; + t = a << 5 | a >>> 27; + e = t + f2 + e + 1518500249 + blocks3[j] << 0; + b = b << 30 | b >>> 2; + f2 = a & b | ~a & c; + t = e << 5 | e >>> 27; + d = t + f2 + d + 1518500249 + blocks3[j + 1] << 0; + a = a << 30 | a >>> 2; + f2 = e & a | ~e & b; + t = d << 5 | d >>> 27; + c = t + f2 + c + 1518500249 + blocks3[j + 2] << 0; + e = e << 30 | e >>> 2; + f2 = d & e | ~d & a; + t = c << 5 | c >>> 27; + b = t + f2 + b + 1518500249 + blocks3[j + 3] << 0; + d = d << 30 | d >>> 2; + f2 = c & d | ~c & e; + t = b << 5 | b >>> 27; + a = t + f2 + a + 1518500249 + blocks3[j + 4] << 0; + c = c << 30 | c >>> 2; + } + for (; j < 40; j += 5) { + f2 = b ^ c ^ d; + t = a << 5 | a >>> 27; + e = t + f2 + e + 1859775393 + blocks3[j] << 0; + b = b << 30 | b >>> 2; + f2 = a ^ b ^ c; + t = e << 5 | e >>> 27; + d = t + f2 + d + 1859775393 + blocks3[j + 1] << 0; + a = a << 30 | a >>> 2; + f2 = e ^ a ^ b; + t = d << 5 | d >>> 27; + c = t + f2 + c + 1859775393 + blocks3[j + 2] << 0; + e = e << 30 | e >>> 2; + f2 = d ^ e ^ a; + t = c << 5 | c >>> 27; + b = t + f2 + b + 1859775393 + blocks3[j + 3] << 0; + d = d << 30 | d >>> 2; + f2 = c ^ d ^ e; + t = b << 5 | b >>> 27; + a = t + f2 + a + 1859775393 + blocks3[j + 4] << 0; + c = c << 30 | c >>> 2; + } + for (; j < 60; j += 5) { + f2 = b & c | b & d | c & d; + t = a << 5 | a >>> 27; + e = t + f2 + e - 1894007588 + blocks3[j] << 0; + b = b << 30 | b >>> 2; + f2 = a & b | a & c | b & c; + t = e << 5 | e >>> 27; + d = t + f2 + d - 1894007588 + blocks3[j + 1] << 0; + a = a << 30 | a >>> 2; + f2 = e & a | e & b | a & b; + t = d << 5 | d >>> 27; + c = t + f2 + c - 1894007588 + blocks3[j + 2] << 0; + e = e << 30 | e >>> 2; + f2 = d & e | d & a | e & a; + t = c << 5 | c >>> 27; + b = t + f2 + b - 1894007588 + blocks3[j + 3] << 0; + d = d << 30 | d >>> 2; + f2 = c & d | c & e | d & e; + t = b << 5 | b >>> 27; + a = t + f2 + a - 1894007588 + blocks3[j + 4] << 0; + c = c << 30 | c >>> 2; + } + for (; j < 80; j += 5) { + f2 = b ^ c ^ d; + t = a << 5 | a >>> 27; + e = t + f2 + e - 899497514 + blocks3[j] << 0; + b = b << 30 | b >>> 2; + f2 = a ^ b ^ c; + t = e << 5 | e >>> 27; + d = t + f2 + d - 899497514 + blocks3[j + 1] << 0; + a = a << 30 | a >>> 2; + f2 = e ^ a ^ b; + t = d << 5 | d >>> 27; + c = t + f2 + c - 899497514 + blocks3[j + 2] << 0; + e = e << 30 | e >>> 2; + f2 = d ^ e ^ a; + t = c << 5 | c >>> 27; + b = t + f2 + b - 899497514 + blocks3[j + 3] << 0; + d = d << 30 | d >>> 2; + f2 = c ^ d ^ e; + t = b << 5 | b >>> 27; + a = t + f2 + a - 899497514 + blocks3[j + 4] << 0; + c = c << 30 | c >>> 2; + } + this.h0 = this.h0 + a << 0; + this.h1 = this.h1 + b << 0; + this.h2 = this.h2 + c << 0; + this.h3 = this.h3 + d << 0; + this.h4 = this.h4 + e << 0; +}; +Sha1.prototype.hex = function() { + this.finalize(); + var h0 = this.h0, h1 = this.h1, h2 = this.h2, h3 = this.h3, h4 = this.h4; + return HEX_CHARS[h0 >> 28 & 15] + HEX_CHARS[h0 >> 24 & 15] + HEX_CHARS[h0 >> 20 & 15] + HEX_CHARS[h0 >> 16 & 15] + HEX_CHARS[h0 >> 12 & 15] + HEX_CHARS[h0 >> 8 & 15] + HEX_CHARS[h0 >> 4 & 15] + HEX_CHARS[h0 & 15] + HEX_CHARS[h1 >> 28 & 15] + HEX_CHARS[h1 >> 24 & 15] + HEX_CHARS[h1 >> 20 & 15] + HEX_CHARS[h1 >> 16 & 15] + HEX_CHARS[h1 >> 12 & 15] + HEX_CHARS[h1 >> 8 & 15] + HEX_CHARS[h1 >> 4 & 15] + HEX_CHARS[h1 & 15] + HEX_CHARS[h2 >> 28 & 15] + HEX_CHARS[h2 >> 24 & 15] + HEX_CHARS[h2 >> 20 & 15] + HEX_CHARS[h2 >> 16 & 15] + HEX_CHARS[h2 >> 12 & 15] + HEX_CHARS[h2 >> 8 & 15] + HEX_CHARS[h2 >> 4 & 15] + HEX_CHARS[h2 & 15] + HEX_CHARS[h3 >> 28 & 15] + HEX_CHARS[h3 >> 24 & 15] + HEX_CHARS[h3 >> 20 & 15] + HEX_CHARS[h3 >> 16 & 15] + HEX_CHARS[h3 >> 12 & 15] + HEX_CHARS[h3 >> 8 & 15] + HEX_CHARS[h3 >> 4 & 15] + HEX_CHARS[h3 & 15] + HEX_CHARS[h4 >> 28 & 15] + HEX_CHARS[h4 >> 24 & 15] + HEX_CHARS[h4 >> 20 & 15] + HEX_CHARS[h4 >> 16 & 15] + HEX_CHARS[h4 >> 12 & 15] + HEX_CHARS[h4 >> 8 & 15] + HEX_CHARS[h4 >> 4 & 15] + HEX_CHARS[h4 & 15]; +}; +Sha1.prototype.toString = Sha1.prototype.hex; +Sha1.prototype.digest = function() { + this.finalize(); + var h0 = this.h0, h1 = this.h1, h2 = this.h2, h3 = this.h3, h4 = this.h4; + return [ + h0 >> 24 & 255, + h0 >> 16 & 255, + h0 >> 8 & 255, + h0 & 255, + h1 >> 24 & 255, + h1 >> 16 & 255, + h1 >> 8 & 255, + h1 & 255, + h2 >> 24 & 255, + h2 >> 16 & 255, + h2 >> 8 & 255, + h2 & 255, + h3 >> 24 & 255, + h3 >> 16 & 255, + h3 >> 8 & 255, + h3 & 255, + h4 >> 24 & 255, + h4 >> 16 & 255, + h4 >> 8 & 255, + h4 & 255 + ]; +}; +Sha1.prototype.array = Sha1.prototype.digest; +Sha1.prototype.arrayBuffer = function() { + this.finalize(); + var buffer = new ArrayBuffer(20); + var dataView = new DataView(buffer); + dataView.setUint32(0, this.h0); + dataView.setUint32(4, this.h1); + dataView.setUint32(8, this.h2); + dataView.setUint32(12, this.h3); + dataView.setUint32(16, this.h4); + return buffer; +}; +var hasLoggedWarning = false; +var insecureHash = (message) => { + if (!hasLoggedWarning) { + console.warn([ + `The default method for hashing keys is insecure and will be replaced in a future version,`, + `but hasn't been replaced yet as to not break existing caches. It's recommended that you use`, + `a more secure hashing algorithm to avoid cache poisoning.`, + ``, + `See this page for more information:`, + `|`, + `\u2514> https://js.langchain.com/docs/troubleshooting/warnings/insecure-cache-algorithm` + ].join("\n")); + hasLoggedWarning = true; + } + return new Sha1(true).update(message)["hex"](); +}; + +// node_modules/@langchain/core/dist/utils/js-sha256/hash.js +var HEX_CHARS2 = "0123456789abcdef".split(""); +var EXTRA2 = [-2147483648, 8388608, 32768, 128]; +var SHIFT2 = [24, 16, 8, 0]; +var K = [ + 1116352408, + 1899447441, + 3049323471, + 3921009573, + 961987163, + 1508970993, + 2453635748, + 2870763221, + 3624381080, + 310598401, + 607225278, + 1426881987, + 1925078388, + 2162078206, + 2614888103, + 3248222580, + 3835390401, + 4022224774, + 264347078, + 604807628, + 770255983, + 1249150122, + 1555081692, + 1996064986, + 2554220882, + 2821834349, + 2952996808, + 3210313671, + 3336571891, + 3584528711, + 113926993, + 338241895, + 666307205, + 773529912, + 1294757372, + 1396182291, + 1695183700, + 1986661051, + 2177026350, + 2456956037, + 2730485921, + 2820302411, + 3259730800, + 3345764771, + 3516065817, + 3600352804, + 4094571909, + 275423344, + 430227734, + 506948616, + 659060556, + 883997877, + 958139571, + 1322822218, + 1537002063, + 1747873779, + 1955562222, + 2024104815, + 2227730452, + 2361852424, + 2428436474, + 2756734187, + 3204031479, + 3329325298 +]; +var blocks2 = []; +function Sha256(is224, sharedMemory) { + if (sharedMemory) { + blocks2[0] = blocks2[16] = blocks2[1] = blocks2[2] = blocks2[3] = blocks2[4] = blocks2[5] = blocks2[6] = blocks2[7] = blocks2[8] = blocks2[9] = blocks2[10] = blocks2[11] = blocks2[12] = blocks2[13] = blocks2[14] = blocks2[15] = 0; + this.blocks = blocks2; + } else { + this.blocks = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + } + if (is224) { + this.h0 = 3238371032; + this.h1 = 914150663; + this.h2 = 812702999; + this.h3 = 4144912697; + this.h4 = 4290775857; + this.h5 = 1750603025; + this.h6 = 1694076839; + this.h7 = 3204075428; + } else { + this.h0 = 1779033703; + this.h1 = 3144134277; + this.h2 = 1013904242; + this.h3 = 2773480762; + this.h4 = 1359893119; + this.h5 = 2600822924; + this.h6 = 528734635; + this.h7 = 1541459225; + } + this.block = this.start = this.bytes = this.hBytes = 0; + this.finalized = this.hashed = false; + this.first = true; + this.is224 = is224; +} +Sha256.prototype.update = function(message) { + if (this.finalized) { + return; + } + var notString, type = typeof message; + if (type !== "string") { + if (type === "object") { + if (message === null) { + throw new Error(ERROR); + } else if (ARRAY_BUFFER && message.constructor === ArrayBuffer) { + message = new Uint8Array(message); + } else if (!Array.isArray(message)) { + if (!ARRAY_BUFFER || !ArrayBuffer.isView(message)) { + throw new Error(ERROR); + } + } + } else { + throw new Error(ERROR); + } + notString = true; + } + var code, index2 = 0, i, length = message.length, blocks3 = this.blocks; + while (index2 < length) { + if (this.hashed) { + this.hashed = false; + blocks3[0] = this.block; + this.block = blocks3[16] = blocks3[1] = blocks3[2] = blocks3[3] = blocks3[4] = blocks3[5] = blocks3[6] = blocks3[7] = blocks3[8] = blocks3[9] = blocks3[10] = blocks3[11] = blocks3[12] = blocks3[13] = blocks3[14] = blocks3[15] = 0; + } + if (notString) { + for (i = this.start; index2 < length && i < 64; ++index2) { + blocks3[i >>> 2] |= message[index2] << SHIFT2[i++ & 3]; + } + } else { + for (i = this.start; index2 < length && i < 64; ++index2) { + code = message.charCodeAt(index2); + if (code < 128) { + blocks3[i >>> 2] |= code << SHIFT2[i++ & 3]; + } else if (code < 2048) { + blocks3[i >>> 2] |= (192 | code >>> 6) << SHIFT2[i++ & 3]; + blocks3[i >>> 2] |= (128 | code & 63) << SHIFT2[i++ & 3]; + } else if (code < 55296 || code >= 57344) { + blocks3[i >>> 2] |= (224 | code >>> 12) << SHIFT2[i++ & 3]; + blocks3[i >>> 2] |= (128 | code >>> 6 & 63) << SHIFT2[i++ & 3]; + blocks3[i >>> 2] |= (128 | code & 63) << SHIFT2[i++ & 3]; + } else { + code = 65536 + ((code & 1023) << 10 | message.charCodeAt(++index2) & 1023); + blocks3[i >>> 2] |= (240 | code >>> 18) << SHIFT2[i++ & 3]; + blocks3[i >>> 2] |= (128 | code >>> 12 & 63) << SHIFT2[i++ & 3]; + blocks3[i >>> 2] |= (128 | code >>> 6 & 63) << SHIFT2[i++ & 3]; + blocks3[i >>> 2] |= (128 | code & 63) << SHIFT2[i++ & 3]; + } + } + } + this.lastByteIndex = i; + this.bytes += i - this.start; + if (i >= 64) { + this.block = blocks3[16]; + this.start = i - 64; + this.hash(); + this.hashed = true; + } else { + this.start = i; + } + } + if (this.bytes > 4294967295) { + this.hBytes += this.bytes / 4294967296 << 0; + this.bytes = this.bytes % 4294967296; + } + return this; +}; +Sha256.prototype.finalize = function() { + if (this.finalized) { + return; + } + this.finalized = true; + var blocks3 = this.blocks, i = this.lastByteIndex; + blocks3[16] = this.block; + blocks3[i >>> 2] |= EXTRA2[i & 3]; + this.block = blocks3[16]; + if (i >= 56) { + if (!this.hashed) { + this.hash(); + } + blocks3[0] = this.block; + blocks3[16] = blocks3[1] = blocks3[2] = blocks3[3] = blocks3[4] = blocks3[5] = blocks3[6] = blocks3[7] = blocks3[8] = blocks3[9] = blocks3[10] = blocks3[11] = blocks3[12] = blocks3[13] = blocks3[14] = blocks3[15] = 0; + } + blocks3[14] = this.hBytes << 3 | this.bytes >>> 29; + blocks3[15] = this.bytes << 3; + this.hash(); +}; +Sha256.prototype.hash = function() { + var a = this.h0, b = this.h1, c = this.h2, d = this.h3, e = this.h4, f2 = this.h5, g = this.h6, h = this.h7, blocks3 = this.blocks, j, s0, s1, maj, t1, t2, ch, ab, da, cd, bc; + for (j = 16; j < 64; ++j) { + t1 = blocks3[j - 15]; + s0 = (t1 >>> 7 | t1 << 25) ^ (t1 >>> 18 | t1 << 14) ^ t1 >>> 3; + t1 = blocks3[j - 2]; + s1 = (t1 >>> 17 | t1 << 15) ^ (t1 >>> 19 | t1 << 13) ^ t1 >>> 10; + blocks3[j] = blocks3[j - 16] + s0 + blocks3[j - 7] + s1 << 0; + } + bc = b & c; + for (j = 0; j < 64; j += 4) { + if (this.first) { + if (this.is224) { + ab = 300032; + t1 = blocks3[0] - 1413257819; + h = t1 - 150054599 << 0; + d = t1 + 24177077 << 0; + } else { + ab = 704751109; + t1 = blocks3[0] - 210244248; + h = t1 - 1521486534 << 0; + d = t1 + 143694565 << 0; + } + this.first = false; + } else { + s0 = (a >>> 2 | a << 30) ^ (a >>> 13 | a << 19) ^ (a >>> 22 | a << 10); + s1 = (e >>> 6 | e << 26) ^ (e >>> 11 | e << 21) ^ (e >>> 25 | e << 7); + ab = a & b; + maj = ab ^ a & c ^ bc; + ch = e & f2 ^ ~e & g; + t1 = h + s1 + ch + K[j] + blocks3[j]; + t2 = s0 + maj; + h = d + t1 << 0; + d = t1 + t2 << 0; + } + s0 = (d >>> 2 | d << 30) ^ (d >>> 13 | d << 19) ^ (d >>> 22 | d << 10); + s1 = (h >>> 6 | h << 26) ^ (h >>> 11 | h << 21) ^ (h >>> 25 | h << 7); + da = d & a; + maj = da ^ d & b ^ ab; + ch = g & h ^ ~g & e; + t1 = f2 + s1 + ch + K[j + 1] + blocks3[j + 1]; + t2 = s0 + maj; + g = c + t1 << 0; + c = t1 + t2 << 0; + s0 = (c >>> 2 | c << 30) ^ (c >>> 13 | c << 19) ^ (c >>> 22 | c << 10); + s1 = (g >>> 6 | g << 26) ^ (g >>> 11 | g << 21) ^ (g >>> 25 | g << 7); + cd = c & d; + maj = cd ^ c & a ^ da; + ch = f2 & g ^ ~f2 & h; + t1 = e + s1 + ch + K[j + 2] + blocks3[j + 2]; + t2 = s0 + maj; + f2 = b + t1 << 0; + b = t1 + t2 << 0; + s0 = (b >>> 2 | b << 30) ^ (b >>> 13 | b << 19) ^ (b >>> 22 | b << 10); + s1 = (f2 >>> 6 | f2 << 26) ^ (f2 >>> 11 | f2 << 21) ^ (f2 >>> 25 | f2 << 7); + bc = b & c; + maj = bc ^ b & d ^ cd; + ch = f2 & g ^ ~f2 & h; + t1 = e + s1 + ch + K[j + 3] + blocks3[j + 3]; + t2 = s0 + maj; + e = a + t1 << 0; + a = t1 + t2 << 0; + this.chromeBugWorkAround = true; + } + this.h0 = this.h0 + a << 0; + this.h1 = this.h1 + b << 0; + this.h2 = this.h2 + c << 0; + this.h3 = this.h3 + d << 0; + this.h4 = this.h4 + e << 0; + this.h5 = this.h5 + f2 << 0; + this.h6 = this.h6 + g << 0; + this.h7 = this.h7 + h << 0; +}; +Sha256.prototype.hex = function() { + this.finalize(); + var h0 = this.h0, h1 = this.h1, h2 = this.h2, h3 = this.h3, h4 = this.h4, h5 = this.h5, h6 = this.h6, h7 = this.h7; + var hex = HEX_CHARS2[h0 >>> 28 & 15] + HEX_CHARS2[h0 >>> 24 & 15] + HEX_CHARS2[h0 >>> 20 & 15] + HEX_CHARS2[h0 >>> 16 & 15] + HEX_CHARS2[h0 >>> 12 & 15] + HEX_CHARS2[h0 >>> 8 & 15] + HEX_CHARS2[h0 >>> 4 & 15] + HEX_CHARS2[h0 & 15] + HEX_CHARS2[h1 >>> 28 & 15] + HEX_CHARS2[h1 >>> 24 & 15] + HEX_CHARS2[h1 >>> 20 & 15] + HEX_CHARS2[h1 >>> 16 & 15] + HEX_CHARS2[h1 >>> 12 & 15] + HEX_CHARS2[h1 >>> 8 & 15] + HEX_CHARS2[h1 >>> 4 & 15] + HEX_CHARS2[h1 & 15] + HEX_CHARS2[h2 >>> 28 & 15] + HEX_CHARS2[h2 >>> 24 & 15] + HEX_CHARS2[h2 >>> 20 & 15] + HEX_CHARS2[h2 >>> 16 & 15] + HEX_CHARS2[h2 >>> 12 & 15] + HEX_CHARS2[h2 >>> 8 & 15] + HEX_CHARS2[h2 >>> 4 & 15] + HEX_CHARS2[h2 & 15] + HEX_CHARS2[h3 >>> 28 & 15] + HEX_CHARS2[h3 >>> 24 & 15] + HEX_CHARS2[h3 >>> 20 & 15] + HEX_CHARS2[h3 >>> 16 & 15] + HEX_CHARS2[h3 >>> 12 & 15] + HEX_CHARS2[h3 >>> 8 & 15] + HEX_CHARS2[h3 >>> 4 & 15] + HEX_CHARS2[h3 & 15] + HEX_CHARS2[h4 >>> 28 & 15] + HEX_CHARS2[h4 >>> 24 & 15] + HEX_CHARS2[h4 >>> 20 & 15] + HEX_CHARS2[h4 >>> 16 & 15] + HEX_CHARS2[h4 >>> 12 & 15] + HEX_CHARS2[h4 >>> 8 & 15] + HEX_CHARS2[h4 >>> 4 & 15] + HEX_CHARS2[h4 & 15] + HEX_CHARS2[h5 >>> 28 & 15] + HEX_CHARS2[h5 >>> 24 & 15] + HEX_CHARS2[h5 >>> 20 & 15] + HEX_CHARS2[h5 >>> 16 & 15] + HEX_CHARS2[h5 >>> 12 & 15] + HEX_CHARS2[h5 >>> 8 & 15] + HEX_CHARS2[h5 >>> 4 & 15] + HEX_CHARS2[h5 & 15] + HEX_CHARS2[h6 >>> 28 & 15] + HEX_CHARS2[h6 >>> 24 & 15] + HEX_CHARS2[h6 >>> 20 & 15] + HEX_CHARS2[h6 >>> 16 & 15] + HEX_CHARS2[h6 >>> 12 & 15] + HEX_CHARS2[h6 >>> 8 & 15] + HEX_CHARS2[h6 >>> 4 & 15] + HEX_CHARS2[h6 & 15]; + if (!this.is224) { + hex += HEX_CHARS2[h7 >>> 28 & 15] + HEX_CHARS2[h7 >>> 24 & 15] + HEX_CHARS2[h7 >>> 20 & 15] + HEX_CHARS2[h7 >>> 16 & 15] + HEX_CHARS2[h7 >>> 12 & 15] + HEX_CHARS2[h7 >>> 8 & 15] + HEX_CHARS2[h7 >>> 4 & 15] + HEX_CHARS2[h7 & 15]; + } + return hex; +}; +Sha256.prototype.toString = Sha256.prototype.hex; +Sha256.prototype.digest = function() { + this.finalize(); + var h0 = this.h0, h1 = this.h1, h2 = this.h2, h3 = this.h3, h4 = this.h4, h5 = this.h5, h6 = this.h6, h7 = this.h7; + var arr3 = [ + h0 >>> 24 & 255, + h0 >>> 16 & 255, + h0 >>> 8 & 255, + h0 & 255, + h1 >>> 24 & 255, + h1 >>> 16 & 255, + h1 >>> 8 & 255, + h1 & 255, + h2 >>> 24 & 255, + h2 >>> 16 & 255, + h2 >>> 8 & 255, + h2 & 255, + h3 >>> 24 & 255, + h3 >>> 16 & 255, + h3 >>> 8 & 255, + h3 & 255, + h4 >>> 24 & 255, + h4 >>> 16 & 255, + h4 >>> 8 & 255, + h4 & 255, + h5 >>> 24 & 255, + h5 >>> 16 & 255, + h5 >>> 8 & 255, + h5 & 255, + h6 >>> 24 & 255, + h6 >>> 16 & 255, + h6 >>> 8 & 255, + h6 & 255 + ]; + if (!this.is224) { + arr3.push(h7 >>> 24 & 255, h7 >>> 16 & 255, h7 >>> 8 & 255, h7 & 255); + } + return arr3; +}; +Sha256.prototype.array = Sha256.prototype.digest; +Sha256.prototype.arrayBuffer = function() { + this.finalize(); + var buffer = new ArrayBuffer(this.is224 ? 28 : 32); + var dataView = new DataView(buffer); + dataView.setUint32(0, this.h0); + dataView.setUint32(4, this.h1); + dataView.setUint32(8, this.h2); + dataView.setUint32(12, this.h3); + dataView.setUint32(16, this.h4); + dataView.setUint32(20, this.h5); + dataView.setUint32(24, this.h6); + if (!this.is224) { + dataView.setUint32(28, this.h7); + } + return buffer; +}; +var sha256 = (...strings) => { + return new Sha256(false, true).update(strings.join("")).hex(); +}; + +// node_modules/@langchain/core/dist/caches/base.js +init_utils2(); +var getCacheKey = (...strings) => insecureHash(strings.join("_")); +function deserializeStoredGeneration(storedGeneration) { + if (storedGeneration.message !== void 0) { + return { + text: storedGeneration.text, + message: mapStoredMessageToChatMessage(storedGeneration.message) + }; + } else { + return { text: storedGeneration.text }; + } +} +function serializeGeneration(generation) { + const serializedValue = { + text: generation.text + }; + if (generation.message !== void 0) { + serializedValue.message = generation.message.toDict(); + } + return serializedValue; +} +var BaseCache = class { + constructor() { + Object.defineProperty(this, "keyEncoder", { + enumerable: true, + configurable: true, + writable: true, + value: getCacheKey + }); + } + /** + * Sets a custom key encoder function for the cache. + * This function should take a prompt and an LLM key and return a string + * that will be used as the cache key. + * @param keyEncoderFn The custom key encoder function. + */ + makeDefaultKeyEncoder(keyEncoderFn) { + this.keyEncoder = keyEncoderFn; + } +}; +var GLOBAL_MAP = /* @__PURE__ */ new Map(); +var InMemoryCache = class _InMemoryCache extends BaseCache { + constructor(map) { + super(); + Object.defineProperty(this, "cache", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.cache = map ?? /* @__PURE__ */ new Map(); + } + /** + * Retrieves data from the cache using a prompt and an LLM key. If the + * data is not found, it returns null. + * @param prompt The prompt used to find the data. + * @param llmKey The LLM key used to find the data. + * @returns The data corresponding to the prompt and LLM key, or null if not found. + */ + lookup(prompt, llmKey) { + return Promise.resolve(this.cache.get(this.keyEncoder(prompt, llmKey)) ?? null); + } + /** + * Updates the cache with new data using a prompt and an LLM key. + * @param prompt The prompt used to store the data. + * @param llmKey The LLM key used to store the data. + * @param value The data to be stored. + */ + async update(prompt, llmKey, value) { + this.cache.set(this.keyEncoder(prompt, llmKey), value); + } + /** + * Returns a global instance of InMemoryCache using a predefined global + * map as the initial cache. + * @returns A global instance of InMemoryCache. + */ + static global() { + return new _InMemoryCache(GLOBAL_MAP); + } +}; + +// node_modules/@langchain/core/dist/load/import_map.js +init_base2(); +init_manager(); +init_promises(); + +// node_modules/@langchain/core/dist/chat_history.js +var chat_history_exports = {}; +__export(chat_history_exports, { + BaseChatMessageHistory: () => BaseChatMessageHistory, + BaseListChatMessageHistory: () => BaseListChatMessageHistory, + InMemoryChatMessageHistory: () => InMemoryChatMessageHistory +}); +init_serializable(); +init_messages2(); +var BaseChatMessageHistory = class extends Serializable { + /** + * Add a list of messages. + * + * Implementations should override this method to handle bulk addition of messages + * in an efficient manner to avoid unnecessary round-trips to the underlying store. + * + * @param messages - A list of BaseMessage objects to store. + */ + async addMessages(messages) { + for (const message of messages) { + await this.addMessage(message); + } + } +}; +var BaseListChatMessageHistory = class extends Serializable { + /** + * This is a convenience method for adding a human message string to the store. + * Please note that this is a convenience method. Code should favor the + * bulk addMessages interface instead to save on round-trips to the underlying + * persistence layer. + * This method may be deprecated in a future release. + */ + addUserMessage(message) { + return this.addMessage(new HumanMessage(message)); + } + /** @deprecated Use addAIMessage instead */ + addAIChatMessage(message) { + return this.addMessage(new AIMessage(message)); + } + /** + * This is a convenience method for adding an AI message string to the store. + * Please note that this is a convenience method. Code should favor the bulk + * addMessages interface instead to save on round-trips to the underlying + * persistence layer. + * This method may be deprecated in a future release. + */ + addAIMessage(message) { + return this.addMessage(new AIMessage(message)); + } + /** + * Add a list of messages. + * + * Implementations should override this method to handle bulk addition of messages + * in an efficient manner to avoid unnecessary round-trips to the underlying store. + * + * @param messages - A list of BaseMessage objects to store. + */ + async addMessages(messages) { + for (const message of messages) { + await this.addMessage(message); + } + } + /** + * Remove all messages from the store. + */ + clear() { + throw new Error("Not implemented."); + } +}; +var InMemoryChatMessageHistory = class extends BaseListChatMessageHistory { + constructor(messages) { + super(...arguments); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain", "stores", "message", "in_memory"] + }); + Object.defineProperty(this, "messages", { + enumerable: true, + configurable: true, + writable: true, + value: [] + }); + this.messages = messages ?? []; + } + /** + * Method to get all the messages stored in the ChatMessageHistory + * instance. + * @returns Array of stored BaseMessage instances. + */ + async getMessages() { + return this.messages; + } + /** + * Method to add a new message to the ChatMessageHistory instance. + * @param message The BaseMessage instance to add. + * @returns A promise that resolves when the message has been added. + */ + async addMessage(message) { + this.messages.push(message); + } + /** + * Method to clear all the messages from the ChatMessageHistory instance. + * @returns A promise that resolves when all messages have been cleared. + */ + async clear() { + this.messages = []; + } +}; + +// node_modules/@langchain/core/dist/documents/index.js +var documents_exports = {}; +__export(documents_exports, { + BaseDocumentTransformer: () => BaseDocumentTransformer, + Document: () => Document, + MappingDocumentTransformer: () => MappingDocumentTransformer +}); + +// node_modules/@langchain/core/dist/documents/document.js +var Document = class { + constructor(fields) { + Object.defineProperty(this, "pageContent", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "metadata", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "id", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.pageContent = fields.pageContent !== void 0 ? fields.pageContent.toString() : ""; + this.metadata = fields.metadata ?? {}; + this.id = fields.id; + } +}; + +// node_modules/@langchain/core/dist/documents/transformers.js +init_base4(); +var BaseDocumentTransformer = class extends Runnable { + constructor() { + super(...arguments); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain_core", "documents", "transformers"] + }); + } + /** + * Method to invoke the document transformation. This method calls the + * transformDocuments method with the provided input. + * @param input The input documents to be transformed. + * @param _options Optional configuration object to customize the behavior of callbacks. + * @returns A Promise that resolves to the transformed documents. + */ + invoke(input, _options) { + return this.transformDocuments(input); + } +}; +var MappingDocumentTransformer = class extends BaseDocumentTransformer { + async transformDocuments(documents) { + const newDocuments = []; + for (const document2 of documents) { + const transformedDocument = await this._transformDocument(document2); + newDocuments.push(transformedDocument); + } + return newDocuments; + } +}; + +// node_modules/@langchain/core/dist/embeddings.js +var embeddings_exports = {}; +__export(embeddings_exports, { + Embeddings: () => Embeddings +}); +init_async_caller2(); +var Embeddings = class { + constructor(params) { + Object.defineProperty(this, "caller", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.caller = new AsyncCaller2(params ?? {}); + } +}; + +// node_modules/@langchain/core/dist/example_selectors/index.js +var example_selectors_exports = {}; +__export(example_selectors_exports, { + BaseExampleSelector: () => BaseExampleSelector, + BasePromptSelector: () => BasePromptSelector, + ConditionalPromptSelector: () => ConditionalPromptSelector, + LengthBasedExampleSelector: () => LengthBasedExampleSelector, + SemanticSimilarityExampleSelector: () => SemanticSimilarityExampleSelector, + isChatModel: () => isChatModel, + isLLM: () => isLLM +}); + +// node_modules/@langchain/core/dist/example_selectors/base.js +init_serializable(); +var BaseExampleSelector = class extends Serializable { + constructor() { + super(...arguments); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain_core", "example_selectors", "base"] + }); + } +}; + +// node_modules/@langchain/core/dist/example_selectors/conditional.js +var BasePromptSelector = class { + /** + * Asynchronous version of `getPrompt` that also accepts an options object + * for partial variables. + * @param llm The language model for which to get a prompt. + * @param options Optional object for partial variables. + * @returns A Promise that resolves to a prompt template. + */ + async getPromptAsync(llm, options) { + const prompt = this.getPrompt(llm); + return prompt.partial(options?.partialVariables ?? {}); + } +}; +var ConditionalPromptSelector = class extends BasePromptSelector { + constructor(default_prompt, conditionals = []) { + super(); + Object.defineProperty(this, "defaultPrompt", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "conditionals", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.defaultPrompt = default_prompt; + this.conditionals = conditionals; + } + /** + * Method that selects a prompt based on a set of conditions. If none of + * the conditions are met, it returns the default prompt. + * @param llm The language model for which to get a prompt. + * @returns A prompt template. + */ + getPrompt(llm) { + for (const [condition, prompt] of this.conditionals) { + if (condition(llm)) { + return prompt; + } + } + return this.defaultPrompt; + } +}; +function isLLM(llm) { + return llm._modelType() === "base_llm"; +} +function isChatModel(llm) { + return llm._modelType() === "base_chat_model"; +} + +// node_modules/@langchain/core/dist/example_selectors/length_based.js +function getLengthBased(text) { + return text.split(/\n| /).length; +} +var LengthBasedExampleSelector = class _LengthBasedExampleSelector extends BaseExampleSelector { + constructor(data) { + super(data); + Object.defineProperty(this, "examples", { + enumerable: true, + configurable: true, + writable: true, + value: [] + }); + Object.defineProperty(this, "examplePrompt", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "getTextLength", { + enumerable: true, + configurable: true, + writable: true, + value: getLengthBased + }); + Object.defineProperty(this, "maxLength", { + enumerable: true, + configurable: true, + writable: true, + value: 2048 + }); + Object.defineProperty(this, "exampleTextLengths", { + enumerable: true, + configurable: true, + writable: true, + value: [] + }); + this.examplePrompt = data.examplePrompt; + this.maxLength = data.maxLength ?? 2048; + this.getTextLength = data.getTextLength ?? getLengthBased; + } + /** + * Adds an example to the list of examples and calculates its length. + * @param example The example to be added. + * @returns Promise that resolves when the example has been added and its length calculated. + */ + async addExample(example) { + this.examples.push(example); + const stringExample = await this.examplePrompt.format(example); + this.exampleTextLengths.push(this.getTextLength(stringExample)); + } + /** + * Calculates the lengths of the examples. + * @param v Array of lengths of the examples. + * @param values Instance of LengthBasedExampleSelector. + * @returns Promise that resolves with an array of lengths of the examples. + */ + async calculateExampleTextLengths(v, values) { + if (v.length > 0) { + return v; + } + const { examples, examplePrompt } = values; + const stringExamples = await Promise.all(examples.map((eg) => examplePrompt.format(eg))); + return stringExamples.map((eg) => this.getTextLength(eg)); + } + /** + * Selects examples until the total length of the selected examples + * reaches the maxLength. + * @param inputVariables The input variables for the examples. + * @returns Promise that resolves with an array of selected examples. + */ + async selectExamples(inputVariables) { + const inputs = Object.values(inputVariables).join(" "); + let remainingLength = this.maxLength - this.getTextLength(inputs); + let i = 0; + const examples = []; + while (remainingLength > 0 && i < this.examples.length) { + const newLength = remainingLength - this.exampleTextLengths[i]; + if (newLength < 0) { + break; + } else { + examples.push(this.examples[i]); + remainingLength = newLength; + } + i += 1; + } + return examples; + } + /** + * Creates a new instance of LengthBasedExampleSelector and adds a list of + * examples to it. + * @param examples Array of examples to be added. + * @param args Input parameters for the LengthBasedExampleSelector. + * @returns Promise that resolves with a new instance of LengthBasedExampleSelector with the examples added. + */ + static async fromExamples(examples, args) { + const selector = new _LengthBasedExampleSelector(args); + await Promise.all(examples.map((eg) => selector.addExample(eg))); + return selector; + } +}; + +// node_modules/@langchain/core/dist/example_selectors/semantic_similarity.js +function sortedValues(values) { + return Object.keys(values).sort().map((key) => values[key]); +} +var SemanticSimilarityExampleSelector = class _SemanticSimilarityExampleSelector extends BaseExampleSelector { + constructor(data) { + super(data); + Object.defineProperty(this, "vectorStoreRetriever", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "exampleKeys", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "inputKeys", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.exampleKeys = data.exampleKeys; + this.inputKeys = data.inputKeys; + if (data.vectorStore !== void 0) { + this.vectorStoreRetriever = data.vectorStore.asRetriever({ + k: data.k ?? 4, + filter: data.filter + }); + } else if (data.vectorStoreRetriever) { + this.vectorStoreRetriever = data.vectorStoreRetriever; + } else { + throw new Error(`You must specify one of "vectorStore" and "vectorStoreRetriever".`); + } + } + /** + * Method that adds a new example to the vectorStore. The example is + * converted to a string and added to the vectorStore as a document. + * @param example The example to be added to the vectorStore. + * @returns Promise that resolves when the example has been added to the vectorStore. + */ + async addExample(example) { + const inputKeys = this.inputKeys ?? Object.keys(example); + const stringExample = sortedValues(inputKeys.reduce((acc, key) => ({ ...acc, [key]: example[key] }), {})).join(" "); + await this.vectorStoreRetriever.addDocuments([ + new Document({ + pageContent: stringExample, + metadata: example + }) + ]); + } + /** + * Method that selects which examples to use based on semantic similarity. + * It performs a similarity search in the vectorStore using the input + * variables and returns the examples with the highest similarity. + * @param inputVariables The input variables used for the similarity search. + * @returns Promise that resolves with an array of the selected examples. + */ + async selectExamples(inputVariables) { + const inputKeys = this.inputKeys ?? Object.keys(inputVariables); + const query = sortedValues(inputKeys.reduce((acc, key) => ({ ...acc, [key]: inputVariables[key] }), {})).join(" "); + const exampleDocs = await this.vectorStoreRetriever.invoke(query); + const examples = exampleDocs.map((doc) => doc.metadata); + if (this.exampleKeys) { + return examples.map((example) => this.exampleKeys.reduce((acc, key) => ({ ...acc, [key]: example[key] }), {})); + } + return examples; + } + /** + * Static method that creates a new instance of + * SemanticSimilarityExampleSelector. It takes a list of examples, an + * instance of Embeddings, a VectorStore class, and an options object as + * parameters. It converts the examples to strings, creates a VectorStore + * from the strings and the embeddings, and returns a new + * SemanticSimilarityExampleSelector with the created VectorStore and the + * options provided. + * @param examples The list of examples to be used. + * @param embeddings The instance of Embeddings to be used. + * @param vectorStoreCls The VectorStore class to be used. + * @param options The options object for the SemanticSimilarityExampleSelector. + * @returns Promise that resolves with a new instance of SemanticSimilarityExampleSelector. + */ + static async fromExamples(examples, embeddings, vectorStoreCls, options = {}) { + const inputKeys = options.inputKeys ?? null; + const stringExamples = examples.map((example) => sortedValues(inputKeys ? inputKeys.reduce((acc, key) => ({ ...acc, [key]: example[key] }), {}) : example).join(" ")); + const vectorStore = await vectorStoreCls.fromTexts( + stringExamples, + examples, + // metadatas + embeddings, + options + ); + return new _SemanticSimilarityExampleSelector({ + vectorStore, + k: options.k ?? 4, + exampleKeys: options.exampleKeys, + inputKeys: options.inputKeys + }); + } +}; + +// node_modules/@langchain/core/dist/language_models/base.js +var base_exports4 = {}; +__export(base_exports4, { + BaseLangChain: () => BaseLangChain, + BaseLanguageModel: () => BaseLanguageModel, + calculateMaxTokens: () => calculateMaxTokens, + getEmbeddingContextSize: () => getEmbeddingContextSize, + getModelContextSize: () => getModelContextSize, + getModelNameForTiktoken: () => getModelNameForTiktoken, + isOpenAITool: () => isOpenAITool +}); +init_prompt_values(); +init_utils2(); +init_async_caller2(); + +// node_modules/@langchain/core/dist/utils/tiktoken.js +var tiktoken_exports = {}; +__export(tiktoken_exports, { + encodingForModel: () => encodingForModel, + getEncoding: () => getEncoding +}); + +// node_modules/js-tiktoken/dist/chunk-VL2OQCWN.js +var import_base64_js = __toESM(require_base64_js(), 1); +var __defProp2 = Object.defineProperty; +var __defNormalProp = (obj, key, value) => key in obj ? __defProp2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __publicField = (obj, key, value) => { + __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); + return value; +}; +function bytePairMerge(piece, ranks) { + let parts = Array.from( + { length: piece.length }, + (_, i) => ({ start: i, end: i + 1 }) + ); + while (parts.length > 1) { + let minRank = null; + for (let i = 0; i < parts.length - 1; i++) { + const slice = piece.slice(parts[i].start, parts[i + 1].end); + const rank = ranks.get(slice.join(",")); + if (rank == null) + continue; + if (minRank == null || rank < minRank[0]) { + minRank = [rank, i]; + } + } + if (minRank != null) { + const i = minRank[1]; + parts[i] = { start: parts[i].start, end: parts[i + 1].end }; + parts.splice(i + 1, 1); + } else { + break; + } + } + return parts; +} +function bytePairEncode(piece, ranks) { + if (piece.length === 1) + return [ranks.get(piece.join(","))]; + return bytePairMerge(piece, ranks).map((p) => ranks.get(piece.slice(p.start, p.end).join(","))).filter((x) => x != null); +} +function escapeRegex2(str) { + return str.replace(/[\\^$*+?.()|[\]{}]/g, "\\$&"); +} +var _Tiktoken = class { + /** @internal */ + specialTokens; + /** @internal */ + inverseSpecialTokens; + /** @internal */ + patStr; + /** @internal */ + textEncoder = new TextEncoder(); + /** @internal */ + textDecoder = new TextDecoder("utf-8"); + /** @internal */ + rankMap = /* @__PURE__ */ new Map(); + /** @internal */ + textMap = /* @__PURE__ */ new Map(); + constructor(ranks, extendedSpecialTokens) { + this.patStr = ranks.pat_str; + const uncompressed = ranks.bpe_ranks.split("\n").filter(Boolean).reduce((memo, x) => { + const [_, offsetStr, ...tokens] = x.split(" "); + const offset = Number.parseInt(offsetStr, 10); + tokens.forEach((token, i) => memo[token] = offset + i); + return memo; + }, {}); + for (const [token, rank] of Object.entries(uncompressed)) { + const bytes = import_base64_js.default.toByteArray(token); + this.rankMap.set(bytes.join(","), rank); + this.textMap.set(rank, bytes); + } + this.specialTokens = { ...ranks.special_tokens, ...extendedSpecialTokens }; + this.inverseSpecialTokens = Object.entries(this.specialTokens).reduce((memo, [text, rank]) => { + memo[rank] = this.textEncoder.encode(text); + return memo; + }, {}); + } + encode(text, allowedSpecial = [], disallowedSpecial = "all") { + const regexes = new RegExp(this.patStr, "ug"); + const specialRegex = _Tiktoken.specialTokenRegex( + Object.keys(this.specialTokens) + ); + const ret = []; + const allowedSpecialSet = new Set( + allowedSpecial === "all" ? Object.keys(this.specialTokens) : allowedSpecial + ); + const disallowedSpecialSet = new Set( + disallowedSpecial === "all" ? Object.keys(this.specialTokens).filter( + (x) => !allowedSpecialSet.has(x) + ) : disallowedSpecial + ); + if (disallowedSpecialSet.size > 0) { + const disallowedSpecialRegex = _Tiktoken.specialTokenRegex([ + ...disallowedSpecialSet + ]); + const specialMatch = text.match(disallowedSpecialRegex); + if (specialMatch != null) { + throw new Error( + `The text contains a special token that is not allowed: ${specialMatch[0]}` + ); + } + } + let start = 0; + while (true) { + let nextSpecial = null; + let startFind = start; + while (true) { + specialRegex.lastIndex = startFind; + nextSpecial = specialRegex.exec(text); + if (nextSpecial == null || allowedSpecialSet.has(nextSpecial[0])) + break; + startFind = nextSpecial.index + 1; + } + const end = nextSpecial?.index ?? text.length; + for (const match of text.substring(start, end).matchAll(regexes)) { + const piece = this.textEncoder.encode(match[0]); + const token2 = this.rankMap.get(piece.join(",")); + if (token2 != null) { + ret.push(token2); + continue; + } + ret.push(...bytePairEncode(piece, this.rankMap)); + } + if (nextSpecial == null) + break; + let token = this.specialTokens[nextSpecial[0]]; + ret.push(token); + start = nextSpecial.index + nextSpecial[0].length; + } + return ret; + } + decode(tokens) { + const res = []; + let length = 0; + for (let i2 = 0; i2 < tokens.length; ++i2) { + const token = tokens[i2]; + const bytes = this.textMap.get(token) ?? this.inverseSpecialTokens[token]; + if (bytes != null) { + res.push(bytes); + length += bytes.length; + } + } + const mergedArray = new Uint8Array(length); + let i = 0; + for (const bytes of res) { + mergedArray.set(bytes, i); + i += bytes.length; + } + return this.textDecoder.decode(mergedArray); + } +}; +var Tiktoken = _Tiktoken; +__publicField(Tiktoken, "specialTokenRegex", (tokens) => { + return new RegExp(tokens.map((i) => escapeRegex2(i)).join("|"), "g"); +}); +function getEncodingNameForModel(model) { + switch (model) { + case "gpt2": { + return "gpt2"; + } + case "code-cushman-001": + case "code-cushman-002": + case "code-davinci-001": + case "code-davinci-002": + case "cushman-codex": + case "davinci-codex": + case "davinci-002": + case "text-davinci-002": + case "text-davinci-003": { + return "p50k_base"; + } + case "code-davinci-edit-001": + case "text-davinci-edit-001": { + return "p50k_edit"; + } + case "ada": + case "babbage": + case "babbage-002": + case "code-search-ada-code-001": + case "code-search-babbage-code-001": + case "curie": + case "davinci": + case "text-ada-001": + case "text-babbage-001": + case "text-curie-001": + case "text-davinci-001": + case "text-search-ada-doc-001": + case "text-search-babbage-doc-001": + case "text-search-curie-doc-001": + case "text-search-davinci-doc-001": + case "text-similarity-ada-001": + case "text-similarity-babbage-001": + case "text-similarity-curie-001": + case "text-similarity-davinci-001": { + return "r50k_base"; + } + case "gpt-3.5-turbo-instruct-0914": + case "gpt-3.5-turbo-instruct": + case "gpt-3.5-turbo-16k-0613": + case "gpt-3.5-turbo-16k": + case "gpt-3.5-turbo-0613": + case "gpt-3.5-turbo-0301": + case "gpt-3.5-turbo": + case "gpt-4-32k-0613": + case "gpt-4-32k-0314": + case "gpt-4-32k": + case "gpt-4-0613": + case "gpt-4-0314": + case "gpt-4": + case "gpt-3.5-turbo-1106": + case "gpt-35-turbo": + case "gpt-4-1106-preview": + case "gpt-4-vision-preview": + case "gpt-3.5-turbo-0125": + case "gpt-4-turbo": + case "gpt-4-turbo-2024-04-09": + case "gpt-4-turbo-preview": + case "gpt-4-0125-preview": + case "text-embedding-ada-002": + case "text-embedding-3-small": + case "text-embedding-3-large": { + return "cl100k_base"; + } + case "gpt-4o": + case "gpt-4o-2024-05-13": + case "gpt-4o-2024-08-06": + case "gpt-4o-2024-11-20": + case "gpt-4o-mini-2024-07-18": + case "gpt-4o-mini": + case "gpt-4o-search-preview": + case "gpt-4o-search-preview-2025-03-11": + case "gpt-4o-mini-search-preview": + case "gpt-4o-mini-search-preview-2025-03-11": + case "gpt-4o-audio-preview": + case "gpt-4o-audio-preview-2024-12-17": + case "gpt-4o-audio-preview-2024-10-01": + case "gpt-4o-mini-audio-preview": + case "gpt-4o-mini-audio-preview-2024-12-17": + case "o1": + case "o1-2024-12-17": + case "o1-mini": + case "o1-mini-2024-09-12": + case "o1-preview": + case "o1-preview-2024-09-12": + case "o1-pro": + case "o1-pro-2025-03-19": + case "o3": + case "o3-2025-04-16": + case "o3-mini": + case "o3-mini-2025-01-31": + case "o4-mini": + case "o4-mini-2025-04-16": + case "chatgpt-4o-latest": + case "gpt-4o-realtime": + case "gpt-4o-realtime-preview-2024-10-01": + case "gpt-4o-realtime-preview-2024-12-17": + case "gpt-4o-mini-realtime-preview": + case "gpt-4o-mini-realtime-preview-2024-12-17": + case "gpt-4.1": + case "gpt-4.1-2025-04-14": + case "gpt-4.1-mini": + case "gpt-4.1-mini-2025-04-14": + case "gpt-4.1-nano": + case "gpt-4.1-nano-2025-04-14": + case "gpt-4.5-preview": + case "gpt-4.5-preview-2025-02-27": + case "gpt-5": + case "gpt-5-2025-08-07": + case "gpt-5-nano": + case "gpt-5-nano-2025-08-07": + case "gpt-5-mini": + case "gpt-5-mini-2025-08-07": + case "gpt-5-chat-latest": { + return "o200k_base"; + } + default: + throw new Error("Unknown model"); + } +} + +// node_modules/@langchain/core/dist/utils/tiktoken.js +init_async_caller2(); +var cache = {}; +var caller = /* @__PURE__ */ new AsyncCaller2({}); +async function getEncoding(encoding) { + if (!(encoding in cache)) { + cache[encoding] = caller.fetch(`https://tiktoken.pages.dev/js/${encoding}.json`).then((res) => res.json()).then((data) => new Tiktoken(data)).catch((e) => { + delete cache[encoding]; + throw e; + }); + } + return await cache[encoding]; +} +async function encodingForModel(model) { + return getEncoding(getEncodingNameForModel(model)); +} + +// node_modules/@langchain/core/dist/language_models/base.js +init_base4(); +var getModelNameForTiktoken = (modelName) => { + if (modelName.startsWith("gpt-3.5-turbo-16k")) { + return "gpt-3.5-turbo-16k"; + } + if (modelName.startsWith("gpt-3.5-turbo-")) { + return "gpt-3.5-turbo"; + } + if (modelName.startsWith("gpt-4-32k")) { + return "gpt-4-32k"; + } + if (modelName.startsWith("gpt-4-")) { + return "gpt-4"; + } + if (modelName.startsWith("gpt-4o")) { + return "gpt-4o"; + } + return modelName; +}; +var getEmbeddingContextSize = (modelName) => { + switch (modelName) { + case "text-embedding-ada-002": + return 8191; + default: + return 2046; + } +}; +var getModelContextSize = (modelName) => { + switch (getModelNameForTiktoken(modelName)) { + case "gpt-3.5-turbo-16k": + return 16384; + case "gpt-3.5-turbo": + return 4096; + case "gpt-4-32k": + return 32768; + case "gpt-4": + return 8192; + case "text-davinci-003": + return 4097; + case "text-curie-001": + return 2048; + case "text-babbage-001": + return 2048; + case "text-ada-001": + return 2048; + case "code-davinci-002": + return 8e3; + case "code-cushman-001": + return 2048; + default: + return 4097; + } +}; +function isOpenAITool(tool2) { + if (typeof tool2 !== "object" || !tool2) + return false; + if ("type" in tool2 && tool2.type === "function" && "function" in tool2 && typeof tool2.function === "object" && tool2.function && "name" in tool2.function && "parameters" in tool2.function) { + return true; + } + return false; +} +var calculateMaxTokens = async ({ prompt, modelName }) => { + let numTokens; + try { + numTokens = (await encodingForModel(getModelNameForTiktoken(modelName))).encode(prompt).length; + } catch (error) { + console.warn("Failed to calculate number of tokens, falling back to approximate count"); + numTokens = Math.ceil(prompt.length / 4); + } + const maxTokens = getModelContextSize(modelName); + return maxTokens - numTokens; +}; +var getVerbosity = () => false; +var BaseLangChain = class extends Runnable { + get lc_attributes() { + return { + callbacks: void 0, + verbose: void 0 + }; + } + constructor(params) { + super(params); + Object.defineProperty(this, "verbose", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "callbacks", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "tags", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "metadata", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.verbose = params.verbose ?? getVerbosity(); + this.callbacks = params.callbacks; + this.tags = params.tags ?? []; + this.metadata = params.metadata ?? {}; + } +}; +var BaseLanguageModel = class extends BaseLangChain { + /** + * Keys that the language model accepts as call options. + */ + get callKeys() { + return ["stop", "timeout", "signal", "tags", "metadata", "callbacks"]; + } + constructor({ callbacks, callbackManager, ...params }) { + const { cache: cache2, ...rest } = params; + super({ + callbacks: callbacks ?? callbackManager, + ...rest + }); + Object.defineProperty(this, "caller", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "cache", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "_encoding", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + if (typeof cache2 === "object") { + this.cache = cache2; + } else if (cache2) { + this.cache = InMemoryCache.global(); + } else { + this.cache = void 0; + } + this.caller = new AsyncCaller2(params ?? {}); + } + /** + * Get the number of tokens in the content. + * @param content The content to get the number of tokens for. + * @returns The number of tokens in the content. + */ + async getNumTokens(content) { + let textContent; + if (typeof content === "string") { + textContent = content; + } else { + textContent = content.map((item) => { + if (typeof item === "string") + return item; + if (item.type === "text" && "text" in item) + return item.text; + return ""; + }).join(""); + } + let numTokens = Math.ceil(textContent.length / 4); + if (!this._encoding) { + try { + this._encoding = await encodingForModel("modelName" in this ? getModelNameForTiktoken(this.modelName) : "gpt2"); + } catch (error) { + console.warn("Failed to calculate number of tokens, falling back to approximate count", error); + } + } + if (this._encoding) { + try { + numTokens = this._encoding.encode(textContent).length; + } catch (error) { + console.warn("Failed to calculate number of tokens, falling back to approximate count", error); + } + } + return numTokens; + } + static _convertInputToPromptValue(input) { + if (typeof input === "string") { + return new StringPromptValue(input); + } else if (Array.isArray(input)) { + return new ChatPromptValue(input.map(coerceMessageLikeToMessage)); + } else { + return input; + } + } + /** + * Get the identifying parameters of the LLM. + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + _identifyingParams() { + return {}; + } + /** + * Create a unique cache key for a specific call to a specific language model. + * @param callOptions Call options for the model + * @returns A unique cache key. + */ + _getSerializedCacheKeyParametersForCall({ config: config2, ...callOptions }) { + const params = { + ...this._identifyingParams(), + ...callOptions, + _type: this._llmType(), + _model: this._modelType() + }; + const filteredEntries = Object.entries(params).filter(([_, value]) => value !== void 0); + const serializedEntries = filteredEntries.map(([key, value]) => `${key}:${JSON.stringify(value)}`).sort().join(","); + return serializedEntries; + } + /** + * @deprecated + * Return a json-like object representing this LLM. + */ + serialize() { + return { + ...this._identifyingParams(), + _type: this._llmType(), + _model: this._modelType() + }; + } + /** + * @deprecated + * Load an LLM from a json-like object describing it. + */ + static async deserialize(_data) { + throw new Error("Use .toJSON() instead"); + } +}; + +// node_modules/@langchain/core/dist/language_models/chat_models.js +var chat_models_exports = {}; +__export(chat_models_exports, { + BaseChatModel: () => BaseChatModel, + SimpleChatModel: () => SimpleChatModel, + createChatMessageChunkEncoderStream: () => createChatMessageChunkEncoderStream +}); +init_messages2(); +init_outputs(); +init_manager(); +init_base4(); +init_stream(); + +// node_modules/@langchain/core/dist/runnables/passthrough.js +init_stream(); +init_base4(); +init_config(); +var RunnablePassthrough = class extends Runnable { + static lc_name() { + return "RunnablePassthrough"; + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain_core", "runnables"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "func", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + if (fields) { + this.func = fields.func; + } + } + async invoke(input, options) { + const config2 = ensureConfig(options); + if (this.func) { + await this.func(input, config2); + } + return this._callWithConfig((input2) => Promise.resolve(input2), input, config2); + } + async *transform(generator, options) { + const config2 = ensureConfig(options); + let finalOutput; + let finalOutputSupported = true; + for await (const chunk of this._transformStreamWithConfig(generator, (input) => input, config2)) { + yield chunk; + if (finalOutputSupported) { + if (finalOutput === void 0) { + finalOutput = chunk; + } else { + try { + finalOutput = concat(finalOutput, chunk); + } catch { + finalOutput = void 0; + finalOutputSupported = false; + } + } + } + } + if (this.func && finalOutput !== void 0) { + await this.func(finalOutput, config2); + } + } + /** + * A runnable that assigns key-value pairs to the input. + * + * The example below shows how you could use it with an inline function. + * + * @example + * ```typescript + * const prompt = + * PromptTemplate.fromTemplate(`Write a SQL query to answer the question using the following schema: {schema} + * Question: {question} + * SQL Query:`); + * + * // The `RunnablePassthrough.assign()` is used here to passthrough the input from the `.invoke()` + * // call (in this example it's the question), along with any inputs passed to the `.assign()` method. + * // In this case, we're passing the schema. + * const sqlQueryGeneratorChain = RunnableSequence.from([ + * RunnablePassthrough.assign({ + * schema: async () => db.getTableInfo(), + * }), + * prompt, + * new ChatOpenAI({ model: "gpt-4o-mini" }).withConfig({ stop: ["\nSQLResult:"] }), + * new StringOutputParser(), + * ]); + * const result = await sqlQueryGeneratorChain.invoke({ + * question: "How many employees are there?", + * }); + * ``` + */ + static assign(mapping) { + return new RunnableAssign(new RunnableMap({ steps: mapping })); + } +}; + +// node_modules/@langchain/core/dist/language_models/chat_models.js +init_zod2(); +init_base2(); +init_json_schema2(); +function createChatMessageChunkEncoderStream() { + const textEncoder = new TextEncoder(); + return new TransformStream({ + transform(chunk, controller) { + controller.enqueue(textEncoder.encode(typeof chunk.content === "string" ? chunk.content : JSON.stringify(chunk.content))); + } + }); +} +function _formatForTracing(messages) { + const messagesToTrace = []; + for (const message of messages) { + let messageToTrace = message; + if (Array.isArray(message.content)) { + for (let idx = 0; idx < message.content.length; idx++) { + const block = message.content[idx]; + if (isURLContentBlock(block) || isBase64ContentBlock(block)) { + if (messageToTrace === message) { + messageToTrace = new message.constructor({ + ...messageToTrace, + content: [ + ...message.content.slice(0, idx), + convertToOpenAIImageBlock(block), + ...message.content.slice(idx + 1) + ] + }); + } + } + } + } + messagesToTrace.push(messageToTrace); + } + return messagesToTrace; +} +var BaseChatModel = class _BaseChatModel extends BaseLanguageModel { + constructor(fields) { + super(fields); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain", "chat_models", this._llmType()] + }); + Object.defineProperty(this, "disableStreaming", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + } + _separateRunnableConfigFromCallOptionsCompat(options) { + const [runnableConfig, callOptions] = super._separateRunnableConfigFromCallOptions(options); + callOptions.signal = runnableConfig.signal; + return [runnableConfig, callOptions]; + } + /** + * Invokes the chat model with a single input. + * @param input The input for the language model. + * @param options The call options. + * @returns A Promise that resolves to a BaseMessageChunk. + */ + async invoke(input, options) { + const promptValue = _BaseChatModel._convertInputToPromptValue(input); + const result = await this.generatePrompt([promptValue], options, options?.callbacks); + const chatGeneration = result.generations[0][0]; + return chatGeneration.message; + } + // eslint-disable-next-line require-yield + async *_streamResponseChunks(_messages, _options, _runManager) { + throw new Error("Not implemented."); + } + async *_streamIterator(input, options) { + if (this._streamResponseChunks === _BaseChatModel.prototype._streamResponseChunks || this.disableStreaming) { + yield this.invoke(input, options); + } else { + const prompt = _BaseChatModel._convertInputToPromptValue(input); + const messages = prompt.toChatMessages(); + const [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptionsCompat(options); + const inheritableMetadata = { + ...runnableConfig.metadata, + ...this.getLsParams(callOptions) + }; + const callbackManager_ = await CallbackManager.configure(runnableConfig.callbacks, this.callbacks, runnableConfig.tags, this.tags, inheritableMetadata, this.metadata, { verbose: this.verbose }); + const extra = { + options: callOptions, + invocation_params: this?.invocationParams(callOptions), + batch_size: 1 + }; + const runManagers = await callbackManager_?.handleChatModelStart(this.toJSON(), [_formatForTracing(messages)], runnableConfig.runId, void 0, extra, void 0, void 0, runnableConfig.runName); + let generationChunk; + let llmOutput; + try { + for await (const chunk of this._streamResponseChunks(messages, callOptions, runManagers?.[0])) { + if (chunk.message.id == null) { + const runId = runManagers?.at(0)?.runId; + if (runId != null) + chunk.message._updateId(`run-${runId}`); + } + chunk.message.response_metadata = { + ...chunk.generationInfo, + ...chunk.message.response_metadata + }; + yield chunk.message; + if (!generationChunk) { + generationChunk = chunk; + } else { + generationChunk = generationChunk.concat(chunk); + } + if (isAIMessageChunk(chunk.message) && chunk.message.usage_metadata !== void 0) { + llmOutput = { + tokenUsage: { + promptTokens: chunk.message.usage_metadata.input_tokens, + completionTokens: chunk.message.usage_metadata.output_tokens, + totalTokens: chunk.message.usage_metadata.total_tokens + } + }; + } + } + } catch (err) { + await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMError(err))); + throw err; + } + await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMEnd({ + // TODO: Remove cast after figuring out inheritance + generations: [[generationChunk]], + llmOutput + }))); + } + } + getLsParams(options) { + const providerName = this.getName().startsWith("Chat") ? this.getName().replace("Chat", "") : this.getName(); + return { + ls_model_type: "chat", + ls_stop: options.stop, + ls_provider: providerName + }; + } + /** @ignore */ + async _generateUncached(messages, parsedOptions, handledOptions, startedRunManagers) { + const baseMessages = messages.map((messageList) => messageList.map(coerceMessageLikeToMessage)); + let runManagers; + if (startedRunManagers !== void 0 && startedRunManagers.length === baseMessages.length) { + runManagers = startedRunManagers; + } else { + const inheritableMetadata = { + ...handledOptions.metadata, + ...this.getLsParams(parsedOptions) + }; + const callbackManager_ = await CallbackManager.configure(handledOptions.callbacks, this.callbacks, handledOptions.tags, this.tags, inheritableMetadata, this.metadata, { verbose: this.verbose }); + const extra = { + options: parsedOptions, + invocation_params: this?.invocationParams(parsedOptions), + batch_size: 1 + }; + runManagers = await callbackManager_?.handleChatModelStart(this.toJSON(), baseMessages.map(_formatForTracing), handledOptions.runId, void 0, extra, void 0, void 0, handledOptions.runName); + } + const generations = []; + const llmOutputs = []; + const hasStreamingHandler = !!runManagers?.[0].handlers.find(callbackHandlerPrefersStreaming); + if (hasStreamingHandler && !this.disableStreaming && baseMessages.length === 1 && this._streamResponseChunks !== _BaseChatModel.prototype._streamResponseChunks) { + try { + const stream = await this._streamResponseChunks(baseMessages[0], parsedOptions, runManagers?.[0]); + let aggregated; + let llmOutput; + for await (const chunk of stream) { + if (chunk.message.id == null) { + const runId = runManagers?.at(0)?.runId; + if (runId != null) + chunk.message._updateId(`run-${runId}`); + } + if (aggregated === void 0) { + aggregated = chunk; + } else { + aggregated = concat(aggregated, chunk); + } + if (isAIMessageChunk(chunk.message) && chunk.message.usage_metadata !== void 0) { + llmOutput = { + tokenUsage: { + promptTokens: chunk.message.usage_metadata.input_tokens, + completionTokens: chunk.message.usage_metadata.output_tokens, + totalTokens: chunk.message.usage_metadata.total_tokens + } + }; + } + } + if (aggregated === void 0) { + throw new Error("Received empty response from chat model call."); + } + generations.push([aggregated]); + await runManagers?.[0].handleLLMEnd({ + generations, + llmOutput + }); + } catch (e) { + await runManagers?.[0].handleLLMError(e); + throw e; + } + } else { + const results = await Promise.allSettled(baseMessages.map((messageList, i) => this._generate(messageList, { ...parsedOptions, promptIndex: i }, runManagers?.[i]))); + await Promise.all(results.map(async (pResult, i) => { + if (pResult.status === "fulfilled") { + const result = pResult.value; + for (const generation of result.generations) { + if (generation.message.id == null) { + const runId = runManagers?.at(0)?.runId; + if (runId != null) + generation.message._updateId(`run-${runId}`); + } + generation.message.response_metadata = { + ...generation.generationInfo, + ...generation.message.response_metadata + }; + } + if (result.generations.length === 1) { + result.generations[0].message.response_metadata = { + ...result.llmOutput, + ...result.generations[0].message.response_metadata + }; + } + generations[i] = result.generations; + llmOutputs[i] = result.llmOutput; + return runManagers?.[i]?.handleLLMEnd({ + generations: [result.generations], + llmOutput: result.llmOutput + }); + } else { + await runManagers?.[i]?.handleLLMError(pResult.reason); + return Promise.reject(pResult.reason); + } + })); + } + const output = { + generations, + llmOutput: llmOutputs.length ? this._combineLLMOutput?.(...llmOutputs) : void 0 + }; + Object.defineProperty(output, RUN_KEY, { + value: runManagers ? { runIds: runManagers?.map((manager) => manager.runId) } : void 0, + configurable: true + }); + return output; + } + async _generateCached({ messages, cache: cache2, llmStringKey, parsedOptions, handledOptions }) { + const baseMessages = messages.map((messageList) => messageList.map(coerceMessageLikeToMessage)); + const inheritableMetadata = { + ...handledOptions.metadata, + ...this.getLsParams(parsedOptions) + }; + const callbackManager_ = await CallbackManager.configure(handledOptions.callbacks, this.callbacks, handledOptions.tags, this.tags, inheritableMetadata, this.metadata, { verbose: this.verbose }); + const extra = { + options: parsedOptions, + invocation_params: this?.invocationParams(parsedOptions), + batch_size: 1 + }; + const runManagers = await callbackManager_?.handleChatModelStart(this.toJSON(), baseMessages.map(_formatForTracing), handledOptions.runId, void 0, extra, void 0, void 0, handledOptions.runName); + const missingPromptIndices = []; + const results = await Promise.allSettled(baseMessages.map(async (baseMessage, index2) => { + const prompt = _BaseChatModel._convertInputToPromptValue(baseMessage).toString(); + const result = await cache2.lookup(prompt, llmStringKey); + if (result == null) { + missingPromptIndices.push(index2); + } + return result; + })); + const cachedResults = results.map((result, index2) => ({ result, runManager: runManagers?.[index2] })).filter(({ result }) => result.status === "fulfilled" && result.value != null || result.status === "rejected"); + const generations = []; + await Promise.all(cachedResults.map(async ({ result: promiseResult, runManager }, i) => { + if (promiseResult.status === "fulfilled") { + const result = promiseResult.value; + generations[i] = result.map((result2) => { + if ("message" in result2 && isBaseMessage(result2.message) && isAIMessage(result2.message)) { + result2.message.usage_metadata = { + input_tokens: 0, + output_tokens: 0, + total_tokens: 0 + }; + } + result2.generationInfo = { + ...result2.generationInfo, + tokenUsage: {} + }; + return result2; + }); + if (result.length) { + await runManager?.handleLLMNewToken(result[0].text); + } + return runManager?.handleLLMEnd({ + generations: [result] + }, void 0, void 0, void 0, { + cached: true + }); + } else { + await runManager?.handleLLMError(promiseResult.reason, void 0, void 0, void 0, { + cached: true + }); + return Promise.reject(promiseResult.reason); + } + })); + const output = { + generations, + missingPromptIndices, + startedRunManagers: runManagers + }; + Object.defineProperty(output, RUN_KEY, { + value: runManagers ? { runIds: runManagers?.map((manager) => manager.runId) } : void 0, + configurable: true + }); + return output; + } + /** + * Generates chat based on the input messages. + * @param messages An array of arrays of BaseMessage instances. + * @param options The call options or an array of stop sequences. + * @param callbacks The callbacks for the language model. + * @returns A Promise that resolves to an LLMResult. + */ + async generate(messages, options, callbacks) { + let parsedOptions; + if (Array.isArray(options)) { + parsedOptions = { stop: options }; + } else { + parsedOptions = options; + } + const baseMessages = messages.map((messageList) => messageList.map(coerceMessageLikeToMessage)); + const [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptionsCompat(parsedOptions); + runnableConfig.callbacks = runnableConfig.callbacks ?? callbacks; + if (!this.cache) { + return this._generateUncached(baseMessages, callOptions, runnableConfig); + } + const { cache: cache2 } = this; + const llmStringKey = this._getSerializedCacheKeyParametersForCall(callOptions); + const { generations, missingPromptIndices, startedRunManagers } = await this._generateCached({ + messages: baseMessages, + cache: cache2, + llmStringKey, + parsedOptions: callOptions, + handledOptions: runnableConfig + }); + let llmOutput = {}; + if (missingPromptIndices.length > 0) { + const results = await this._generateUncached(missingPromptIndices.map((i) => baseMessages[i]), callOptions, runnableConfig, startedRunManagers !== void 0 ? missingPromptIndices.map((i) => startedRunManagers?.[i]) : void 0); + await Promise.all(results.generations.map(async (generation, index2) => { + const promptIndex = missingPromptIndices[index2]; + generations[promptIndex] = generation; + const prompt = _BaseChatModel._convertInputToPromptValue(baseMessages[promptIndex]).toString(); + return cache2.update(prompt, llmStringKey, generation); + })); + llmOutput = results.llmOutput ?? {}; + } + return { generations, llmOutput }; + } + /** + * Get the parameters used to invoke the model + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + invocationParams(_options) { + return {}; + } + _modelType() { + return "base_chat_model"; + } + /** + * @deprecated + * Return a json-like object representing this LLM. + */ + serialize() { + return { + ...this.invocationParams(), + _type: this._llmType(), + _model: this._modelType() + }; + } + /** + * Generates a prompt based on the input prompt values. + * @param promptValues An array of BasePromptValue instances. + * @param options The call options or an array of stop sequences. + * @param callbacks The callbacks for the language model. + * @returns A Promise that resolves to an LLMResult. + */ + async generatePrompt(promptValues, options, callbacks) { + const promptMessages = promptValues.map((promptValue) => promptValue.toChatMessages()); + return this.generate(promptMessages, options, callbacks); + } + /** + * @deprecated Use .invoke() instead. Will be removed in 0.2.0. + * + * Makes a single call to the chat model. + * @param messages An array of BaseMessage instances. + * @param options The call options or an array of stop sequences. + * @param callbacks The callbacks for the language model. + * @returns A Promise that resolves to a BaseMessage. + */ + async call(messages, options, callbacks) { + const result = await this.generate([messages.map(coerceMessageLikeToMessage)], options, callbacks); + const generations = result.generations; + return generations[0][0].message; + } + /** + * @deprecated Use .invoke() instead. Will be removed in 0.2.0. + * + * Makes a single call to the chat model with a prompt value. + * @param promptValue The value of the prompt. + * @param options The call options or an array of stop sequences. + * @param callbacks The callbacks for the language model. + * @returns A Promise that resolves to a BaseMessage. + */ + async callPrompt(promptValue, options, callbacks) { + const promptMessages = promptValue.toChatMessages(); + return this.call(promptMessages, options, callbacks); + } + /** + * @deprecated Use .invoke() instead. Will be removed in 0.2.0. + * + * Predicts the next message based on the input messages. + * @param messages An array of BaseMessage instances. + * @param options The call options or an array of stop sequences. + * @param callbacks The callbacks for the language model. + * @returns A Promise that resolves to a BaseMessage. + */ + async predictMessages(messages, options, callbacks) { + return this.call(messages, options, callbacks); + } + /** + * @deprecated Use .invoke() instead. Will be removed in 0.2.0. + * + * Predicts the next message based on a text input. + * @param text The text input. + * @param options The call options or an array of stop sequences. + * @param callbacks The callbacks for the language model. + * @returns A Promise that resolves to a string. + */ + async predict(text, options, callbacks) { + const message = new HumanMessage(text); + const result = await this.call([message], options, callbacks); + if (typeof result.content !== "string") { + throw new Error("Cannot use predict when output is not a string."); + } + return result.content; + } + withStructuredOutput(outputSchema, config2) { + if (typeof this.bindTools !== "function") { + throw new Error(`Chat model must implement ".bindTools()" to use withStructuredOutput.`); + } + if (config2?.strict) { + throw new Error(`"strict" mode is not supported for this model by default.`); + } + const schema = outputSchema; + const name = config2?.name; + const description = getSchemaDescription(schema) ?? "A function available to call."; + const method = config2?.method; + const includeRaw = config2?.includeRaw; + if (method === "jsonMode") { + throw new Error(`Base withStructuredOutput implementation only supports "functionCalling" as a method.`); + } + let functionName = name ?? "extract"; + let tools; + if (isInteropZodSchema(schema)) { + tools = [ + { + type: "function", + function: { + name: functionName, + description, + parameters: toJsonSchema(schema) + } + } + ]; + } else { + if ("name" in schema) { + functionName = schema.name; + } + tools = [ + { + type: "function", + function: { + name: functionName, + description, + parameters: schema + } + } + ]; + } + const llm = this.bindTools(tools); + const outputParser = RunnableLambda.from((input) => { + if (!input.tool_calls || input.tool_calls.length === 0) { + throw new Error("No tool calls found in the response."); + } + const toolCall = input.tool_calls.find((tc) => tc.name === functionName); + if (!toolCall) { + throw new Error(`No tool call found with name ${functionName}.`); + } + return toolCall.args; + }); + if (!includeRaw) { + return llm.pipe(outputParser).withConfig({ + runName: "StructuredOutput" + }); + } + const parserAssign = RunnablePassthrough.assign({ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + parsed: (input, config3) => outputParser.invoke(input.raw, config3) + }); + const parserNone = RunnablePassthrough.assign({ + parsed: () => null + }); + const parsedWithFallback = parserAssign.withFallbacks({ + fallbacks: [parserNone] + }); + return RunnableSequence.from([ + { + raw: llm + }, + parsedWithFallback + ]).withConfig({ + runName: "StructuredOutputRunnable" + }); + } +}; +var SimpleChatModel = class extends BaseChatModel { + async _generate(messages, options, runManager) { + const text = await this._call(messages, options, runManager); + const message = new AIMessage(text); + if (typeof message.content !== "string") { + throw new Error("Cannot generate with a simple chat model when output is not a string."); + } + return { + generations: [ + { + text: message.content, + message + } + ] + }; + } +}; + +// node_modules/@langchain/core/dist/language_models/llms.js +var llms_exports = {}; +__export(llms_exports, { + BaseLLM: () => BaseLLM, + LLM: () => LLM +}); +init_messages2(); +init_outputs(); +init_manager(); +init_stream(); +init_base2(); +var BaseLLM = class _BaseLLM extends BaseLanguageModel { + constructor({ concurrency, ...rest }) { + super(concurrency ? { maxConcurrency: concurrency, ...rest } : rest); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain", "llms", this._llmType()] + }); + } + /** + * This method takes an input and options, and returns a string. It + * converts the input to a prompt value and generates a result based on + * the prompt. + * @param input Input for the LLM. + * @param options Options for the LLM call. + * @returns A string result based on the prompt. + */ + async invoke(input, options) { + const promptValue = _BaseLLM._convertInputToPromptValue(input); + const result = await this.generatePrompt([promptValue], options, options?.callbacks); + return result.generations[0][0].text; + } + // eslint-disable-next-line require-yield + async *_streamResponseChunks(_input, _options, _runManager) { + throw new Error("Not implemented."); + } + _separateRunnableConfigFromCallOptionsCompat(options) { + const [runnableConfig, callOptions] = super._separateRunnableConfigFromCallOptions(options); + callOptions.signal = runnableConfig.signal; + return [runnableConfig, callOptions]; + } + async *_streamIterator(input, options) { + if (this._streamResponseChunks === _BaseLLM.prototype._streamResponseChunks) { + yield this.invoke(input, options); + } else { + const prompt = _BaseLLM._convertInputToPromptValue(input); + const [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptionsCompat(options); + const callbackManager_ = await CallbackManager.configure(runnableConfig.callbacks, this.callbacks, runnableConfig.tags, this.tags, runnableConfig.metadata, this.metadata, { verbose: this.verbose }); + const extra = { + options: callOptions, + invocation_params: this?.invocationParams(callOptions), + batch_size: 1 + }; + const runManagers = await callbackManager_?.handleLLMStart(this.toJSON(), [prompt.toString()], runnableConfig.runId, void 0, extra, void 0, void 0, runnableConfig.runName); + let generation = new GenerationChunk({ + text: "" + }); + try { + for await (const chunk of this._streamResponseChunks(prompt.toString(), callOptions, runManagers?.[0])) { + if (!generation) { + generation = chunk; + } else { + generation = generation.concat(chunk); + } + if (typeof chunk.text === "string") { + yield chunk.text; + } + } + } catch (err) { + await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMError(err))); + throw err; + } + await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMEnd({ + generations: [[generation]] + }))); + } + } + /** + * This method takes prompt values, options, and callbacks, and generates + * a result based on the prompts. + * @param promptValues Prompt values for the LLM. + * @param options Options for the LLM call. + * @param callbacks Callbacks for the LLM call. + * @returns An LLMResult based on the prompts. + */ + async generatePrompt(promptValues, options, callbacks) { + const prompts = promptValues.map((promptValue) => promptValue.toString()); + return this.generate(prompts, options, callbacks); + } + /** + * Get the parameters used to invoke the model + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + invocationParams(_options) { + return {}; + } + _flattenLLMResult(llmResult) { + const llmResults = []; + for (let i = 0; i < llmResult.generations.length; i += 1) { + const genList = llmResult.generations[i]; + if (i === 0) { + llmResults.push({ + generations: [genList], + llmOutput: llmResult.llmOutput + }); + } else { + const llmOutput = llmResult.llmOutput ? { ...llmResult.llmOutput, tokenUsage: {} } : void 0; + llmResults.push({ + generations: [genList], + llmOutput + }); + } + } + return llmResults; + } + /** @ignore */ + async _generateUncached(prompts, parsedOptions, handledOptions, startedRunManagers) { + let runManagers; + if (startedRunManagers !== void 0 && startedRunManagers.length === prompts.length) { + runManagers = startedRunManagers; + } else { + const callbackManager_ = await CallbackManager.configure(handledOptions.callbacks, this.callbacks, handledOptions.tags, this.tags, handledOptions.metadata, this.metadata, { verbose: this.verbose }); + const extra = { + options: parsedOptions, + invocation_params: this?.invocationParams(parsedOptions), + batch_size: prompts.length + }; + runManagers = await callbackManager_?.handleLLMStart(this.toJSON(), prompts, handledOptions.runId, void 0, extra, void 0, void 0, handledOptions?.runName); + } + const hasStreamingHandler = !!runManagers?.[0].handlers.find(callbackHandlerPrefersStreaming); + let output; + if (hasStreamingHandler && prompts.length === 1 && this._streamResponseChunks !== _BaseLLM.prototype._streamResponseChunks) { + try { + const stream = await this._streamResponseChunks(prompts[0], parsedOptions, runManagers?.[0]); + let aggregated; + for await (const chunk of stream) { + if (aggregated === void 0) { + aggregated = chunk; + } else { + aggregated = concat(aggregated, chunk); + } + } + if (aggregated === void 0) { + throw new Error("Received empty response from chat model call."); + } + output = { generations: [[aggregated]], llmOutput: {} }; + await runManagers?.[0].handleLLMEnd(output); + } catch (e) { + await runManagers?.[0].handleLLMError(e); + throw e; + } + } else { + try { + output = await this._generate(prompts, parsedOptions, runManagers?.[0]); + } catch (err) { + await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMError(err))); + throw err; + } + const flattenedOutputs = this._flattenLLMResult(output); + await Promise.all((runManagers ?? []).map((runManager, i) => runManager?.handleLLMEnd(flattenedOutputs[i]))); + } + const runIds = runManagers?.map((manager) => manager.runId) || void 0; + Object.defineProperty(output, RUN_KEY, { + value: runIds ? { runIds } : void 0, + configurable: true + }); + return output; + } + async _generateCached({ prompts, cache: cache2, llmStringKey, parsedOptions, handledOptions, runId }) { + const callbackManager_ = await CallbackManager.configure(handledOptions.callbacks, this.callbacks, handledOptions.tags, this.tags, handledOptions.metadata, this.metadata, { verbose: this.verbose }); + const extra = { + options: parsedOptions, + invocation_params: this?.invocationParams(parsedOptions), + batch_size: prompts.length + }; + const runManagers = await callbackManager_?.handleLLMStart(this.toJSON(), prompts, runId, void 0, extra, void 0, void 0, handledOptions?.runName); + const missingPromptIndices = []; + const results = await Promise.allSettled(prompts.map(async (prompt, index2) => { + const result = await cache2.lookup(prompt, llmStringKey); + if (result == null) { + missingPromptIndices.push(index2); + } + return result; + })); + const cachedResults = results.map((result, index2) => ({ result, runManager: runManagers?.[index2] })).filter(({ result }) => result.status === "fulfilled" && result.value != null || result.status === "rejected"); + const generations = []; + await Promise.all(cachedResults.map(async ({ result: promiseResult, runManager }, i) => { + if (promiseResult.status === "fulfilled") { + const result = promiseResult.value; + generations[i] = result.map((result2) => { + result2.generationInfo = { + ...result2.generationInfo, + tokenUsage: {} + }; + return result2; + }); + if (result.length) { + await runManager?.handleLLMNewToken(result[0].text); + } + return runManager?.handleLLMEnd({ + generations: [result] + }, void 0, void 0, void 0, { + cached: true + }); + } else { + await runManager?.handleLLMError(promiseResult.reason, void 0, void 0, void 0, { + cached: true + }); + return Promise.reject(promiseResult.reason); + } + })); + const output = { + generations, + missingPromptIndices, + startedRunManagers: runManagers + }; + Object.defineProperty(output, RUN_KEY, { + value: runManagers ? { runIds: runManagers?.map((manager) => manager.runId) } : void 0, + configurable: true + }); + return output; + } + /** + * Run the LLM on the given prompts and input, handling caching. + */ + async generate(prompts, options, callbacks) { + if (!Array.isArray(prompts)) { + throw new Error("Argument 'prompts' is expected to be a string[]"); + } + let parsedOptions; + if (Array.isArray(options)) { + parsedOptions = { stop: options }; + } else { + parsedOptions = options; + } + const [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptionsCompat(parsedOptions); + runnableConfig.callbacks = runnableConfig.callbacks ?? callbacks; + if (!this.cache) { + return this._generateUncached(prompts, callOptions, runnableConfig); + } + const { cache: cache2 } = this; + const llmStringKey = this._getSerializedCacheKeyParametersForCall(callOptions); + const { generations, missingPromptIndices, startedRunManagers } = await this._generateCached({ + prompts, + cache: cache2, + llmStringKey, + parsedOptions: callOptions, + handledOptions: runnableConfig, + runId: runnableConfig.runId + }); + let llmOutput = {}; + if (missingPromptIndices.length > 0) { + const results = await this._generateUncached(missingPromptIndices.map((i) => prompts[i]), callOptions, runnableConfig, startedRunManagers !== void 0 ? missingPromptIndices.map((i) => startedRunManagers?.[i]) : void 0); + await Promise.all(results.generations.map(async (generation, index2) => { + const promptIndex = missingPromptIndices[index2]; + generations[promptIndex] = generation; + return cache2.update(prompts[promptIndex], llmStringKey, generation); + })); + llmOutput = results.llmOutput ?? {}; + } + return { generations, llmOutput }; + } + /** + * @deprecated Use .invoke() instead. Will be removed in 0.2.0. + * Convenience wrapper for {@link generate} that takes in a single string prompt and returns a single string output. + */ + async call(prompt, options, callbacks) { + const { generations } = await this.generate([prompt], options, callbacks); + return generations[0][0].text; + } + /** + * @deprecated Use .invoke() instead. Will be removed in 0.2.0. + * + * This method is similar to `call`, but it's used for making predictions + * based on the input text. + * @param text Input text for the prediction. + * @param options Options for the LLM call. + * @param callbacks Callbacks for the LLM call. + * @returns A prediction based on the input text. + */ + async predict(text, options, callbacks) { + return this.call(text, options, callbacks); + } + /** + * @deprecated Use .invoke() instead. Will be removed in 0.2.0. + * + * This method takes a list of messages, options, and callbacks, and + * returns a predicted message. + * @param messages A list of messages for the prediction. + * @param options Options for the LLM call. + * @param callbacks Callbacks for the LLM call. + * @returns A predicted message based on the list of messages. + */ + async predictMessages(messages, options, callbacks) { + const text = getBufferString(messages); + const prediction = await this.call(text, options, callbacks); + return new AIMessage(prediction); + } + /** + * Get the identifying parameters of the LLM. + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + _identifyingParams() { + return {}; + } + /** + * @deprecated + * Return a json-like object representing this LLM. + */ + serialize() { + return { + ...this._identifyingParams(), + _type: this._llmType(), + _model: this._modelType() + }; + } + _modelType() { + return "base_llm"; + } +}; +var LLM = class extends BaseLLM { + async _generate(prompts, options, runManager) { + const generations = await Promise.all(prompts.map((prompt, promptIndex) => this._call(prompt, { ...options, promptIndex }, runManager).then((text) => [{ text }]))); + return { generations }; + } +}; + +// node_modules/@langchain/core/dist/load/import_map.js +init_serializable(); + +// node_modules/@langchain/core/dist/memory.js +var memory_exports = {}; +__export(memory_exports, { + BaseMemory: () => BaseMemory, + getInputValue: () => getInputValue, + getOutputValue: () => getOutputValue, + getPromptInputKey: () => getPromptInputKey +}); +var BaseMemory = class { +}; +var getValue = (values, key) => { + if (key !== void 0) { + return values[key]; + } + const keys = Object.keys(values); + if (keys.length === 1) { + return values[keys[0]]; + } +}; +var getInputValue = (inputValues, inputKey) => { + const value = getValue(inputValues, inputKey); + if (!value) { + const keys = Object.keys(inputValues); + throw new Error(`input values have ${keys.length} keys, you must specify an input key or pass only 1 key as input`); + } + return value; +}; +var getOutputValue = (outputValues, outputKey) => { + const value = getValue(outputValues, outputKey); + if (!value && value !== "") { + const keys = Object.keys(outputValues); + throw new Error(`output values have ${keys.length} keys, you must specify an output key or pass only 1 key as output`); + } + return value; +}; +function getPromptInputKey(inputs, memoryVariables) { + const promptInputKeys = Object.keys(inputs).filter((key) => !memoryVariables.includes(key) && key !== "stop"); + if (promptInputKeys.length !== 1) { + throw new Error(`One input key expected, but got ${promptInputKeys.length}`); + } + return promptInputKeys[0]; +} + +// node_modules/@langchain/core/dist/load/import_map.js +init_messages2(); + +// node_modules/@langchain/core/dist/output_parsers/index.js +var output_parsers_exports = {}; +__export(output_parsers_exports, { + AsymmetricStructuredOutputParser: () => AsymmetricStructuredOutputParser, + BaseCumulativeTransformOutputParser: () => BaseCumulativeTransformOutputParser, + BaseLLMOutputParser: () => BaseLLMOutputParser, + BaseOutputParser: () => BaseOutputParser, + BaseTransformOutputParser: () => BaseTransformOutputParser, + BytesOutputParser: () => BytesOutputParser, + CommaSeparatedListOutputParser: () => CommaSeparatedListOutputParser, + CustomListOutputParser: () => CustomListOutputParser, + JsonMarkdownStructuredOutputParser: () => JsonMarkdownStructuredOutputParser, + JsonOutputParser: () => JsonOutputParser, + ListOutputParser: () => ListOutputParser, + MarkdownListOutputParser: () => MarkdownListOutputParser, + NumberedListOutputParser: () => NumberedListOutputParser, + OutputParserException: () => OutputParserException, + StringOutputParser: () => StringOutputParser, + StructuredOutputParser: () => StructuredOutputParser, + XMLOutputParser: () => XMLOutputParser, + XML_FORMAT_INSTRUCTIONS: () => XML_FORMAT_INSTRUCTIONS, + parseJsonMarkdown: () => parseJsonMarkdown, + parsePartialJson: () => parsePartialJson, + parseXMLMarkdown: () => parseXMLMarkdown +}); + +// node_modules/@langchain/core/dist/runnables/index.js +var runnables_exports = {}; +__export(runnables_exports, { + RouterRunnable: () => RouterRunnable, + Runnable: () => Runnable, + RunnableAssign: () => RunnableAssign, + RunnableBinding: () => RunnableBinding, + RunnableBranch: () => RunnableBranch, + RunnableEach: () => RunnableEach, + RunnableLambda: () => RunnableLambda, + RunnableMap: () => RunnableMap, + RunnableParallel: () => RunnableParallel, + RunnablePassthrough: () => RunnablePassthrough, + RunnablePick: () => RunnablePick, + RunnableRetry: () => RunnableRetry, + RunnableSequence: () => RunnableSequence, + RunnableToolLike: () => RunnableToolLike, + RunnableWithFallbacks: () => RunnableWithFallbacks, + RunnableWithMessageHistory: () => RunnableWithMessageHistory, + _coerceToRunnable: () => _coerceToRunnable, + ensureConfig: () => ensureConfig, + getCallbackManagerForConfig: () => getCallbackManagerForConfig, + mergeConfigs: () => mergeConfigs, + patchConfig: () => patchConfig, + pickRunnableConfigKeys: () => pickRunnableConfigKeys +}); +init_base4(); +init_config(); + +// node_modules/@langchain/core/dist/runnables/router.js +init_base4(); +init_config(); +var RouterRunnable = class extends Runnable { + static lc_name() { + return "RouterRunnable"; + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain_core", "runnables"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "runnables", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.runnables = fields.runnables; + } + async invoke(input, options) { + const { key, input: actualInput } = input; + const runnable = this.runnables[key]; + if (runnable === void 0) { + throw new Error(`No runnable associated with key "${key}".`); + } + return runnable.invoke(actualInput, ensureConfig(options)); + } + async batch(inputs, options, batchOptions) { + const keys = inputs.map((input) => input.key); + const actualInputs = inputs.map((input) => input.input); + const missingKey = keys.find((key) => this.runnables[key] === void 0); + if (missingKey !== void 0) { + throw new Error(`One or more keys do not have a corresponding runnable.`); + } + const runnables = keys.map((key) => this.runnables[key]); + const optionsList = this._getOptionsList(options ?? {}, inputs.length); + const maxConcurrency = optionsList[0]?.maxConcurrency ?? batchOptions?.maxConcurrency; + const batchSize = maxConcurrency && maxConcurrency > 0 ? maxConcurrency : inputs.length; + const batchResults = []; + for (let i = 0; i < actualInputs.length; i += batchSize) { + const batchPromises = actualInputs.slice(i, i + batchSize).map((actualInput, i2) => runnables[i2].invoke(actualInput, optionsList[i2])); + const batchResult = await Promise.all(batchPromises); + batchResults.push(batchResult); + } + return batchResults.flat(); + } + async stream(input, options) { + const { key, input: actualInput } = input; + const runnable = this.runnables[key]; + if (runnable === void 0) { + throw new Error(`No runnable associated with key "${key}".`); + } + return runnable.stream(actualInput, options); + } +}; + +// node_modules/@langchain/core/dist/runnables/branch.js +init_base4(); +init_config(); +init_stream(); +var RunnableBranch = class extends Runnable { + static lc_name() { + return "RunnableBranch"; + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain_core", "runnables"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "default", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "branches", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.branches = fields.branches; + this.default = fields.default; + } + /** + * Convenience method for instantiating a RunnableBranch from + * RunnableLikes (objects, functions, or Runnables). + * + * Each item in the input except for the last one should be a + * tuple with two items. The first is a "condition" RunnableLike that + * returns "true" if the second RunnableLike in the tuple should run. + * + * The final item in the input should be a RunnableLike that acts as a + * default branch if no other branches match. + * + * @example + * ```ts + * import { RunnableBranch } from "@langchain/core/runnables"; + * + * const branch = RunnableBranch.from([ + * [(x: number) => x > 0, (x: number) => x + 1], + * [(x: number) => x < 0, (x: number) => x - 1], + * (x: number) => x + * ]); + * ``` + * @param branches An array where the every item except the last is a tuple of [condition, runnable] + * pairs. The last item is a default runnable which is invoked if no other condition matches. + * @returns A new RunnableBranch. + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + static from(branches) { + if (branches.length < 1) { + throw new Error("RunnableBranch requires at least one branch"); + } + const branchLikes = branches.slice(0, -1); + const coercedBranches = branchLikes.map(([condition, runnable]) => [ + _coerceToRunnable(condition), + _coerceToRunnable(runnable) + ]); + const defaultBranch = _coerceToRunnable(branches[branches.length - 1]); + return new this({ + branches: coercedBranches, + default: defaultBranch + }); + } + async _invoke(input, config2, runManager) { + let result; + for (let i = 0; i < this.branches.length; i += 1) { + const [condition, branchRunnable] = this.branches[i]; + const conditionValue = await condition.invoke(input, patchConfig(config2, { + callbacks: runManager?.getChild(`condition:${i + 1}`) + })); + if (conditionValue) { + result = await branchRunnable.invoke(input, patchConfig(config2, { + callbacks: runManager?.getChild(`branch:${i + 1}`) + })); + break; + } + } + if (!result) { + result = await this.default.invoke(input, patchConfig(config2, { + callbacks: runManager?.getChild("branch:default") + })); + } + return result; + } + async invoke(input, config2 = {}) { + return this._callWithConfig(this._invoke, input, config2); + } + async *_streamIterator(input, config2) { + const callbackManager_ = await getCallbackManagerForConfig(config2); + const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict3(input, "input"), config2?.runId, void 0, void 0, void 0, config2?.runName); + let finalOutput; + let finalOutputSupported = true; + let stream; + try { + for (let i = 0; i < this.branches.length; i += 1) { + const [condition, branchRunnable] = this.branches[i]; + const conditionValue = await condition.invoke(input, patchConfig(config2, { + callbacks: runManager?.getChild(`condition:${i + 1}`) + })); + if (conditionValue) { + stream = await branchRunnable.stream(input, patchConfig(config2, { + callbacks: runManager?.getChild(`branch:${i + 1}`) + })); + for await (const chunk of stream) { + yield chunk; + if (finalOutputSupported) { + if (finalOutput === void 0) { + finalOutput = chunk; + } else { + try { + finalOutput = concat(finalOutput, chunk); + } catch (e) { + finalOutput = void 0; + finalOutputSupported = false; + } + } + } + } + break; + } + } + if (stream === void 0) { + stream = await this.default.stream(input, patchConfig(config2, { + callbacks: runManager?.getChild("branch:default") + })); + for await (const chunk of stream) { + yield chunk; + if (finalOutputSupported) { + if (finalOutput === void 0) { + finalOutput = chunk; + } else { + try { + finalOutput = concat(finalOutput, chunk); + } catch (e) { + finalOutput = void 0; + finalOutputSupported = false; + } + } + } + } + } + } catch (e) { + await runManager?.handleChainError(e); + throw e; + } + await runManager?.handleChainEnd(finalOutput ?? {}); + } +}; + +// node_modules/@langchain/core/dist/runnables/history.js +init_messages2(); +init_base4(); +var RunnableWithMessageHistory = class extends RunnableBinding { + constructor(fields) { + let historyChain = RunnableLambda.from((input, options) => this._enterHistory(input, options ?? {})).withConfig({ runName: "loadHistory" }); + const messagesKey = fields.historyMessagesKey ?? fields.inputMessagesKey; + if (messagesKey) { + historyChain = RunnablePassthrough.assign({ + [messagesKey]: historyChain + }).withConfig({ runName: "insertHistory" }); + } + const bound = historyChain.pipe(fields.runnable.withListeners({ + onEnd: (run, config3) => this._exitHistory(run, config3 ?? {}) + })).withConfig({ runName: "RunnableWithMessageHistory" }); + const config2 = fields.config ?? {}; + super({ + ...fields, + config: config2, + bound + }); + Object.defineProperty(this, "runnable", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "inputMessagesKey", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "outputMessagesKey", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "historyMessagesKey", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "getMessageHistory", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.runnable = fields.runnable; + this.getMessageHistory = fields.getMessageHistory; + this.inputMessagesKey = fields.inputMessagesKey; + this.outputMessagesKey = fields.outputMessagesKey; + this.historyMessagesKey = fields.historyMessagesKey; + } + _getInputMessages(inputValue) { + let parsedInputValue; + if (typeof inputValue === "object" && !Array.isArray(inputValue) && !isBaseMessage(inputValue)) { + let key; + if (this.inputMessagesKey) { + key = this.inputMessagesKey; + } else if (Object.keys(inputValue).length === 1) { + key = Object.keys(inputValue)[0]; + } else { + key = "input"; + } + if (Array.isArray(inputValue[key]) && Array.isArray(inputValue[key][0])) { + parsedInputValue = inputValue[key][0]; + } else { + parsedInputValue = inputValue[key]; + } + } else { + parsedInputValue = inputValue; + } + if (typeof parsedInputValue === "string") { + return [new HumanMessage(parsedInputValue)]; + } else if (Array.isArray(parsedInputValue)) { + return parsedInputValue; + } else if (isBaseMessage(parsedInputValue)) { + return [parsedInputValue]; + } else { + throw new Error(`Expected a string, BaseMessage, or array of BaseMessages. +Got ${JSON.stringify(parsedInputValue, null, 2)}`); + } + } + _getOutputMessages(outputValue) { + let parsedOutputValue; + if (!Array.isArray(outputValue) && !isBaseMessage(outputValue) && typeof outputValue !== "string") { + let key; + if (this.outputMessagesKey !== void 0) { + key = this.outputMessagesKey; + } else if (Object.keys(outputValue).length === 1) { + key = Object.keys(outputValue)[0]; + } else { + key = "output"; + } + if (outputValue.generations !== void 0) { + parsedOutputValue = outputValue.generations[0][0].message; + } else { + parsedOutputValue = outputValue[key]; + } + } else { + parsedOutputValue = outputValue; + } + if (typeof parsedOutputValue === "string") { + return [new AIMessage(parsedOutputValue)]; + } else if (Array.isArray(parsedOutputValue)) { + return parsedOutputValue; + } else if (isBaseMessage(parsedOutputValue)) { + return [parsedOutputValue]; + } else { + throw new Error(`Expected a string, BaseMessage, or array of BaseMessages. Received: ${JSON.stringify(parsedOutputValue, null, 2)}`); + } + } + async _enterHistory(input, kwargs) { + const history = kwargs?.configurable?.messageHistory; + const messages = await history.getMessages(); + if (this.historyMessagesKey === void 0) { + return messages.concat(this._getInputMessages(input)); + } + return messages; + } + async _exitHistory(run, config2) { + const history = config2.configurable?.messageHistory; + let inputs; + if (Array.isArray(run.inputs) && Array.isArray(run.inputs[0])) { + inputs = run.inputs[0]; + } else { + inputs = run.inputs; + } + let inputMessages = this._getInputMessages(inputs); + if (this.historyMessagesKey === void 0) { + const existingMessages = await history.getMessages(); + inputMessages = inputMessages.slice(existingMessages.length); + } + const outputValue = run.outputs; + if (!outputValue) { + throw new Error(`Output values from 'Run' undefined. Run: ${JSON.stringify(run, null, 2)}`); + } + const outputMessages = this._getOutputMessages(outputValue); + await history.addMessages([...inputMessages, ...outputMessages]); + } + async _mergeConfig(...configs) { + const config2 = await super._mergeConfig(...configs); + if (!config2.configurable || !config2.configurable.sessionId) { + const exampleInput = { + [this.inputMessagesKey ?? "input"]: "foo" + }; + const exampleConfig = { configurable: { sessionId: "123" } }; + throw new Error(`sessionId is required. Pass it in as part of the config argument to .invoke() or .stream() +eg. chain.invoke(${JSON.stringify(exampleInput)}, ${JSON.stringify(exampleConfig)})`); + } + const { sessionId } = config2.configurable; + config2.configurable.messageHistory = await this.getMessageHistory(sessionId); + return config2; + } +}; + +// node_modules/@langchain/core/dist/output_parsers/base.js +init_errors(); +var BaseLLMOutputParser = class extends Runnable { + /** + * Parses the result of an LLM call with a given prompt. By default, it + * simply calls `parseResult`. + * @param generations The generations from an LLM call. + * @param _prompt The prompt used in the LLM call. + * @param callbacks Optional callbacks. + * @returns A promise of the parsed output. + */ + parseResultWithPrompt(generations, _prompt, callbacks) { + return this.parseResult(generations, callbacks); + } + _baseMessageToString(message) { + return typeof message.content === "string" ? message.content : this._baseMessageContentToString(message.content); + } + _baseMessageContentToString(content) { + return JSON.stringify(content); + } + /** + * Calls the parser with a given input and optional configuration options. + * If the input is a string, it creates a generation with the input as + * text and calls `parseResult`. If the input is a `BaseMessage`, it + * creates a generation with the input as a message and the content of the + * input as text, and then calls `parseResult`. + * @param input The input to the parser, which can be a string or a `BaseMessage`. + * @param options Optional configuration options. + * @returns A promise of the parsed output. + */ + async invoke(input, options) { + if (typeof input === "string") { + return this._callWithConfig(async (input2, options2) => this.parseResult([{ text: input2 }], options2?.callbacks), input, { ...options, runType: "parser" }); + } else { + return this._callWithConfig(async (input2, options2) => this.parseResult([ + { + message: input2, + text: this._baseMessageToString(input2) + } + ], options2?.callbacks), input, { ...options, runType: "parser" }); + } + } +}; +var BaseOutputParser = class extends BaseLLMOutputParser { + parseResult(generations, callbacks) { + return this.parse(generations[0].text, callbacks); + } + async parseWithPrompt(text, _prompt, callbacks) { + return this.parse(text, callbacks); + } + /** + * Return the string type key uniquely identifying this class of parser + */ + _type() { + throw new Error("_type not implemented"); + } +}; +var OutputParserException = class extends Error { + constructor(message, llmOutput, observation, sendToLLM = false) { + super(message); + Object.defineProperty(this, "llmOutput", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "observation", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "sendToLLM", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.llmOutput = llmOutput; + this.observation = observation; + this.sendToLLM = sendToLLM; + if (sendToLLM) { + if (observation === void 0 || llmOutput === void 0) { + throw new Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true"); + } + } + addLangChainErrorFields(this, "OUTPUT_PARSING_FAILURE"); + } +}; + +// node_modules/@langchain/core/dist/output_parsers/transform.js +init_esm2(); +init_base(); +init_utils2(); +init_outputs(); +var BaseTransformOutputParser = class extends BaseOutputParser { + async *_transform(inputGenerator) { + for await (const chunk of inputGenerator) { + if (typeof chunk === "string") { + yield this.parseResult([{ text: chunk }]); + } else { + yield this.parseResult([ + { + message: chunk, + text: this._baseMessageToString(chunk) + } + ]); + } + } + } + /** + * Transforms an asynchronous generator of input into an asynchronous + * generator of parsed output. + * @param inputGenerator An asynchronous generator of input. + * @param options A configuration object. + * @returns An asynchronous generator of parsed output. + */ + async *transform(inputGenerator, options) { + yield* this._transformStreamWithConfig(inputGenerator, this._transform.bind(this), { + ...options, + runType: "parser" + }); + } +}; +var BaseCumulativeTransformOutputParser = class extends BaseTransformOutputParser { + constructor(fields) { + super(fields); + Object.defineProperty(this, "diff", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + this.diff = fields?.diff ?? this.diff; + } + async *_transform(inputGenerator) { + let prevParsed; + let accGen; + for await (const chunk of inputGenerator) { + if (typeof chunk !== "string" && typeof chunk.content !== "string") { + throw new Error("Cannot handle non-string output."); + } + let chunkGen; + if (isBaseMessageChunk(chunk)) { + if (typeof chunk.content !== "string") { + throw new Error("Cannot handle non-string message output."); + } + chunkGen = new ChatGenerationChunk({ + message: chunk, + text: chunk.content + }); + } else if (isBaseMessage(chunk)) { + if (typeof chunk.content !== "string") { + throw new Error("Cannot handle non-string message output."); + } + chunkGen = new ChatGenerationChunk({ + message: convertToChunk(chunk), + text: chunk.content + }); + } else { + chunkGen = new GenerationChunk({ text: chunk }); + } + if (accGen === void 0) { + accGen = chunkGen; + } else { + accGen = accGen.concat(chunkGen); + } + const parsed = await this.parsePartialResult([accGen]); + if (parsed !== void 0 && parsed !== null && !deepCompareStrict(parsed, prevParsed)) { + if (this.diff) { + yield this._diff(prevParsed, parsed); + } else { + yield parsed; + } + prevParsed = parsed; + } + } + } + getFormatInstructions() { + return ""; + } +}; + +// node_modules/@langchain/core/dist/output_parsers/bytes.js +var BytesOutputParser = class extends BaseTransformOutputParser { + constructor() { + super(...arguments); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain_core", "output_parsers", "bytes"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "textEncoder", { + enumerable: true, + configurable: true, + writable: true, + value: new TextEncoder() + }); + } + static lc_name() { + return "BytesOutputParser"; + } + parse(text) { + return Promise.resolve(this.textEncoder.encode(text)); + } + getFormatInstructions() { + return ""; + } +}; + +// node_modules/@langchain/core/dist/output_parsers/list.js +var ListOutputParser = class extends BaseTransformOutputParser { + constructor() { + super(...arguments); + Object.defineProperty(this, "re", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + } + async *_transform(inputGenerator) { + let buffer = ""; + for await (const input of inputGenerator) { + if (typeof input === "string") { + buffer += input; + } else { + buffer += input.content; + } + if (!this.re) { + const parts = await this.parse(buffer); + if (parts.length > 1) { + for (const part of parts.slice(0, -1)) { + yield [part]; + } + buffer = parts[parts.length - 1]; + } + } else { + const matches = [...buffer.matchAll(this.re)]; + if (matches.length > 1) { + let doneIdx = 0; + for (const match of matches.slice(0, -1)) { + yield [match[1]]; + doneIdx += (match.index ?? 0) + match[0].length; + } + buffer = buffer.slice(doneIdx); + } + } + } + for (const part of await this.parse(buffer)) { + yield [part]; + } + } +}; +var CommaSeparatedListOutputParser = class extends ListOutputParser { + constructor() { + super(...arguments); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain_core", "output_parsers", "list"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + } + static lc_name() { + return "CommaSeparatedListOutputParser"; + } + /** + * Parses the given text into an array of strings, using a comma as the + * separator. If the parsing fails, throws an OutputParserException. + * @param text The text to parse. + * @returns An array of strings obtained by splitting the input text at each comma. + */ + async parse(text) { + try { + return text.trim().split(",").map((s) => s.trim()); + } catch (e) { + throw new OutputParserException(`Could not parse output: ${text}`, text); + } + } + /** + * Provides instructions on the expected format of the response for the + * CommaSeparatedListOutputParser. + * @returns A string containing instructions on the expected format of the response. + */ + getFormatInstructions() { + return `Your response should be a list of comma separated values, eg: \`foo, bar, baz\``; + } +}; +var CustomListOutputParser = class extends ListOutputParser { + constructor({ length, separator }) { + super(...arguments); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain_core", "output_parsers", "list"] + }); + Object.defineProperty(this, "length", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "separator", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.length = length; + this.separator = separator || ","; + } + /** + * Parses the given text into an array of strings, using the specified + * separator. If the parsing fails or the number of items in the list + * doesn't match the expected length, throws an OutputParserException. + * @param text The text to parse. + * @returns An array of strings obtained by splitting the input text at each occurrence of the specified separator. + */ + async parse(text) { + try { + const items = text.trim().split(this.separator).map((s) => s.trim()); + if (this.length !== void 0 && items.length !== this.length) { + throw new OutputParserException(`Incorrect number of items. Expected ${this.length}, got ${items.length}.`); + } + return items; + } catch (e) { + if (Object.getPrototypeOf(e) === OutputParserException.prototype) { + throw e; + } + throw new OutputParserException(`Could not parse output: ${text}`); + } + } + /** + * Provides instructions on the expected format of the response for the + * CustomListOutputParser, including the number of items and the + * separator. + * @returns A string containing instructions on the expected format of the response. + */ + getFormatInstructions() { + return `Your response should be a list of ${this.length === void 0 ? "" : `${this.length} `}items separated by "${this.separator}" (eg: \`foo${this.separator} bar${this.separator} baz\`)`; + } +}; +var NumberedListOutputParser = class extends ListOutputParser { + constructor() { + super(...arguments); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain_core", "output_parsers", "list"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "re", { + enumerable: true, + configurable: true, + writable: true, + value: /\d+\.\s([^\n]+)/g + }); + } + static lc_name() { + return "NumberedListOutputParser"; + } + getFormatInstructions() { + return `Your response should be a numbered list with each item on a new line. For example: + +1. foo + +2. bar + +3. baz`; + } + async parse(text) { + return [...text.matchAll(this.re) ?? []].map((m) => m[1]); + } +}; +var MarkdownListOutputParser = class extends ListOutputParser { + constructor() { + super(...arguments); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain_core", "output_parsers", "list"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "re", { + enumerable: true, + configurable: true, + writable: true, + value: /^\s*[-*]\s([^\n]+)$/gm + }); + } + static lc_name() { + return "NumberedListOutputParser"; + } + getFormatInstructions() { + return `Your response should be a numbered list with each item on a new line. For example: + +1. foo + +2. bar + +3. baz`; + } + async parse(text) { + return [...text.matchAll(this.re) ?? []].map((m) => m[1]); + } +}; + +// node_modules/@langchain/core/dist/output_parsers/string.js +var StringOutputParser = class extends BaseTransformOutputParser { + constructor() { + super(...arguments); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain_core", "output_parsers", "string"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + } + static lc_name() { + return "StrOutputParser"; + } + /** + * Parses a string output from an LLM call. This method is meant to be + * implemented by subclasses to define how a string output from an LLM + * should be parsed. + * @param text The string output from an LLM call. + * @param callbacks Optional callbacks. + * @returns A promise of the parsed output. + */ + parse(text) { + return Promise.resolve(text); + } + getFormatInstructions() { + return ""; + } + _textContentToString(content) { + return content.text; + } + _imageUrlContentToString(_content) { + throw new Error(`Cannot coerce a multimodal "image_url" message part into a string.`); + } + _messageContentComplexToString(content) { + switch (content.type) { + case "text": + case "text_delta": + if ("text" in content) { + return this._textContentToString(content); + } + break; + case "image_url": + if ("image_url" in content) { + return this._imageUrlContentToString(content); + } + break; + default: + throw new Error(`Cannot coerce "${content.type}" message part into a string.`); + } + throw new Error(`Invalid content type: ${content.type}`); + } + _baseMessageContentToString(content) { + return content.reduce((acc, item) => acc + this._messageContentComplexToString(item), ""); + } +}; + +// node_modules/@langchain/core/dist/output_parsers/structured.js +init_v3(); +init_zod2(); +init_json_schema2(); +var StructuredOutputParser = class extends BaseOutputParser { + static lc_name() { + return "StructuredOutputParser"; + } + toJSON() { + return this.toJSONNotImplemented(); + } + constructor(schema) { + super(schema); + Object.defineProperty(this, "schema", { + enumerable: true, + configurable: true, + writable: true, + value: schema + }); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain", "output_parsers", "structured"] + }); + } + /** + * Creates a new StructuredOutputParser from a Zod schema. + * @param schema The Zod schema which the output should match + * @returns A new instance of StructuredOutputParser. + */ + static fromZodSchema(schema) { + return new this(schema); + } + /** + * Creates a new StructuredOutputParser from a set of names and + * descriptions. + * @param schemas An object where each key is a name and each value is a description + * @returns A new instance of StructuredOutputParser. + */ + static fromNamesAndDescriptions(schemas) { + const zodSchema = external_exports.object(Object.fromEntries(Object.entries(schemas).map(([name, description]) => [name, external_exports.string().describe(description)]))); + return new this(zodSchema); + } + /** + * Returns a markdown code snippet with a JSON object formatted according + * to the schema. + * @param options Optional. The options for formatting the instructions + * @returns A markdown code snippet with a JSON object formatted according to the schema. + */ + getFormatInstructions() { + return `You must format your output as a JSON value that adheres to a given "JSON Schema" instance. + +"JSON Schema" is a declarative language that allows you to annotate and validate JSON documents. + +For example, the example "JSON Schema" instance {{"properties": {{"foo": {{"description": "a list of test words", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}} +would match an object with one required property, "foo". The "type" property specifies "foo" must be an "array", and the "description" property semantically describes it as "a list of test words". The items within "foo" must be strings. +Thus, the object {{"foo": ["bar", "baz"]}} is a well-formatted instance of this example "JSON Schema". The object {{"properties": {{"foo": ["bar", "baz"]}}}} is not well-formatted. + +Your output will be parsed and type-checked according to the provided schema instance, so make sure all fields in your output match the schema exactly and there are no trailing commas! + +Here is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock: +\`\`\`json +${JSON.stringify(toJsonSchema(this.schema))} +\`\`\` +`; + } + /** + * Parses the given text according to the schema. + * @param text The text to parse + * @returns The parsed output. + */ + async parse(text) { + try { + const json = text.includes("```") ? text.trim().split(/```(?:json)?/)[1] : text.trim(); + const escapedJson = json.replace(/"([^"\\]*(\\.[^"\\]*)*)"/g, (_match, capturedGroup) => { + const escapedInsideQuotes = capturedGroup.replace(/\n/g, "\\n"); + return `"${escapedInsideQuotes}"`; + }).replace(/\n/g, ""); + return await interopParseAsync(this.schema, JSON.parse(escapedJson)); + } catch (e) { + throw new OutputParserException(`Failed to parse. Text: "${text}". Error: ${e}`, text); + } + } +}; +var JsonMarkdownStructuredOutputParser = class extends StructuredOutputParser { + static lc_name() { + return "JsonMarkdownStructuredOutputParser"; + } + getFormatInstructions(options) { + const interpolationDepth = options?.interpolationDepth ?? 1; + if (interpolationDepth < 1) { + throw new Error("f string interpolation depth must be at least 1"); + } + return `Return a markdown code snippet with a JSON object formatted to look like: +\`\`\`json +${this._schemaToInstruction(toJsonSchema(this.schema)).replaceAll("{", "{".repeat(interpolationDepth)).replaceAll("}", "}".repeat(interpolationDepth))} +\`\`\``; + } + _schemaToInstruction(schemaInput, indent = 2) { + const schema = schemaInput; + if ("type" in schema) { + let nullable = false; + let type; + if (Array.isArray(schema.type)) { + const nullIdx = schema.type.findIndex((type2) => type2 === "null"); + if (nullIdx !== -1) { + nullable = true; + schema.type.splice(nullIdx, 1); + } + type = schema.type.join(" | "); + } else { + type = schema.type; + } + if (schema.type === "object" && schema.properties) { + const description2 = schema.description ? ` // ${schema.description}` : ""; + const properties = Object.entries(schema.properties).map(([key, value]) => { + const isOptional = schema.required?.includes(key) ? "" : " (optional)"; + return `${" ".repeat(indent)}"${key}": ${this._schemaToInstruction(value, indent + 2)}${isOptional}`; + }).join("\n"); + return `{ +${properties} +${" ".repeat(indent - 2)}}${description2}`; + } + if (schema.type === "array" && schema.items) { + const description2 = schema.description ? ` // ${schema.description}` : ""; + return `array[ +${" ".repeat(indent)}${this._schemaToInstruction(schema.items, indent + 2)} +${" ".repeat(indent - 2)}] ${description2}`; + } + const isNullable = nullable ? " (nullable)" : ""; + const description = schema.description ? ` // ${schema.description}` : ""; + return `${type}${description}${isNullable}`; + } + if ("anyOf" in schema) { + return schema.anyOf.map((s) => this._schemaToInstruction(s, indent)).join(` +${" ".repeat(indent - 2)}`); + } + throw new Error("unsupported schema type"); + } + static fromZodSchema(schema) { + return new this(schema); + } + static fromNamesAndDescriptions(schemas) { + const zodSchema = external_exports.object(Object.fromEntries(Object.entries(schemas).map(([name, description]) => [name, external_exports.string().describe(description)]))); + return new this(zodSchema); + } +}; +var AsymmetricStructuredOutputParser = class extends BaseOutputParser { + constructor({ inputSchema }) { + super(...arguments); + Object.defineProperty(this, "structuredInputParser", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.structuredInputParser = new JsonMarkdownStructuredOutputParser(inputSchema); + } + async parse(text) { + let parsedInput; + try { + parsedInput = await this.structuredInputParser.parse(text); + } catch (e) { + throw new OutputParserException(`Failed to parse. Text: "${text}". Error: ${e}`, text); + } + return this.outputProcessor(parsedInput); + } + getFormatInstructions() { + return this.structuredInputParser.getFormatInstructions(); + } +}; + +// node_modules/@langchain/core/dist/utils/json_patch.js +var json_patch_exports = {}; +__export(json_patch_exports, { + applyPatch: () => applyPatch, + compare: () => compare +}); +init_fast_json_patch(); + +// node_modules/@langchain/core/dist/output_parsers/json.js +init_json(); +var JsonOutputParser = class extends BaseCumulativeTransformOutputParser { + constructor() { + super(...arguments); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain_core", "output_parsers"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + } + static lc_name() { + return "JsonOutputParser"; + } + /** @internal */ + _concatOutputChunks(first, second) { + if (this.diff) { + return super._concatOutputChunks(first, second); + } + return second; + } + _diff(prev, next) { + if (!next) { + return void 0; + } + if (!prev) { + return [{ op: "replace", path: "", value: next }]; + } + return compare(prev, next); + } + // This should actually return Partial, but there's no way + // to specify emitted chunks as instances separate from the main output type. + async parsePartialResult(generations) { + return parseJsonMarkdown(generations[0].text); + } + async parse(text) { + return parseJsonMarkdown(text, JSON.parse); + } + getFormatInstructions() { + return ""; + } +}; + +// node_modules/@langchain/core/dist/utils/sax-js/sax.js +var initializeSax = function() { + const sax2 = {}; + sax2.parser = function(strict, opt) { + return new SAXParser(strict, opt); + }; + sax2.SAXParser = SAXParser; + sax2.SAXStream = SAXStream; + sax2.createStream = createStream; + sax2.MAX_BUFFER_LENGTH = 64 * 1024; + const buffers = [ + "comment", + "sgmlDecl", + "textNode", + "tagName", + "doctype", + "procInstName", + "procInstBody", + "entity", + "attribName", + "attribValue", + "cdata", + "script" + ]; + sax2.EVENTS = [ + "text", + "processinginstruction", + "sgmldeclaration", + "doctype", + "comment", + "opentagstart", + "attribute", + "opentag", + "closetag", + "opencdata", + "cdata", + "closecdata", + "error", + "end", + "ready", + "script", + "opennamespace", + "closenamespace" + ]; + function SAXParser(strict, opt) { + if (!(this instanceof SAXParser)) { + return new SAXParser(strict, opt); + } + var parser = this; + clearBuffers(parser); + parser.q = parser.c = ""; + parser.bufferCheckPosition = sax2.MAX_BUFFER_LENGTH; + parser.opt = opt || {}; + parser.opt.lowercase = parser.opt.lowercase || parser.opt.lowercasetags; + parser.looseCase = parser.opt.lowercase ? "toLowerCase" : "toUpperCase"; + parser.tags = []; + parser.closed = parser.closedRoot = parser.sawRoot = false; + parser.tag = parser.error = null; + parser.strict = !!strict; + parser.noscript = !!(strict || parser.opt.noscript); + parser.state = S.BEGIN; + parser.strictEntities = parser.opt.strictEntities; + parser.ENTITIES = parser.strictEntities ? Object.create(sax2.XML_ENTITIES) : Object.create(sax2.ENTITIES); + parser.attribList = []; + if (parser.opt.xmlns) { + parser.ns = Object.create(rootNS); + } + parser.trackPosition = parser.opt.position !== false; + if (parser.trackPosition) { + parser.position = parser.line = parser.column = 0; + } + emit(parser, "onready"); + } + if (!Object.create) { + Object.create = function(o) { + function F() { + } + F.prototype = o; + var newf = new F(); + return newf; + }; + } + if (!Object.keys) { + Object.keys = function(o) { + var a = []; + for (var i in o) + if (o.hasOwnProperty(i)) + a.push(i); + return a; + }; + } + function checkBufferLength(parser) { + var maxAllowed = Math.max(sax2.MAX_BUFFER_LENGTH, 10); + var maxActual = 0; + for (var i = 0, l = buffers.length; i < l; i++) { + var len = parser[buffers[i]].length; + if (len > maxAllowed) { + switch (buffers[i]) { + case "textNode": + closeText(parser); + break; + case "cdata": + emitNode(parser, "oncdata", parser.cdata); + parser.cdata = ""; + break; + case "script": + emitNode(parser, "onscript", parser.script); + parser.script = ""; + break; + default: + error(parser, "Max buffer length exceeded: " + buffers[i]); + } + } + maxActual = Math.max(maxActual, len); + } + var m = sax2.MAX_BUFFER_LENGTH - maxActual; + parser.bufferCheckPosition = m + parser.position; + } + function clearBuffers(parser) { + for (var i = 0, l = buffers.length; i < l; i++) { + parser[buffers[i]] = ""; + } + } + function flushBuffers(parser) { + closeText(parser); + if (parser.cdata !== "") { + emitNode(parser, "oncdata", parser.cdata); + parser.cdata = ""; + } + if (parser.script !== "") { + emitNode(parser, "onscript", parser.script); + parser.script = ""; + } + } + SAXParser.prototype = { + end: function() { + end(this); + }, + write, + resume: function() { + this.error = null; + return this; + }, + close: function() { + return this.write(null); + }, + flush: function() { + flushBuffers(this); + } + }; + var Stream = ReadableStream; + if (!Stream) + Stream = function() { + }; + var streamWraps = sax2.EVENTS.filter(function(ev) { + return ev !== "error" && ev !== "end"; + }); + function createStream(strict, opt) { + return new SAXStream(strict, opt); + } + function SAXStream(strict, opt) { + if (!(this instanceof SAXStream)) { + return new SAXStream(strict, opt); + } + Stream.apply(this); + this._parser = new SAXParser(strict, opt); + this.writable = true; + this.readable = true; + var me = this; + this._parser.onend = function() { + me.emit("end"); + }; + this._parser.onerror = function(er) { + me.emit("error", er); + me._parser.error = null; + }; + this._decoder = null; + streamWraps.forEach(function(ev) { + Object.defineProperty(me, "on" + ev, { + get: function() { + return me._parser["on" + ev]; + }, + set: function(h) { + if (!h) { + me.removeAllListeners(ev); + me._parser["on" + ev] = h; + return h; + } + me.on(ev, h); + }, + enumerable: true, + configurable: false + }); + }); + } + SAXStream.prototype = Object.create(Stream.prototype, { + constructor: { + value: SAXStream + } + }); + SAXStream.prototype.write = function(data) { + this._parser.write(data.toString()); + this.emit("data", data); + return true; + }; + SAXStream.prototype.end = function(chunk) { + if (chunk && chunk.length) { + this.write(chunk); + } + this._parser.end(); + return true; + }; + SAXStream.prototype.on = function(ev, handler) { + var me = this; + if (!me._parser["on" + ev] && streamWraps.indexOf(ev) !== -1) { + me._parser["on" + ev] = function() { + var args = arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments); + args.splice(0, 0, ev); + me.emit.apply(me, args); + }; + } + return Stream.prototype.on.call(me, ev, handler); + }; + var CDATA = "[CDATA["; + var DOCTYPE = "DOCTYPE"; + var XML_NAMESPACE = "http://www.w3.org/XML/1998/namespace"; + var XMLNS_NAMESPACE = "http://www.w3.org/2000/xmlns/"; + var rootNS = { xml: XML_NAMESPACE, xmlns: XMLNS_NAMESPACE }; + var nameStart = /[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/; + var nameBody = /[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/; + var entityStart = /[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/; + var entityBody = /[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/; + function isWhitespace2(c) { + return c === " " || c === "\n" || c === "\r" || c === " "; + } + function isQuote(c) { + return c === '"' || c === "'"; + } + function isAttribEnd(c) { + return c === ">" || isWhitespace2(c); + } + function isMatch(regex2, c) { + return regex2.test(c); + } + function notMatch(regex2, c) { + return !isMatch(regex2, c); + } + var S = 0; + sax2.STATE = { + BEGIN: S++, + // leading byte order mark or whitespace + BEGIN_WHITESPACE: S++, + // leading whitespace + TEXT: S++, + // general stuff + TEXT_ENTITY: S++, + // & and such. + OPEN_WAKA: S++, + // < + SGML_DECL: S++, + // + SCRIPT: S++, + // + + + + + diff --git a/browser/base/content/assistant/auth-callback.html b/browser/base/content/assistant/auth-callback.html new file mode 100644 index 0000000000000..05b1a587c2d63 --- /dev/null +++ b/browser/base/content/assistant/auth-callback.html @@ -0,0 +1,153 @@ + + + + + + Oasis Browser - Authentication Callback + + + +
+
+
Processing authentication...
+
+
+ + + + diff --git a/browser/base/content/assistant/auth-guard.js b/browser/base/content/assistant/auth-guard.js new file mode 100644 index 0000000000000..f8990da8cd38a --- /dev/null +++ b/browser/base/content/assistant/auth-guard.js @@ -0,0 +1,93 @@ +// Authentication Guard for AI Assistant +// This module provides authentication checks for the AI assistant API calls + +(function() { + 'use strict'; + + // Store original functions + let originalRouteRemote = null; + let originalChatRemote = null; + + // Authentication check function + function checkAuthentication() { + const authState = window.oasisAuthState; + if (!authState || !authState.isAuthenticated) { + console.warn('AI Assistant: Unauthenticated access attempt blocked'); + throw new Error('Authentication required: Please sign in to use the AI assistant'); + } + return true; + } + + // Wrapper for routeRemote function + async function protectedRouteRemote(system, messages, options) { + checkAuthentication(); + + const authState = window.oasisAuthState; + console.log(`AI Assistant: Authenticated request from user ${authState?.user?.email || 'unknown'}`); + + return originalRouteRemote(system, messages, options); + } + + // Wrapper for chatRemote function + async function protectedChatRemote(system, messages) { + checkAuthentication(); + + const authState = window.oasisAuthState; + console.log(`AI Assistant: Authenticated chat request from user ${authState?.user?.email || 'unknown'}`); + + return originalChatRemote(system, messages); + } + + // Function to install authentication guards + function installAuthGuards() { + // Wait for the assistant bundle to load + if (typeof window.runAssistantStream === 'undefined') { + setTimeout(installAuthGuards, 100); + return; + } + + // Try to access the proxy client functions + // Since they're bundled, we need to intercept them at the module level + console.log('Installing authentication guards for AI Assistant...'); + + // The functions are likely in the global scope or accessible via the bundle + // We'll need to patch them when they become available + const checkForFunctions = () => { + // Look for the functions in various possible locations + if (window.routeRemote && !originalRouteRemote) { + originalRouteRemote = window.routeRemote; + window.routeRemote = protectedRouteRemote; + console.log('Protected routeRemote function'); + } + + if (window.chatRemote && !originalChatRemote) { + originalChatRemote = window.chatRemote; + window.chatRemote = protectedChatRemote; + console.log('Protected chatRemote function'); + } + + // If we haven't found them yet, keep checking + if (!originalRouteRemote || !originalChatRemote) { + setTimeout(checkForFunctions, 100); + } else { + console.log('Authentication guards successfully installed'); + } + }; + + checkForFunctions(); + } + + // Install guards when the page loads + if (document.readyState === 'loading') { + document.addEventListener('DOMContentLoaded', installAuthGuards); + } else { + installAuthGuards(); + } + + // Also try to install immediately + installAuthGuards(); + + // Export for manual installation if needed + window.installAuthGuards = installAuthGuards; + +})(); diff --git a/browser/base/content/assistant/bootstrap.js b/browser/base/content/assistant/bootstrap.js new file mode 100644 index 0000000000000..9eaa02d37a784 --- /dev/null +++ b/browser/base/content/assistant/bootstrap.js @@ -0,0 +1,32 @@ +// Runs in the chrome-privileged browser window. +// Wires up the assistant button to toggle the assistant sidebar via command +(function () { + window.addEventListener("load", function() { + const assistantToggle = document.getElementById("assistant-button"); + + if (assistantToggle) { + // Use the command system to toggle the sidebar + assistantToggle.setAttribute("command", "viewOasisAssistantSidebar"); + + // Also handle direct clicks as fallback + assistantToggle.addEventListener("click", function(event) { + // If the command attribute doesn't work, manually execute the command + const command = "viewOasisAssistantSidebar"; + const commandElement = document.getElementById(command); + + if (commandElement && typeof commandElement.doCommand === "function") { + commandElement.doCommand(); + } else { + // Fallback: try to access SidebarController directly + try { + if (typeof SidebarController !== "undefined" && SidebarController.show) { + SidebarController.show(command); + } + } catch (e) { + console.error("Failed to open assistant sidebar:", e); + } + } + }); + } + }, { once: true }); +})(); diff --git a/browser/base/content/assistant/build/.gitignore b/browser/base/content/assistant/build/.gitignore new file mode 100644 index 0000000000000..504afef81fbad --- /dev/null +++ b/browser/base/content/assistant/build/.gitignore @@ -0,0 +1,2 @@ +node_modules/ +package-lock.json diff --git a/browser/base/content/assistant/build/esbuild.config.mjs b/browser/base/content/assistant/build/esbuild.config.mjs new file mode 100644 index 0000000000000..adc2377650d70 --- /dev/null +++ b/browser/base/content/assistant/build/esbuild.config.mjs @@ -0,0 +1,27 @@ +import esbuild from "esbuild"; + +const OASIS_API_BASE = "https://segvax3qd7tkhcckzrijydbz6m0cijdu.lambda-url.us-east-2.on.aws/"; +const OASIS_TRANSCRIBE_URL = "https://uzfhm4tjnp7k5lpf2vkyqmrpxq0pxxed.lambda-url.us-east-2.on.aws/"; // Add your transcription lambda URL here +const AWS_REGION = "us-east-2"; +const COGNITO_IDENTITY_POOL_ID = "us-east-2:21ce1894-9a97-48ac-8741-b69f7eafea1c"; +const SUPABASE_URL = "https://wvclepquxxczgrukfqyr.supabase.co"; +const SUPABASE_ANON_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Ind2Y2xlcHF1eHhjemdydWtmcXlyIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTUwODU5OTksImV4cCI6MjA3MDY2MTk5OX0.T-hZ_8QxtVnOt0mtCY_Zch87SYEcsyQZwnvvFAtZiNY"; + +await esbuild.build({ + entryPoints: ["./src/assistant.ts"], + bundle: true, + platform: "browser", + format: "esm", + target: "es2022", + outfile: "../assistant.bundle.js", + sourcemap: false, + logLevel: "info", + define: { + "process.env.OASIS_API_BASE": JSON.stringify(OASIS_API_BASE), + "process.env.OASIS_TRANSCRIBE_URL": JSON.stringify(OASIS_TRANSCRIBE_URL), + "process.env.AWS_REGION": JSON.stringify(AWS_REGION), + "process.env.COGNITO_IDENTITY_POOL_ID": JSON.stringify(COGNITO_IDENTITY_POOL_ID), + "process.env.SUPABASE_URL": JSON.stringify(SUPABASE_URL), + "process.env.SUPABASE_ANON_KEY": JSON.stringify(SUPABASE_ANON_KEY), + }, +}); diff --git a/browser/base/content/assistant/build/package-lock.json b/browser/base/content/assistant/build/package-lock.json new file mode 100644 index 0000000000000..626c9f3ad10ed --- /dev/null +++ b/browser/base/content/assistant/build/package-lock.json @@ -0,0 +1,3512 @@ +{ + "name": "assistant-bundle", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "assistant-bundle", + "dependencies": { + "@aws-crypto/sha256-js": "^5.2.0", + "@aws-sdk/client-s3": "^3.896.0", + "@aws-sdk/credential-provider-cognito-identity": "^3.901.0", + "@aws-sdk/protocol-http": "^3.370.0", + "@aws-sdk/signature-v4": "^3.370.0", + "@langchain/core": "^0.3.72", + "@langchain/langgraph": "^0.4.6", + "@supabase/supabase-js": "^2.45.4", + "idb": "^8.0.3", + "minisearch": "^7.2.0", + "zod": "^3.25.76" + }, + "devDependencies": { + "dotenv": "^17.2.1", + "esbuild": "^0.25.9", + "typescript": "^5.5.4" + } + }, + "node_modules/@aws-crypto/crc32": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@aws-crypto/crc32/-/crc32-5.2.0.tgz", + "integrity": "sha512-nLbCWqQNgUiwwtFsen1AdzAtvuLRsQS8rYgMuxCrdKf9kOssamGLuPwyTY9wyYblNr9+1XM8v6zoDTPPSIeANg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/util": "^5.2.0", + "@aws-sdk/types": "^3.222.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-crypto/crc32c": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@aws-crypto/crc32c/-/crc32c-5.2.0.tgz", + "integrity": "sha512-+iWb8qaHLYKrNvGRbiYRHSdKRWhto5XlZUEBwDjYNf+ly5SVYG6zEoYIdxvf5R3zyeP16w4PLBn3rH1xc74Rag==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/util": "^5.2.0", + "@aws-sdk/types": "^3.222.0", + "tslib": "^2.6.2" + } + }, + "node_modules/@aws-crypto/sha1-browser": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@aws-crypto/sha1-browser/-/sha1-browser-5.2.0.tgz", + "integrity": "sha512-OH6lveCFfcDjX4dbAvCFSYUjJZjDr/3XJ3xHtjn3Oj5b9RjojQo8npoLeA/bNwkOkrSQ0wgrHzXk4tDRxGKJeg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/supports-web-crypto": "^5.2.0", + "@aws-crypto/util": "^5.2.0", + "@aws-sdk/types": "^3.222.0", + "@aws-sdk/util-locate-window": "^3.0.0", + "@smithy/util-utf8": "^2.0.0", + "tslib": "^2.6.2" + } + }, + "node_modules/@aws-crypto/sha1-browser/node_modules/@smithy/is-array-buffer": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@smithy/is-array-buffer/-/is-array-buffer-2.2.0.tgz", + "integrity": "sha512-GGP3O9QFD24uGeAXYUjwSTXARoqpZykHadOmA8G5vfJPK0/DC67qa//0qvqrJzL1xc8WQWX7/yc7fwudjPHPhA==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-crypto/sha1-browser/node_modules/@smithy/util-buffer-from": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-buffer-from/-/util-buffer-from-2.2.0.tgz", + "integrity": "sha512-IJdWBbTcMQ6DA0gdNhh/BwrLkDR+ADW5Kr1aZmd4k3DIF6ezMV4R2NIAmT08wQJ3yUK82thHWmC/TnK/wpMMIA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/is-array-buffer": "^2.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-crypto/sha1-browser/node_modules/@smithy/util-utf8": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-2.3.0.tgz", + "integrity": "sha512-R8Rdn8Hy72KKcebgLiv8jQcQkXoLMOGGv5uI1/k0l+snqkOzQ1R0ChUBCxWMlBsFMekWjq0wRudIweFs7sKT5A==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/util-buffer-from": "^2.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-crypto/sha256-browser": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@aws-crypto/sha256-browser/-/sha256-browser-5.2.0.tgz", + "integrity": "sha512-AXfN/lGotSQwu6HNcEsIASo7kWXZ5HYWvfOmSNKDsEqC4OashTp8alTmaz+F7TC2L083SFv5RdB+qU3Vs1kZqw==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/sha256-js": "^5.2.0", + "@aws-crypto/supports-web-crypto": "^5.2.0", + "@aws-crypto/util": "^5.2.0", + "@aws-sdk/types": "^3.222.0", + "@aws-sdk/util-locate-window": "^3.0.0", + "@smithy/util-utf8": "^2.0.0", + "tslib": "^2.6.2" + } + }, + "node_modules/@aws-crypto/sha256-browser/node_modules/@smithy/is-array-buffer": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@smithy/is-array-buffer/-/is-array-buffer-2.2.0.tgz", + "integrity": "sha512-GGP3O9QFD24uGeAXYUjwSTXARoqpZykHadOmA8G5vfJPK0/DC67qa//0qvqrJzL1xc8WQWX7/yc7fwudjPHPhA==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-crypto/sha256-browser/node_modules/@smithy/util-buffer-from": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-buffer-from/-/util-buffer-from-2.2.0.tgz", + "integrity": "sha512-IJdWBbTcMQ6DA0gdNhh/BwrLkDR+ADW5Kr1aZmd4k3DIF6ezMV4R2NIAmT08wQJ3yUK82thHWmC/TnK/wpMMIA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/is-array-buffer": "^2.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-crypto/sha256-browser/node_modules/@smithy/util-utf8": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-2.3.0.tgz", + "integrity": "sha512-R8Rdn8Hy72KKcebgLiv8jQcQkXoLMOGGv5uI1/k0l+snqkOzQ1R0ChUBCxWMlBsFMekWjq0wRudIweFs7sKT5A==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/util-buffer-from": "^2.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-crypto/sha256-js": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@aws-crypto/sha256-js/-/sha256-js-5.2.0.tgz", + "integrity": "sha512-FFQQyu7edu4ufvIZ+OadFpHHOt+eSTBaYaki44c+akjg7qZg9oOQeLlk77F6tSYqjDAFClrHJk9tMf0HdVyOvA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/util": "^5.2.0", + "@aws-sdk/types": "^3.222.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-crypto/supports-web-crypto": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@aws-crypto/supports-web-crypto/-/supports-web-crypto-5.2.0.tgz", + "integrity": "sha512-iAvUotm021kM33eCdNfwIN//F77/IADDSs58i+MDaOqFrVjZo9bAal0NK7HurRuWLLpF1iLX7gbWrjHjeo+YFg==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + } + }, + "node_modules/@aws-crypto/util": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@aws-crypto/util/-/util-5.2.0.tgz", + "integrity": "sha512-4RkU9EsI6ZpBve5fseQlGNUWKMa1RLPQ1dnjnQoe07ldfIzcsGb5hC5W0Dm7u423KWzawlrpbjXBrXCEv9zazQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "^3.222.0", + "@smithy/util-utf8": "^2.0.0", + "tslib": "^2.6.2" + } + }, + "node_modules/@aws-crypto/util/node_modules/@smithy/is-array-buffer": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@smithy/is-array-buffer/-/is-array-buffer-2.2.0.tgz", + "integrity": "sha512-GGP3O9QFD24uGeAXYUjwSTXARoqpZykHadOmA8G5vfJPK0/DC67qa//0qvqrJzL1xc8WQWX7/yc7fwudjPHPhA==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-crypto/util/node_modules/@smithy/util-buffer-from": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-buffer-from/-/util-buffer-from-2.2.0.tgz", + "integrity": "sha512-IJdWBbTcMQ6DA0gdNhh/BwrLkDR+ADW5Kr1aZmd4k3DIF6ezMV4R2NIAmT08wQJ3yUK82thHWmC/TnK/wpMMIA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/is-array-buffer": "^2.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-crypto/util/node_modules/@smithy/util-utf8": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-2.3.0.tgz", + "integrity": "sha512-R8Rdn8Hy72KKcebgLiv8jQcQkXoLMOGGv5uI1/k0l+snqkOzQ1R0ChUBCxWMlBsFMekWjq0wRudIweFs7sKT5A==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/util-buffer-from": "^2.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-sdk/client-cognito-identity": { + "version": "3.901.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-cognito-identity/-/client-cognito-identity-3.901.0.tgz", + "integrity": "sha512-cDJ+npYeAiS9u/52RwR0AHgneEF+rnyxiYm4d/c4FTI6xTQId3hSD0zdK0EgZ1wfoMk0/+5Ft6mYk0V6JN+cbQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/sha256-browser": "5.2.0", + "@aws-crypto/sha256-js": "5.2.0", + "@aws-sdk/core": "3.901.0", + "@aws-sdk/credential-provider-node": "3.901.0", + "@aws-sdk/middleware-host-header": "3.901.0", + "@aws-sdk/middleware-logger": "3.901.0", + "@aws-sdk/middleware-recursion-detection": "3.901.0", + "@aws-sdk/middleware-user-agent": "3.901.0", + "@aws-sdk/region-config-resolver": "3.901.0", + "@aws-sdk/types": "3.901.0", + "@aws-sdk/util-endpoints": "3.901.0", + "@aws-sdk/util-user-agent-browser": "3.901.0", + "@aws-sdk/util-user-agent-node": "3.901.0", + "@smithy/config-resolver": "^4.3.0", + "@smithy/core": "^3.14.0", + "@smithy/fetch-http-handler": "^5.3.0", + "@smithy/hash-node": "^4.2.0", + "@smithy/invalid-dependency": "^4.2.0", + "@smithy/middleware-content-length": "^4.2.0", + "@smithy/middleware-endpoint": "^4.3.0", + "@smithy/middleware-retry": "^4.4.0", + "@smithy/middleware-serde": "^4.2.0", + "@smithy/middleware-stack": "^4.2.0", + "@smithy/node-config-provider": "^4.3.0", + "@smithy/node-http-handler": "^4.3.0", + "@smithy/protocol-http": "^5.3.0", + "@smithy/smithy-client": "^4.7.0", + "@smithy/types": "^4.6.0", + "@smithy/url-parser": "^4.2.0", + "@smithy/util-base64": "^4.2.0", + "@smithy/util-body-length-browser": "^4.2.0", + "@smithy/util-body-length-node": "^4.2.0", + "@smithy/util-defaults-mode-browser": "^4.2.0", + "@smithy/util-defaults-mode-node": "^4.2.0", + "@smithy/util-endpoints": "^3.2.0", + "@smithy/util-middleware": "^4.2.0", + "@smithy/util-retry": "^4.2.0", + "@smithy/util-utf8": "^4.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/client-sso": { + "version": "3.901.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-sso/-/client-sso-3.901.0.tgz", + "integrity": "sha512-sGyDjjkJ7ppaE+bAKL/Q5IvVCxtoyBIzN+7+hWTS/mUxWJ9EOq9238IqmVIIK6sYNIzEf9yhobfMARasPYVTNg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/sha256-browser": "5.2.0", + "@aws-crypto/sha256-js": "5.2.0", + "@aws-sdk/core": "3.901.0", + "@aws-sdk/middleware-host-header": "3.901.0", + "@aws-sdk/middleware-logger": "3.901.0", + "@aws-sdk/middleware-recursion-detection": "3.901.0", + "@aws-sdk/middleware-user-agent": "3.901.0", + "@aws-sdk/region-config-resolver": "3.901.0", + "@aws-sdk/types": "3.901.0", + "@aws-sdk/util-endpoints": "3.901.0", + "@aws-sdk/util-user-agent-browser": "3.901.0", + "@aws-sdk/util-user-agent-node": "3.901.0", + "@smithy/config-resolver": "^4.3.0", + "@smithy/core": "^3.14.0", + "@smithy/fetch-http-handler": "^5.3.0", + "@smithy/hash-node": "^4.2.0", + "@smithy/invalid-dependency": "^4.2.0", + "@smithy/middleware-content-length": "^4.2.0", + "@smithy/middleware-endpoint": "^4.3.0", + "@smithy/middleware-retry": "^4.4.0", + "@smithy/middleware-serde": "^4.2.0", + "@smithy/middleware-stack": "^4.2.0", + "@smithy/node-config-provider": "^4.3.0", + "@smithy/node-http-handler": "^4.3.0", + "@smithy/protocol-http": "^5.3.0", + "@smithy/smithy-client": "^4.7.0", + "@smithy/types": "^4.6.0", + "@smithy/url-parser": "^4.2.0", + "@smithy/util-base64": "^4.2.0", + "@smithy/util-body-length-browser": "^4.2.0", + "@smithy/util-body-length-node": "^4.2.0", + "@smithy/util-defaults-mode-browser": "^4.2.0", + "@smithy/util-defaults-mode-node": "^4.2.0", + "@smithy/util-endpoints": "^3.2.0", + "@smithy/util-middleware": "^4.2.0", + "@smithy/util-retry": "^4.2.0", + "@smithy/util-utf8": "^4.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core": { + "version": "3.901.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/core/-/core-3.901.0.tgz", + "integrity": "sha512-brKAc3y64tdhyuEf+OPIUln86bRTqkLgb9xkd6kUdIeA5+qmp/N6amItQz+RN4k4O3kqkCPYnAd3LonTKluobw==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.901.0", + "@aws-sdk/xml-builder": "3.901.0", + "@smithy/core": "^3.14.0", + "@smithy/node-config-provider": "^4.3.0", + "@smithy/property-provider": "^4.2.0", + "@smithy/protocol-http": "^5.3.0", + "@smithy/signature-v4": "^5.3.0", + "@smithy/smithy-client": "^4.7.0", + "@smithy/types": "^4.6.0", + "@smithy/util-base64": "^4.2.0", + "@smithy/util-middleware": "^4.2.0", + "@smithy/util-utf8": "^4.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/credential-provider-env": { + "version": "3.901.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-env/-/credential-provider-env-3.901.0.tgz", + "integrity": "sha512-5hAdVl3tBuARh3zX5MLJ1P/d+Kr5kXtDU3xm1pxUEF4xt2XkEEpwiX5fbkNkz2rbh3BCt2gOHsAbh6b3M7n+DA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "3.901.0", + "@aws-sdk/types": "3.901.0", + "@smithy/property-provider": "^4.2.0", + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/credential-provider-http": { + "version": "3.901.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-http/-/credential-provider-http-3.901.0.tgz", + "integrity": "sha512-Ggr7+0M6QZEsrqRkK7iyJLf4LkIAacAxHz9c4dm9hnDdU7vqrlJm6g73IxMJXWN1bIV7IxfpzB11DsRrB/oNjQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "3.901.0", + "@aws-sdk/types": "3.901.0", + "@smithy/fetch-http-handler": "^5.3.0", + "@smithy/node-http-handler": "^4.3.0", + "@smithy/property-provider": "^4.2.0", + "@smithy/protocol-http": "^5.3.0", + "@smithy/smithy-client": "^4.7.0", + "@smithy/types": "^4.6.0", + "@smithy/util-stream": "^4.4.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/credential-provider-ini": { + "version": "3.901.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-ini/-/credential-provider-ini-3.901.0.tgz", + "integrity": "sha512-zxadcDS0hNJgv8n4hFYJNOXyfjaNE1vvqIiF/JzZSQpSSYXzCd+WxXef5bQh+W3giDtRUmkvP5JLbamEFjZKyw==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "3.901.0", + "@aws-sdk/credential-provider-env": "3.901.0", + "@aws-sdk/credential-provider-http": "3.901.0", + "@aws-sdk/credential-provider-process": "3.901.0", + "@aws-sdk/credential-provider-sso": "3.901.0", + "@aws-sdk/credential-provider-web-identity": "3.901.0", + "@aws-sdk/nested-clients": "3.901.0", + "@aws-sdk/types": "3.901.0", + "@smithy/credential-provider-imds": "^4.2.0", + "@smithy/property-provider": "^4.2.0", + "@smithy/shared-ini-file-loader": "^4.3.0", + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/credential-provider-node": { + "version": "3.901.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-node/-/credential-provider-node-3.901.0.tgz", + "integrity": "sha512-dPuFzMF7L1s/lQyT3wDxqLe82PyTH+5o1jdfseTEln64LJMl0ZMWaKX/C1UFNDxaTd35Cgt1bDbjjAWHMiKSFQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/credential-provider-env": "3.901.0", + "@aws-sdk/credential-provider-http": "3.901.0", + "@aws-sdk/credential-provider-ini": "3.901.0", + "@aws-sdk/credential-provider-process": "3.901.0", + "@aws-sdk/credential-provider-sso": "3.901.0", + "@aws-sdk/credential-provider-web-identity": "3.901.0", + "@aws-sdk/types": "3.901.0", + "@smithy/credential-provider-imds": "^4.2.0", + "@smithy/property-provider": "^4.2.0", + "@smithy/shared-ini-file-loader": "^4.3.0", + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/credential-provider-process": { + "version": "3.901.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-process/-/credential-provider-process-3.901.0.tgz", + "integrity": "sha512-/IWgmgM3Cl1wTdJA5HqKMAojxLkYchh5kDuphApxKhupLu6Pu0JBOHU8A5GGeFvOycyaVwosod6zDduINZxe+A==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "3.901.0", + "@aws-sdk/types": "3.901.0", + "@smithy/property-provider": "^4.2.0", + "@smithy/shared-ini-file-loader": "^4.3.0", + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/credential-provider-sso": { + "version": "3.901.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-sso/-/credential-provider-sso-3.901.0.tgz", + "integrity": "sha512-SjmqZQHmqFSET7+6xcZgtH7yEyh5q53LN87GqwYlJZ6KJ5oNw11acUNEhUOL1xTSJEvaWqwTIkS2zqrzLcM9bw==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/client-sso": "3.901.0", + "@aws-sdk/core": "3.901.0", + "@aws-sdk/token-providers": "3.901.0", + "@aws-sdk/types": "3.901.0", + "@smithy/property-provider": "^4.2.0", + "@smithy/shared-ini-file-loader": "^4.3.0", + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/credential-provider-web-identity": { + "version": "3.901.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-web-identity/-/credential-provider-web-identity-3.901.0.tgz", + "integrity": "sha512-NYjy/6NLxH9m01+pfpB4ql8QgAorJcu8tw69kzHwUd/ql6wUDTbC7HcXqtKlIwWjzjgj2BKL7j6SyFapgCuafA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "3.901.0", + "@aws-sdk/nested-clients": "3.901.0", + "@aws-sdk/types": "3.901.0", + "@smithy/property-provider": "^4.2.0", + "@smithy/shared-ini-file-loader": "^4.3.0", + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/middleware-host-header": { + "version": "3.901.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-host-header/-/middleware-host-header-3.901.0.tgz", + "integrity": "sha512-yWX7GvRmqBtbNnUW7qbre3GvZmyYwU0WHefpZzDTYDoNgatuYq6LgUIQ+z5C04/kCRoFkAFrHag8a3BXqFzq5A==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.901.0", + "@smithy/protocol-http": "^5.3.0", + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/middleware-logger": { + "version": "3.901.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-logger/-/middleware-logger-3.901.0.tgz", + "integrity": "sha512-UoHebjE7el/tfRo8/CQTj91oNUm+5Heus5/a4ECdmWaSCHCS/hXTsU3PTTHAY67oAQR8wBLFPfp3mMvXjB+L2A==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.901.0", + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/middleware-recursion-detection": { + "version": "3.901.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-recursion-detection/-/middleware-recursion-detection-3.901.0.tgz", + "integrity": "sha512-Wd2t8qa/4OL0v/oDpCHHYkgsXJr8/ttCxrvCKAt0H1zZe2LlRhY9gpDVKqdertfHrHDj786fOvEQA28G1L75Dg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.901.0", + "@aws/lambda-invoke-store": "^0.0.1", + "@smithy/protocol-http": "^5.3.0", + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/middleware-user-agent": { + "version": "3.901.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-user-agent/-/middleware-user-agent-3.901.0.tgz", + "integrity": "sha512-Zby4F03fvD9xAgXGPywyk4bC1jCbnyubMEYChLYohD+x20ULQCf+AimF/Btn7YL+hBpzh1+RmqmvZcx+RgwgNQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "3.901.0", + "@aws-sdk/types": "3.901.0", + "@aws-sdk/util-endpoints": "3.901.0", + "@smithy/core": "^3.14.0", + "@smithy/protocol-http": "^5.3.0", + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/nested-clients": { + "version": "3.901.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/nested-clients/-/nested-clients-3.901.0.tgz", + "integrity": "sha512-feAAAMsVwctk2Tms40ONybvpfJPLCmSdI+G+OTrNpizkGLNl6ik2Ng2RzxY6UqOfN8abqKP/DOUj1qYDRDG8ag==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/sha256-browser": "5.2.0", + "@aws-crypto/sha256-js": "5.2.0", + "@aws-sdk/core": "3.901.0", + "@aws-sdk/middleware-host-header": "3.901.0", + "@aws-sdk/middleware-logger": "3.901.0", + "@aws-sdk/middleware-recursion-detection": "3.901.0", + "@aws-sdk/middleware-user-agent": "3.901.0", + "@aws-sdk/region-config-resolver": "3.901.0", + "@aws-sdk/types": "3.901.0", + "@aws-sdk/util-endpoints": "3.901.0", + "@aws-sdk/util-user-agent-browser": "3.901.0", + "@aws-sdk/util-user-agent-node": "3.901.0", + "@smithy/config-resolver": "^4.3.0", + "@smithy/core": "^3.14.0", + "@smithy/fetch-http-handler": "^5.3.0", + "@smithy/hash-node": "^4.2.0", + "@smithy/invalid-dependency": "^4.2.0", + "@smithy/middleware-content-length": "^4.2.0", + "@smithy/middleware-endpoint": "^4.3.0", + "@smithy/middleware-retry": "^4.4.0", + "@smithy/middleware-serde": "^4.2.0", + "@smithy/middleware-stack": "^4.2.0", + "@smithy/node-config-provider": "^4.3.0", + "@smithy/node-http-handler": "^4.3.0", + "@smithy/protocol-http": "^5.3.0", + "@smithy/smithy-client": "^4.7.0", + "@smithy/types": "^4.6.0", + "@smithy/url-parser": "^4.2.0", + "@smithy/util-base64": "^4.2.0", + "@smithy/util-body-length-browser": "^4.2.0", + "@smithy/util-body-length-node": "^4.2.0", + "@smithy/util-defaults-mode-browser": "^4.2.0", + "@smithy/util-defaults-mode-node": "^4.2.0", + "@smithy/util-endpoints": "^3.2.0", + "@smithy/util-middleware": "^4.2.0", + "@smithy/util-retry": "^4.2.0", + "@smithy/util-utf8": "^4.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/region-config-resolver": { + "version": "3.901.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/region-config-resolver/-/region-config-resolver-3.901.0.tgz", + "integrity": "sha512-7F0N888qVLHo4CSQOsnkZ4QAp8uHLKJ4v3u09Ly5k4AEStrSlFpckTPyUx6elwGL+fxGjNE2aakK8vEgzzCV0A==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.901.0", + "@smithy/node-config-provider": "^4.3.0", + "@smithy/types": "^4.6.0", + "@smithy/util-config-provider": "^4.2.0", + "@smithy/util-middleware": "^4.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/token-providers": { + "version": "3.901.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/token-providers/-/token-providers-3.901.0.tgz", + "integrity": "sha512-pJEr1Ggbc/uVTDqp9IbNu9hdr0eQf3yZix3s4Nnyvmg4xmJSGAlbPC9LrNr5u3CDZoc8Z9CuLrvbP4MwYquNpQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "3.901.0", + "@aws-sdk/nested-clients": "3.901.0", + "@aws-sdk/types": "3.901.0", + "@smithy/property-provider": "^4.2.0", + "@smithy/shared-ini-file-loader": "^4.3.0", + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/types": { + "version": "3.901.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.901.0.tgz", + "integrity": "sha512-FfEM25hLEs4LoXsLXQ/q6X6L4JmKkKkbVFpKD4mwfVHtRVQG6QxJiCPcrkcPISquiy6esbwK2eh64TWbiD60cg==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/util-endpoints": { + "version": "3.901.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-endpoints/-/util-endpoints-3.901.0.tgz", + "integrity": "sha512-5nZP3hGA8FHEtKvEQf4Aww5QZOkjLW1Z+NixSd+0XKfHvA39Ah5sZboScjLx0C9kti/K3OGW1RCx5K9Zc3bZqg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.901.0", + "@smithy/types": "^4.6.0", + "@smithy/url-parser": "^4.2.0", + "@smithy/util-endpoints": "^3.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/util-user-agent-browser": { + "version": "3.901.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-user-agent-browser/-/util-user-agent-browser-3.901.0.tgz", + "integrity": "sha512-Ntb6V/WFI21Ed4PDgL/8NSfoZQQf9xzrwNgiwvnxgAl/KvAvRBgQtqj5gHsDX8Nj2YmJuVoHfH9BGjL9VQ4WNg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.901.0", + "@smithy/types": "^4.6.0", + "bowser": "^2.11.0", + "tslib": "^2.6.2" + } + }, + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/util-user-agent-node": { + "version": "3.901.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-user-agent-node/-/util-user-agent-node-3.901.0.tgz", + "integrity": "sha512-l59KQP5TY7vPVUfEURc7P5BJKuNg1RSsAKBQW7LHLECXjLqDUbo2SMLrexLBEoArSt6E8QOrIN0C8z/0Xk0jYw==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/middleware-user-agent": "3.901.0", + "@aws-sdk/types": "3.901.0", + "@smithy/node-config-provider": "^4.3.0", + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + }, + "peerDependencies": { + "aws-crt": ">=1.0.0" + }, + "peerDependenciesMeta": { + "aws-crt": { + "optional": true + } + } + }, + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/xml-builder": { + "version": "3.901.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/xml-builder/-/xml-builder-3.901.0.tgz", + "integrity": "sha512-pxFCkuAP7Q94wMTNPAwi6hEtNrp/BdFf+HOrIEeFQsk4EoOmpKY3I6S+u6A9Wg295J80Kh74LqDWM22ux3z6Aw==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.6.0", + "fast-xml-parser": "5.2.5", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/client-s3": { + "version": "3.896.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-s3/-/client-s3-3.896.0.tgz", + "integrity": "sha512-UETVuMLQRqgrWxTnavotY0TlB/jaR9sL3hkIFPx4KtjmigNBdwRaiVfOuTnIXKd+w9RPINYG//nnrK+5gIyZkA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/sha1-browser": "5.2.0", + "@aws-crypto/sha256-browser": "5.2.0", + "@aws-crypto/sha256-js": "5.2.0", + "@aws-sdk/core": "3.896.0", + "@aws-sdk/credential-provider-node": "3.896.0", + "@aws-sdk/middleware-bucket-endpoint": "3.893.0", + "@aws-sdk/middleware-expect-continue": "3.893.0", + "@aws-sdk/middleware-flexible-checksums": "3.896.0", + "@aws-sdk/middleware-host-header": "3.893.0", + "@aws-sdk/middleware-location-constraint": "3.893.0", + "@aws-sdk/middleware-logger": "3.893.0", + "@aws-sdk/middleware-recursion-detection": "3.893.0", + "@aws-sdk/middleware-sdk-s3": "3.896.0", + "@aws-sdk/middleware-ssec": "3.893.0", + "@aws-sdk/middleware-user-agent": "3.896.0", + "@aws-sdk/region-config-resolver": "3.893.0", + "@aws-sdk/signature-v4-multi-region": "3.896.0", + "@aws-sdk/types": "3.893.0", + "@aws-sdk/util-endpoints": "3.895.0", + "@aws-sdk/util-user-agent-browser": "3.893.0", + "@aws-sdk/util-user-agent-node": "3.896.0", + "@aws-sdk/xml-builder": "3.894.0", + "@smithy/config-resolver": "^4.2.2", + "@smithy/core": "^3.12.0", + "@smithy/eventstream-serde-browser": "^4.1.1", + "@smithy/eventstream-serde-config-resolver": "^4.2.1", + "@smithy/eventstream-serde-node": "^4.1.1", + "@smithy/fetch-http-handler": "^5.2.1", + "@smithy/hash-blob-browser": "^4.1.1", + "@smithy/hash-node": "^4.1.1", + "@smithy/hash-stream-node": "^4.1.1", + "@smithy/invalid-dependency": "^4.1.1", + "@smithy/md5-js": "^4.1.1", + "@smithy/middleware-content-length": "^4.1.1", + "@smithy/middleware-endpoint": "^4.2.4", + "@smithy/middleware-retry": "^4.3.0", + "@smithy/middleware-serde": "^4.1.1", + "@smithy/middleware-stack": "^4.1.1", + "@smithy/node-config-provider": "^4.2.2", + "@smithy/node-http-handler": "^4.2.1", + "@smithy/protocol-http": "^5.2.1", + "@smithy/smithy-client": "^4.6.4", + "@smithy/types": "^4.5.0", + "@smithy/url-parser": "^4.1.1", + "@smithy/util-base64": "^4.1.0", + "@smithy/util-body-length-browser": "^4.1.0", + "@smithy/util-body-length-node": "^4.1.0", + "@smithy/util-defaults-mode-browser": "^4.1.4", + "@smithy/util-defaults-mode-node": "^4.1.4", + "@smithy/util-endpoints": "^3.1.2", + "@smithy/util-middleware": "^4.1.1", + "@smithy/util-retry": "^4.1.2", + "@smithy/util-stream": "^4.3.2", + "@smithy/util-utf8": "^4.1.0", + "@smithy/util-waiter": "^4.1.1", + "@smithy/uuid": "^1.0.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/client-sso": { + "version": "3.896.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-sso/-/client-sso-3.896.0.tgz", + "integrity": "sha512-mpE3mrNili1dcvEvxaYjyoib8HlRXkb2bY5a3WeK++KObFY+HUujKtgQmiNSRX5YwQszm//fTrmGMmv9zpMcKg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/sha256-browser": "5.2.0", + "@aws-crypto/sha256-js": "5.2.0", + "@aws-sdk/core": "3.896.0", + "@aws-sdk/middleware-host-header": "3.893.0", + "@aws-sdk/middleware-logger": "3.893.0", + "@aws-sdk/middleware-recursion-detection": "3.893.0", + "@aws-sdk/middleware-user-agent": "3.896.0", + "@aws-sdk/region-config-resolver": "3.893.0", + "@aws-sdk/types": "3.893.0", + "@aws-sdk/util-endpoints": "3.895.0", + "@aws-sdk/util-user-agent-browser": "3.893.0", + "@aws-sdk/util-user-agent-node": "3.896.0", + "@smithy/config-resolver": "^4.2.2", + "@smithy/core": "^3.12.0", + "@smithy/fetch-http-handler": "^5.2.1", + "@smithy/hash-node": "^4.1.1", + "@smithy/invalid-dependency": "^4.1.1", + "@smithy/middleware-content-length": "^4.1.1", + "@smithy/middleware-endpoint": "^4.2.4", + "@smithy/middleware-retry": "^4.3.0", + "@smithy/middleware-serde": "^4.1.1", + "@smithy/middleware-stack": "^4.1.1", + "@smithy/node-config-provider": "^4.2.2", + "@smithy/node-http-handler": "^4.2.1", + "@smithy/protocol-http": "^5.2.1", + "@smithy/smithy-client": "^4.6.4", + "@smithy/types": "^4.5.0", + "@smithy/url-parser": "^4.1.1", + "@smithy/util-base64": "^4.1.0", + "@smithy/util-body-length-browser": "^4.1.0", + "@smithy/util-body-length-node": "^4.1.0", + "@smithy/util-defaults-mode-browser": "^4.1.4", + "@smithy/util-defaults-mode-node": "^4.1.4", + "@smithy/util-endpoints": "^3.1.2", + "@smithy/util-middleware": "^4.1.1", + "@smithy/util-retry": "^4.1.2", + "@smithy/util-utf8": "^4.1.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/core": { + "version": "3.896.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/core/-/core-3.896.0.tgz", + "integrity": "sha512-uJaoyWKeGNyCyeI+cIJrD7LEB4iF/W8/x2ij7zg32OFpAAJx96N34/e+XSKp/xkJpO5FKiBOskKLnHeUsJsAPA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.893.0", + "@aws-sdk/xml-builder": "3.894.0", + "@smithy/core": "^3.12.0", + "@smithy/node-config-provider": "^4.2.2", + "@smithy/property-provider": "^4.1.1", + "@smithy/protocol-http": "^5.2.1", + "@smithy/signature-v4": "^5.2.1", + "@smithy/smithy-client": "^4.6.4", + "@smithy/types": "^4.5.0", + "@smithy/util-base64": "^4.1.0", + "@smithy/util-middleware": "^4.1.1", + "@smithy/util-utf8": "^4.1.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-cognito-identity": { + "version": "3.901.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-cognito-identity/-/credential-provider-cognito-identity-3.901.0.tgz", + "integrity": "sha512-irVFwiiEC+JRFQTZwI7264LOGXRjqdp3AvmqiEmmZS0+sJsEaF65prCs+nzw6J1WqQ6IZKClKKQsH7x8FfOPrQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/client-cognito-identity": "3.901.0", + "@aws-sdk/types": "3.901.0", + "@smithy/property-provider": "^4.2.0", + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-cognito-identity/node_modules/@aws-sdk/types": { + "version": "3.901.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.901.0.tgz", + "integrity": "sha512-FfEM25hLEs4LoXsLXQ/q6X6L4JmKkKkbVFpKD4mwfVHtRVQG6QxJiCPcrkcPISquiy6esbwK2eh64TWbiD60cg==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-env": { + "version": "3.896.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-env/-/credential-provider-env-3.896.0.tgz", + "integrity": "sha512-Cnqhupdkp825ICySrz4QTI64Nq3AmUAscPW8dueanni0avYBDp7RBppX4H0+6icqN569B983XNfQ0YSImQhfhg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "3.896.0", + "@aws-sdk/types": "3.893.0", + "@smithy/property-provider": "^4.1.1", + "@smithy/types": "^4.5.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-http": { + "version": "3.896.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-http/-/credential-provider-http-3.896.0.tgz", + "integrity": "sha512-CN0fTCKCUA1OTSx1c76o8XyJCy2WoI/av3J8r8mL6GmxTerhLRyzDy/MwxzPjTYPoL+GLEg6V4a9fRkWj1hBUA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "3.896.0", + "@aws-sdk/types": "3.893.0", + "@smithy/fetch-http-handler": "^5.2.1", + "@smithy/node-http-handler": "^4.2.1", + "@smithy/property-provider": "^4.1.1", + "@smithy/protocol-http": "^5.2.1", + "@smithy/smithy-client": "^4.6.4", + "@smithy/types": "^4.5.0", + "@smithy/util-stream": "^4.3.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-ini": { + "version": "3.896.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-ini/-/credential-provider-ini-3.896.0.tgz", + "integrity": "sha512-+rbYG98czzwZLTYHJasK+VBjnIeXk73mRpZXHvaa4kDNxBezdN2YsoGNpLlPSxPdbpq18LY3LRtkdFTaT6DIQA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "3.896.0", + "@aws-sdk/credential-provider-env": "3.896.0", + "@aws-sdk/credential-provider-http": "3.896.0", + "@aws-sdk/credential-provider-process": "3.896.0", + "@aws-sdk/credential-provider-sso": "3.896.0", + "@aws-sdk/credential-provider-web-identity": "3.896.0", + "@aws-sdk/nested-clients": "3.896.0", + "@aws-sdk/types": "3.893.0", + "@smithy/credential-provider-imds": "^4.1.2", + "@smithy/property-provider": "^4.1.1", + "@smithy/shared-ini-file-loader": "^4.2.0", + "@smithy/types": "^4.5.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-node": { + "version": "3.896.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-node/-/credential-provider-node-3.896.0.tgz", + "integrity": "sha512-J0Jm+56MNngk1PIyqoJFf5FC2fjA4CYXlqODqNRDtid7yk7HB9W3UTtvxofmii5KJOLcHGNPdGnHWKkUc+xYgw==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/credential-provider-env": "3.896.0", + "@aws-sdk/credential-provider-http": "3.896.0", + "@aws-sdk/credential-provider-ini": "3.896.0", + "@aws-sdk/credential-provider-process": "3.896.0", + "@aws-sdk/credential-provider-sso": "3.896.0", + "@aws-sdk/credential-provider-web-identity": "3.896.0", + "@aws-sdk/types": "3.893.0", + "@smithy/credential-provider-imds": "^4.1.2", + "@smithy/property-provider": "^4.1.1", + "@smithy/shared-ini-file-loader": "^4.2.0", + "@smithy/types": "^4.5.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-process": { + "version": "3.896.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-process/-/credential-provider-process-3.896.0.tgz", + "integrity": "sha512-UfWVMQPZy7dus40c4LWxh5vQ+I51z0q4vf09Eqas5848e9DrGRG46GYIuc/gy+4CqEypjbg/XNMjnZfGLHxVnQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "3.896.0", + "@aws-sdk/types": "3.893.0", + "@smithy/property-provider": "^4.1.1", + "@smithy/shared-ini-file-loader": "^4.2.0", + "@smithy/types": "^4.5.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-sso": { + "version": "3.896.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-sso/-/credential-provider-sso-3.896.0.tgz", + "integrity": "sha512-77Te8WrVdLABKlv7QyetXP6aYEX1UORiahLA1PXQb/p66aFBw18Xc6JiN/6zJ4RqdyV1Xr9rwYBwGYua93ANIA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/client-sso": "3.896.0", + "@aws-sdk/core": "3.896.0", + "@aws-sdk/token-providers": "3.896.0", + "@aws-sdk/types": "3.893.0", + "@smithy/property-provider": "^4.1.1", + "@smithy/shared-ini-file-loader": "^4.2.0", + "@smithy/types": "^4.5.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-web-identity": { + "version": "3.896.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-web-identity/-/credential-provider-web-identity-3.896.0.tgz", + "integrity": "sha512-gwMwZWumo+V0xJplO8j2HIb1TfPsF9fbcRGXS0CanEvjg4fF2Xs1pOQl2oCw3biPZpxHB0plNZjqSF2eneGg9g==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "3.896.0", + "@aws-sdk/nested-clients": "3.896.0", + "@aws-sdk/types": "3.893.0", + "@smithy/property-provider": "^4.1.1", + "@smithy/shared-ini-file-loader": "^4.2.0", + "@smithy/types": "^4.5.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/eventstream-codec": { + "version": "3.370.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/eventstream-codec/-/eventstream-codec-3.370.0.tgz", + "integrity": "sha512-PiaDMum7TNsIE3DGECSsNYwibBIPN2/e13BJbTwi6KgVx8BV2mYA3kQkaUDiy++tEpzN81Nh5OPTFVb7bvgYYg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/crc32": "3.0.0", + "@aws-sdk/types": "3.370.0", + "@aws-sdk/util-hex-encoding": "3.310.0", + "tslib": "^2.5.0" + } + }, + "node_modules/@aws-sdk/eventstream-codec/node_modules/@aws-crypto/crc32": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@aws-crypto/crc32/-/crc32-3.0.0.tgz", + "integrity": "sha512-IzSgsrxUcsrejQbPVilIKy16kAT52EwB6zSaI+M3xxIhKh5+aldEyvI+z6erM7TCLB2BJsFrtHjp6/4/sr+3dA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/util": "^3.0.0", + "@aws-sdk/types": "^3.222.0", + "tslib": "^1.11.1" + } + }, + "node_modules/@aws-sdk/eventstream-codec/node_modules/@aws-crypto/crc32/node_modules/tslib": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", + "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==", + "license": "0BSD" + }, + "node_modules/@aws-sdk/eventstream-codec/node_modules/@aws-crypto/util": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@aws-crypto/util/-/util-3.0.0.tgz", + "integrity": "sha512-2OJlpeJpCR48CC8r+uKVChzs9Iungj9wkZrl8Z041DWEWvyIHILYKCPNzJghKsivj+S3mLo6BVc7mBNzdxA46w==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "^3.222.0", + "@aws-sdk/util-utf8-browser": "^3.0.0", + "tslib": "^1.11.1" + } + }, + "node_modules/@aws-sdk/eventstream-codec/node_modules/@aws-crypto/util/node_modules/tslib": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", + "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==", + "license": "0BSD" + }, + "node_modules/@aws-sdk/eventstream-codec/node_modules/@aws-sdk/types": { + "version": "3.370.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.370.0.tgz", + "integrity": "sha512-8PGMKklSkRKjunFhzM2y5Jm0H2TBu7YRNISdYzXLUHKSP9zlMEYagseKVdmox0zKHf1LXVNuSlUV2b6SRrieCQ==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^1.1.0", + "tslib": "^2.5.0" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-sdk/eventstream-codec/node_modules/@smithy/types": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@smithy/types/-/types-1.2.0.tgz", + "integrity": "sha512-z1r00TvBqF3dh4aHhya7nz1HhvCg4TRmw51fjMrh5do3h+ngSstt/yKlNbHeb9QxJmFbmN8KEVSWgb1bRvfEoA==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.5.0" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-sdk/is-array-buffer": { + "version": "3.310.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/is-array-buffer/-/is-array-buffer-3.310.0.tgz", + "integrity": "sha512-urnbcCR+h9NWUnmOtet/s4ghvzsidFmspfhYaHAmSRdy9yDjdjBJMFjjsn85A1ODUktztm+cVncXjQ38WCMjMQ==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.5.0" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-sdk/middleware-bucket-endpoint": { + "version": "3.893.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-bucket-endpoint/-/middleware-bucket-endpoint-3.893.0.tgz", + "integrity": "sha512-H+wMAoFC73T7M54OFIezdHXR9/lH8TZ3Cx1C3MEBb2ctlzQrVCd8LX8zmOtcGYC8plrRwV+8rNPe0FMqecLRew==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.893.0", + "@aws-sdk/util-arn-parser": "3.893.0", + "@smithy/node-config-provider": "^4.2.2", + "@smithy/protocol-http": "^5.2.1", + "@smithy/types": "^4.5.0", + "@smithy/util-config-provider": "^4.1.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/middleware-expect-continue": { + "version": "3.893.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-expect-continue/-/middleware-expect-continue-3.893.0.tgz", + "integrity": "sha512-PEZkvD6k0X9sacHkvkVF4t2QyQEAzd35OJ2bIrjWCfc862TwukMMJ1KErRmQ1WqKXHKF4L0ed5vtWaO/8jVLNA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.893.0", + "@smithy/protocol-http": "^5.2.1", + "@smithy/types": "^4.5.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/middleware-flexible-checksums": { + "version": "3.896.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-flexible-checksums/-/middleware-flexible-checksums-3.896.0.tgz", + "integrity": "sha512-bB3W/IFG7HNNziACOp1aZVGGnrIahXc0PxZoU055JirEGQtDFIU1ZD7S9zLKmy9FFUvQsAeRL9nDFHbx8cwx/w==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/crc32": "5.2.0", + "@aws-crypto/crc32c": "5.2.0", + "@aws-crypto/util": "5.2.0", + "@aws-sdk/core": "3.896.0", + "@aws-sdk/types": "3.893.0", + "@smithy/is-array-buffer": "^4.1.0", + "@smithy/node-config-provider": "^4.2.2", + "@smithy/protocol-http": "^5.2.1", + "@smithy/types": "^4.5.0", + "@smithy/util-middleware": "^4.1.1", + "@smithy/util-stream": "^4.3.2", + "@smithy/util-utf8": "^4.1.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/middleware-host-header": { + "version": "3.893.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-host-header/-/middleware-host-header-3.893.0.tgz", + "integrity": "sha512-qL5xYRt80ahDfj9nDYLhpCNkDinEXvjLe/Qen/Y/u12+djrR2MB4DRa6mzBCkLkdXDtf0WAoW2EZsNCfGrmOEQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.893.0", + "@smithy/protocol-http": "^5.2.1", + "@smithy/types": "^4.5.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/middleware-location-constraint": { + "version": "3.893.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-location-constraint/-/middleware-location-constraint-3.893.0.tgz", + "integrity": "sha512-MlbBc7Ttb1ekbeeeFBU4DeEZOLb5s0Vl4IokvO17g6yJdLk4dnvZro9zdXl3e7NXK+kFxHRBFZe55p/42mVgDA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.893.0", + "@smithy/types": "^4.5.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/middleware-logger": { + "version": "3.893.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-logger/-/middleware-logger-3.893.0.tgz", + "integrity": "sha512-ZqzMecjju5zkBquSIfVfCORI/3Mge21nUY4nWaGQy+NUXehqCGG4W7AiVpiHGOcY2cGJa7xeEkYcr2E2U9U0AA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.893.0", + "@smithy/types": "^4.5.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/middleware-recursion-detection": { + "version": "3.893.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-recursion-detection/-/middleware-recursion-detection-3.893.0.tgz", + "integrity": "sha512-H7Zotd9zUHQAr/wr3bcWHULYhEeoQrF54artgsoUGIf/9emv6LzY89QUccKIxYd6oHKNTrTyXm9F0ZZrzXNxlg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.893.0", + "@aws/lambda-invoke-store": "^0.0.1", + "@smithy/protocol-http": "^5.2.1", + "@smithy/types": "^4.5.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/middleware-sdk-s3": { + "version": "3.896.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-sdk-s3/-/middleware-sdk-s3-3.896.0.tgz", + "integrity": "sha512-hlPu/AZ5Afa4ZafP+aXIjRtKm7BX57lurA+TJ+7nXm1Az8Du3Sg2tZXP2/GfqTztLIFQYj/Jy5smkJ0+1HNAPQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "3.896.0", + "@aws-sdk/types": "3.893.0", + "@aws-sdk/util-arn-parser": "3.893.0", + "@smithy/core": "^3.12.0", + "@smithy/node-config-provider": "^4.2.2", + "@smithy/protocol-http": "^5.2.1", + "@smithy/signature-v4": "^5.2.1", + "@smithy/smithy-client": "^4.6.4", + "@smithy/types": "^4.5.0", + "@smithy/util-config-provider": "^4.1.0", + "@smithy/util-middleware": "^4.1.1", + "@smithy/util-stream": "^4.3.2", + "@smithy/util-utf8": "^4.1.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/middleware-ssec": { + "version": "3.893.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-ssec/-/middleware-ssec-3.893.0.tgz", + "integrity": "sha512-e4ccCiAnczv9mMPheKjgKxZQN473mcup+3DPLVNnIw5GRbQoDqPSB70nUzfORKZvM7ar7xLMPxNR8qQgo1C8Rg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.893.0", + "@smithy/types": "^4.5.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/middleware-user-agent": { + "version": "3.896.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-user-agent/-/middleware-user-agent-3.896.0.tgz", + "integrity": "sha512-so/3tZH34YIeqG/QJgn5ZinnmHRdXV1ehsj4wVUrezL/dVW86jfwIkQIwpw8roOC657UoUf91c9FDhCxs3J5aQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "3.896.0", + "@aws-sdk/types": "3.893.0", + "@aws-sdk/util-endpoints": "3.895.0", + "@smithy/core": "^3.12.0", + "@smithy/protocol-http": "^5.2.1", + "@smithy/types": "^4.5.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/nested-clients": { + "version": "3.896.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/nested-clients/-/nested-clients-3.896.0.tgz", + "integrity": "sha512-KaHALB6DIXScJL/ExmonADr3jtTV6dpOHoEeTRSskJ/aW+rhZo7kH8SLmrwOT/qX8d5tza17YyR/oRkIKY6Eaw==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/sha256-browser": "5.2.0", + "@aws-crypto/sha256-js": "5.2.0", + "@aws-sdk/core": "3.896.0", + "@aws-sdk/middleware-host-header": "3.893.0", + "@aws-sdk/middleware-logger": "3.893.0", + "@aws-sdk/middleware-recursion-detection": "3.893.0", + "@aws-sdk/middleware-user-agent": "3.896.0", + "@aws-sdk/region-config-resolver": "3.893.0", + "@aws-sdk/types": "3.893.0", + "@aws-sdk/util-endpoints": "3.895.0", + "@aws-sdk/util-user-agent-browser": "3.893.0", + "@aws-sdk/util-user-agent-node": "3.896.0", + "@smithy/config-resolver": "^4.2.2", + "@smithy/core": "^3.12.0", + "@smithy/fetch-http-handler": "^5.2.1", + "@smithy/hash-node": "^4.1.1", + "@smithy/invalid-dependency": "^4.1.1", + "@smithy/middleware-content-length": "^4.1.1", + "@smithy/middleware-endpoint": "^4.2.4", + "@smithy/middleware-retry": "^4.3.0", + "@smithy/middleware-serde": "^4.1.1", + "@smithy/middleware-stack": "^4.1.1", + "@smithy/node-config-provider": "^4.2.2", + "@smithy/node-http-handler": "^4.2.1", + "@smithy/protocol-http": "^5.2.1", + "@smithy/smithy-client": "^4.6.4", + "@smithy/types": "^4.5.0", + "@smithy/url-parser": "^4.1.1", + "@smithy/util-base64": "^4.1.0", + "@smithy/util-body-length-browser": "^4.1.0", + "@smithy/util-body-length-node": "^4.1.0", + "@smithy/util-defaults-mode-browser": "^4.1.4", + "@smithy/util-defaults-mode-node": "^4.1.4", + "@smithy/util-endpoints": "^3.1.2", + "@smithy/util-middleware": "^4.1.1", + "@smithy/util-retry": "^4.1.2", + "@smithy/util-utf8": "^4.1.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/protocol-http": { + "version": "3.370.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/protocol-http/-/protocol-http-3.370.0.tgz", + "integrity": "sha512-MfZCgSsVmir+4kJps7xT0awOPNi+swBpcVp9ZtAP7POduUVV6zVLurMNLXsppKsErggssD5E9HUgQFs5w06U4Q==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.370.0", + "tslib": "^2.5.0" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-sdk/protocol-http/node_modules/@aws-sdk/types": { + "version": "3.370.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.370.0.tgz", + "integrity": "sha512-8PGMKklSkRKjunFhzM2y5Jm0H2TBu7YRNISdYzXLUHKSP9zlMEYagseKVdmox0zKHf1LXVNuSlUV2b6SRrieCQ==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^1.1.0", + "tslib": "^2.5.0" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@smithy/types/-/types-1.2.0.tgz", + "integrity": "sha512-z1r00TvBqF3dh4aHhya7nz1HhvCg4TRmw51fjMrh5do3h+ngSstt/yKlNbHeb9QxJmFbmN8KEVSWgb1bRvfEoA==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.5.0" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-sdk/region-config-resolver": { + "version": "3.893.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/region-config-resolver/-/region-config-resolver-3.893.0.tgz", + "integrity": "sha512-/cJvh3Zsa+Of0Zbg7vl9wp/kZtdb40yk/2+XcroAMVPO9hPvmS9r/UOm6tO7FeX4TtkRFwWaQJiTZTgSdsPY+Q==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.893.0", + "@smithy/node-config-provider": "^4.2.2", + "@smithy/types": "^4.5.0", + "@smithy/util-config-provider": "^4.1.0", + "@smithy/util-middleware": "^4.1.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/signature-v4": { + "version": "3.370.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/signature-v4/-/signature-v4-3.370.0.tgz", + "integrity": "sha512-Mh++NJiXoBxMzz4d8GQPNB37nqjS1gsVwjKoSAWFE67sjgsjb8D5JWRCm9CinqPoXi2iN57+1DcQalTDKQGc0A==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/eventstream-codec": "3.370.0", + "@aws-sdk/is-array-buffer": "3.310.0", + "@aws-sdk/types": "3.370.0", + "@aws-sdk/util-hex-encoding": "3.310.0", + "@aws-sdk/util-middleware": "3.370.0", + "@aws-sdk/util-uri-escape": "3.310.0", + "@aws-sdk/util-utf8": "3.310.0", + "tslib": "^2.5.0" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-sdk/signature-v4-multi-region": { + "version": "3.896.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/signature-v4-multi-region/-/signature-v4-multi-region-3.896.0.tgz", + "integrity": "sha512-txiQDEZXL9tlNP8mbnNaDtuHBYc/FCqaZ8Y76qnfM3o6CTIn0t0tTAlnx1CyFe4EaikVBgQuZvj5KfNA8PmlzA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/middleware-sdk-s3": "3.896.0", + "@aws-sdk/types": "3.893.0", + "@smithy/protocol-http": "^5.2.1", + "@smithy/signature-v4": "^5.2.1", + "@smithy/types": "^4.5.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/signature-v4/node_modules/@aws-sdk/types": { + "version": "3.370.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.370.0.tgz", + "integrity": "sha512-8PGMKklSkRKjunFhzM2y5Jm0H2TBu7YRNISdYzXLUHKSP9zlMEYagseKVdmox0zKHf1LXVNuSlUV2b6SRrieCQ==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^1.1.0", + "tslib": "^2.5.0" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-sdk/signature-v4/node_modules/@smithy/types": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@smithy/types/-/types-1.2.0.tgz", + "integrity": "sha512-z1r00TvBqF3dh4aHhya7nz1HhvCg4TRmw51fjMrh5do3h+ngSstt/yKlNbHeb9QxJmFbmN8KEVSWgb1bRvfEoA==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.5.0" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-sdk/token-providers": { + "version": "3.896.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/token-providers/-/token-providers-3.896.0.tgz", + "integrity": "sha512-WBoD+RY7tUfW9M+wGrZ2vdveR+ziZOjGHWFY3lcGnDvI8KE+fcSccEOTxgJBNBS5Z8B+WHKU2sZjb+Z7QqGwjw==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "3.896.0", + "@aws-sdk/nested-clients": "3.896.0", + "@aws-sdk/types": "3.893.0", + "@smithy/property-provider": "^4.1.1", + "@smithy/shared-ini-file-loader": "^4.2.0", + "@smithy/types": "^4.5.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/types": { + "version": "3.893.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.893.0.tgz", + "integrity": "sha512-Aht1nn5SnA0N+Tjv0dzhAY7CQbxVtmq1bBR6xI0MhG7p2XYVh1wXuKTzrldEvQWwA3odOYunAfT9aBiKZx9qIg==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.5.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/util-arn-parser": { + "version": "3.893.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-arn-parser/-/util-arn-parser-3.893.0.tgz", + "integrity": "sha512-u8H4f2Zsi19DGnwj5FSZzDMhytYF/bCh37vAtBsn3cNDL3YG578X5oc+wSX54pM3tOxS+NY7tvOAo52SW7koUA==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/util-buffer-from": { + "version": "3.310.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-buffer-from/-/util-buffer-from-3.310.0.tgz", + "integrity": "sha512-i6LVeXFtGih5Zs8enLrt+ExXY92QV25jtEnTKHsmlFqFAuL3VBeod6boeMXkN2p9lbSVVQ1sAOOYZOHYbYkntw==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/is-array-buffer": "3.310.0", + "tslib": "^2.5.0" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-sdk/util-endpoints": { + "version": "3.895.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-endpoints/-/util-endpoints-3.895.0.tgz", + "integrity": "sha512-MhxBvWbwxmKknuggO2NeMwOVkHOYL98pZ+1ZRI5YwckoCL3AvISMnPJgfN60ww6AIXHGpkp+HhpFdKOe8RHSEg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.893.0", + "@smithy/types": "^4.5.0", + "@smithy/url-parser": "^4.1.1", + "@smithy/util-endpoints": "^3.1.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/util-hex-encoding": { + "version": "3.310.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-hex-encoding/-/util-hex-encoding-3.310.0.tgz", + "integrity": "sha512-sVN7mcCCDSJ67pI1ZMtk84SKGqyix6/0A1Ab163YKn+lFBQRMKexleZzpYzNGxYzmQS6VanP/cfU7NiLQOaSfA==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.5.0" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-sdk/util-locate-window": { + "version": "3.893.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-locate-window/-/util-locate-window-3.893.0.tgz", + "integrity": "sha512-T89pFfgat6c8nMmpI8eKjBcDcgJq36+m9oiXbcUzeU55MP9ZuGgBomGjGnHaEyF36jenW9gmg3NfZDm0AO2XPg==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/util-middleware": { + "version": "3.370.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-middleware/-/util-middleware-3.370.0.tgz", + "integrity": "sha512-Jvs9FZHaQznWGLkRel3PFEP93I1n0Kp6356zxYHk3LIOmjpzoob3R+v96mzyN+dZrnhPdPubYS41qbU2F9lROg==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.5.0" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-sdk/util-uri-escape": { + "version": "3.310.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-uri-escape/-/util-uri-escape-3.310.0.tgz", + "integrity": "sha512-drzt+aB2qo2LgtDoiy/3sVG8w63cgLkqFIa2NFlGpUgHFWTXkqtbgf4L5QdjRGKWhmZsnqkbtL7vkSWEcYDJ4Q==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.5.0" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-sdk/util-user-agent-browser": { + "version": "3.893.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-user-agent-browser/-/util-user-agent-browser-3.893.0.tgz", + "integrity": "sha512-PE9NtbDBW6Kgl1bG6A5fF3EPo168tnkj8TgMcT0sg4xYBWsBpq0bpJZRh+Jm5Bkwiw9IgTCLjEU7mR6xWaMB9w==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.893.0", + "@smithy/types": "^4.5.0", + "bowser": "^2.11.0", + "tslib": "^2.6.2" + } + }, + "node_modules/@aws-sdk/util-user-agent-node": { + "version": "3.896.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-user-agent-node/-/util-user-agent-node-3.896.0.tgz", + "integrity": "sha512-jegizucAwoxyBddKl0kRGNEgRHcfGuMeyhP1Nf+wIUmHz/9CxobIajqcVk/KRNLdZY5mSn7YG2VtP3z0BcBb0w==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/middleware-user-agent": "3.896.0", + "@aws-sdk/types": "3.893.0", + "@smithy/node-config-provider": "^4.2.2", + "@smithy/types": "^4.5.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + }, + "peerDependencies": { + "aws-crt": ">=1.0.0" + }, + "peerDependenciesMeta": { + "aws-crt": { + "optional": true + } + } + }, + "node_modules/@aws-sdk/util-utf8": { + "version": "3.310.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-utf8/-/util-utf8-3.310.0.tgz", + "integrity": "sha512-DnLfFT8uCO22uOJc0pt0DsSNau1GTisngBCDw8jQuWT5CqogMJu4b/uXmwEqfj8B3GX6Xsz8zOd6JpRlPftQoA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/util-buffer-from": "3.310.0", + "tslib": "^2.5.0" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-sdk/util-utf8-browser": { + "version": "3.259.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-utf8-browser/-/util-utf8-browser-3.259.0.tgz", + "integrity": "sha512-UvFa/vR+e19XookZF8RzFZBrw2EUkQWxiBW0yYQAhvk3C+QVGl0H3ouca8LDBlBfQKXwmW3huo/59H8rwb1wJw==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.3.1" + } + }, + "node_modules/@aws-sdk/xml-builder": { + "version": "3.894.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/xml-builder/-/xml-builder-3.894.0.tgz", + "integrity": "sha512-E6EAMc9dT1a2DOdo4zyOf3fp5+NJ2wI+mcm7RaW1baFIWDwcb99PpvWoV7YEiK7oaBDshuOEGWKUSYXdW+JYgA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.5.0", + "fast-xml-parser": "5.2.5", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws/lambda-invoke-store": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/@aws/lambda-invoke-store/-/lambda-invoke-store-0.0.1.tgz", + "integrity": "sha512-ORHRQ2tmvnBXc8t/X9Z8IcSbBA4xTLKuN873FopzklHMeqBst7YG0d+AX97inkvDX+NChYtSr+qGfcqGFaI8Zw==", + "license": "Apache-2.0", + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@cfworker/json-schema": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/@cfworker/json-schema/-/json-schema-4.1.1.tgz", + "integrity": "sha512-gAmrUZSGtKc3AiBL71iNWxDsyUC5uMaKKGdvzYsBoTW/xi42JQHl7eKV2OYzCUqvc+D2RCcf7EXY2iCyFIk6og==", + "license": "MIT" + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.25.9", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.9.tgz", + "integrity": "sha512-OaGtL73Jck6pBKjNIe24BnFE6agGl+6KxDtTfHhy1HmhthfKouEcOhqpSL64K4/0WCtbKFLOdzD/44cJ4k9opA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.25.9", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.9.tgz", + "integrity": "sha512-5WNI1DaMtxQ7t7B6xa572XMXpHAaI/9Hnhk8lcxF4zVN4xstUgTlvuGDorBguKEnZO70qwEcLpfifMLoxiPqHQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.25.9", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.9.tgz", + "integrity": "sha512-IDrddSmpSv51ftWslJMvl3Q2ZT98fUSL2/rlUXuVqRXHCs5EUF1/f+jbjF5+NG9UffUDMCiTyh8iec7u8RlTLg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.25.9", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.9.tgz", + "integrity": "sha512-I853iMZ1hWZdNllhVZKm34f4wErd4lMyeV7BLzEExGEIZYsOzqDWDf+y082izYUE8gtJnYHdeDpN/6tUdwvfiw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.25.9", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.9.tgz", + "integrity": "sha512-XIpIDMAjOELi/9PB30vEbVMs3GV1v2zkkPnuyRRURbhqjyzIINwj+nbQATh4H9GxUgH1kFsEyQMxwiLFKUS6Rg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.25.9", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.9.tgz", + "integrity": "sha512-jhHfBzjYTA1IQu8VyrjCX4ApJDnH+ez+IYVEoJHeqJm9VhG9Dh2BYaJritkYK3vMaXrf7Ogr/0MQ8/MeIefsPQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.25.9", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.9.tgz", + "integrity": "sha512-z93DmbnY6fX9+KdD4Ue/H6sYs+bhFQJNCPZsi4XWJoYblUqT06MQUdBCpcSfuiN72AbqeBFu5LVQTjfXDE2A6Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.25.9", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.9.tgz", + "integrity": "sha512-mrKX6H/vOyo5v71YfXWJxLVxgy1kyt1MQaD8wZJgJfG4gq4DpQGpgTB74e5yBeQdyMTbgxp0YtNj7NuHN0PoZg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.25.9", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.9.tgz", + "integrity": "sha512-HBU2Xv78SMgaydBmdor38lg8YDnFKSARg1Q6AT0/y2ezUAKiZvc211RDFHlEZRFNRVhcMamiToo7bDx3VEOYQw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.25.9", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.9.tgz", + "integrity": "sha512-BlB7bIcLT3G26urh5Dmse7fiLmLXnRlopw4s8DalgZ8ef79Jj4aUcYbk90g8iCa2467HX8SAIidbL7gsqXHdRw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.25.9", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.9.tgz", + "integrity": "sha512-e7S3MOJPZGp2QW6AK6+Ly81rC7oOSerQ+P8L0ta4FhVi+/j/v2yZzx5CqqDaWjtPFfYz21Vi1S0auHrap3Ma3A==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.25.9", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.9.tgz", + "integrity": "sha512-Sbe10Bnn0oUAB2AalYztvGcK+o6YFFA/9829PhOCUS9vkJElXGdphz0A3DbMdP8gmKkqPmPcMJmJOrI3VYB1JQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.25.9", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.9.tgz", + "integrity": "sha512-YcM5br0mVyZw2jcQeLIkhWtKPeVfAerES5PvOzaDxVtIyZ2NUBZKNLjC5z3/fUlDgT6w89VsxP2qzNipOaaDyA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.25.9", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.9.tgz", + "integrity": "sha512-++0HQvasdo20JytyDpFvQtNrEsAgNG2CY1CLMwGXfFTKGBGQT3bOeLSYE2l1fYdvML5KUuwn9Z8L1EWe2tzs1w==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.25.9", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.9.tgz", + "integrity": "sha512-uNIBa279Y3fkjV+2cUjx36xkx7eSjb8IvnL01eXUKXez/CBHNRw5ekCGMPM0BcmqBxBcdgUWuUXmVWwm4CH9kg==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.25.9", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.9.tgz", + "integrity": "sha512-Mfiphvp3MjC/lctb+7D287Xw1DGzqJPb/J2aHHcHxflUo+8tmN/6d4k6I2yFR7BVo5/g7x2Monq4+Yew0EHRIA==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.25.9", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.9.tgz", + "integrity": "sha512-iSwByxzRe48YVkmpbgoxVzn76BXjlYFXC7NvLYq+b+kDjyyk30J0JY47DIn8z1MO3K0oSl9fZoRmZPQI4Hklzg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.25.9", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.9.tgz", + "integrity": "sha512-9jNJl6FqaUG+COdQMjSCGW4QiMHH88xWbvZ+kRVblZsWrkXlABuGdFJ1E9L7HK+T0Yqd4akKNa/lO0+jDxQD4Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.25.9", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.9.tgz", + "integrity": "sha512-RLLdkflmqRG8KanPGOU7Rpg829ZHu8nFy5Pqdi9U01VYtG9Y0zOG6Vr2z4/S+/3zIyOxiK6cCeYNWOFR9QP87g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.25.9", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.9.tgz", + "integrity": "sha512-YaFBlPGeDasft5IIM+CQAhJAqS3St3nJzDEgsgFixcfZeyGPCd6eJBWzke5piZuZ7CtL656eOSYKk4Ls2C0FRQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.25.9", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.9.tgz", + "integrity": "sha512-1MkgTCuvMGWuqVtAvkpkXFmtL8XhWy+j4jaSO2wxfJtilVCi0ZE37b8uOdMItIHz4I6z1bWWtEX4CJwcKYLcuA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.25.9", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.9.tgz", + "integrity": "sha512-4Xd0xNiMVXKh6Fa7HEJQbrpP3m3DDn43jKxMjxLLRjWnRsfxjORYJlXPO4JNcXtOyfajXorRKY9NkOpTHptErg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.25.9", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.9.tgz", + "integrity": "sha512-WjH4s6hzo00nNezhp3wFIAfmGZ8U7KtrJNlFMRKxiI9mxEK1scOMAaa9i4crUtu+tBr+0IN6JCuAcSBJZfnphw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.25.9", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.9.tgz", + "integrity": "sha512-mGFrVJHmZiRqmP8xFOc6b84/7xa5y5YvR1x8djzXpJBSv/UsNK6aqec+6JDjConTgvvQefdGhFDAs2DLAds6gQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.25.9", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.9.tgz", + "integrity": "sha512-b33gLVU2k11nVx1OhX3C8QQP6UHQK4ZtN56oFWvVXvz2VkDoe6fbG8TOgHFxEvqeqohmRnIHe5A1+HADk4OQww==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.25.9", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.9.tgz", + "integrity": "sha512-PPOl1mi6lpLNQxnGoyAfschAodRFYXJ+9fs6WHXz7CSWKbOqiMZsubC+BQsVKuul+3vKLuwTHsS2c2y9EoKwxQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@langchain/core": { + "version": "0.3.72", + "resolved": "https://registry.npmjs.org/@langchain/core/-/core-0.3.72.tgz", + "integrity": "sha512-WsGWVZYnlKffj2eEfDocPNiaTRoxyYiLSQdQ7oxZvxGZBqo/90vpjbC33UGK1uPNBM4kT+pkdaol/MnvKUh8TQ==", + "license": "MIT", + "peer": true, + "dependencies": { + "@cfworker/json-schema": "^4.0.2", + "ansi-styles": "^5.0.0", + "camelcase": "6", + "decamelize": "1.2.0", + "js-tiktoken": "^1.0.12", + "langsmith": "^0.3.46", + "mustache": "^4.2.0", + "p-queue": "^6.6.2", + "p-retry": "4", + "uuid": "^10.0.0", + "zod": "^3.25.32", + "zod-to-json-schema": "^3.22.3" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@langchain/langgraph": { + "version": "0.4.6", + "resolved": "https://registry.npmjs.org/@langchain/langgraph/-/langgraph-0.4.6.tgz", + "integrity": "sha512-4ivuy6PWMvgE7mOByePdJ88Mk7JpoC+nZ6SB0g9qhX3oZtIA5d3Fswtcr5hgS3XlYaTtr5hJRYdXBehZ3JNX3Q==", + "license": "MIT", + "dependencies": { + "@langchain/langgraph-checkpoint": "^0.1.0", + "@langchain/langgraph-sdk": "~0.0.109", + "uuid": "^10.0.0", + "zod": "^3.25.32" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@langchain/core": ">=0.3.58 < 0.4.0", + "zod-to-json-schema": "^3.x" + }, + "peerDependenciesMeta": { + "zod-to-json-schema": { + "optional": true + } + } + }, + "node_modules/@langchain/langgraph-checkpoint": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/@langchain/langgraph-checkpoint/-/langgraph-checkpoint-0.1.0.tgz", + "integrity": "sha512-7oY5b0VQSxcV3DgoHdXiCgBhEzml/ZjZfKNeuq6oZ3ggcdUICa/fzrIBbFju6gxPU8ly93s0OsjF4yURnHw70Q==", + "license": "MIT", + "dependencies": { + "uuid": "^10.0.0" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@langchain/core": ">=0.2.31 <0.4.0" + } + }, + "node_modules/@langchain/langgraph-sdk": { + "version": "0.0.109", + "resolved": "https://registry.npmjs.org/@langchain/langgraph-sdk/-/langgraph-sdk-0.0.109.tgz", + "integrity": "sha512-UpjL0c681CJqvKxgWD8o9fwUXRZzcDfsz8EcJ2PkXFxQFKRLe4QKZMtBr4OKFTR94pJtlOuTVla4OV5I5w+mdQ==", + "license": "MIT", + "dependencies": { + "@types/json-schema": "^7.0.15", + "p-queue": "^6.6.2", + "p-retry": "4", + "uuid": "^9.0.0" + }, + "peerDependencies": { + "@langchain/core": ">=0.2.31 <0.4.0", + "react": "^18 || ^19", + "react-dom": "^18 || ^19" + }, + "peerDependenciesMeta": { + "@langchain/core": { + "optional": true + }, + "react": { + "optional": true + }, + "react-dom": { + "optional": true + } + } + }, + "node_modules/@langchain/langgraph-sdk/node_modules/uuid": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-9.0.1.tgz", + "integrity": "sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA==", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "license": "MIT", + "bin": { + "uuid": "dist/bin/uuid" + } + }, + "node_modules/@smithy/abort-controller": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/abort-controller/-/abort-controller-4.2.0.tgz", + "integrity": "sha512-PLUYa+SUKOEZtXFURBu/CNxlsxfaFGxSBPcStL13KpVeVWIfdezWyDqkz7iDLmwnxojXD0s5KzuB5HGHvt4Aeg==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/chunked-blob-reader": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@smithy/chunked-blob-reader/-/chunked-blob-reader-5.1.0.tgz", + "integrity": "sha512-a36AtR7Q7XOhRPt6F/7HENmTWcB8kN7mDJcOFM/+FuKO6x88w8MQJfYCufMWh4fGyVkPjUh3Rrz/dnqFQdo6OQ==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/chunked-blob-reader-native": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@smithy/chunked-blob-reader-native/-/chunked-blob-reader-native-4.1.0.tgz", + "integrity": "sha512-Bnv0B3nSlfB2mPO0WgM49I/prl7+kamF042rrf3ezJ3Z4C7csPYvyYgZfXTGXwXfj1mAwDWjE/ybIf49PzFzvA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/util-base64": "^4.1.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/config-resolver": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/@smithy/config-resolver/-/config-resolver-4.3.0.tgz", + "integrity": "sha512-9oH+n8AVNiLPK/iK/agOsoWfrKZ3FGP3502tkksd6SRsKMYiu7AFX0YXo6YBADdsAj7C+G/aLKdsafIJHxuCkQ==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/node-config-provider": "^4.3.0", + "@smithy/types": "^4.6.0", + "@smithy/util-config-provider": "^4.2.0", + "@smithy/util-middleware": "^4.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/core": { + "version": "3.14.0", + "resolved": "https://registry.npmjs.org/@smithy/core/-/core-3.14.0.tgz", + "integrity": "sha512-XJ4z5FxvY/t0Dibms/+gLJrI5niRoY0BCmE02fwmPcRYFPI4KI876xaE79YGWIKnEslMbuQPsIEsoU/DXa0DoA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/middleware-serde": "^4.2.0", + "@smithy/protocol-http": "^5.3.0", + "@smithy/types": "^4.6.0", + "@smithy/util-base64": "^4.2.0", + "@smithy/util-body-length-browser": "^4.2.0", + "@smithy/util-middleware": "^4.2.0", + "@smithy/util-stream": "^4.4.0", + "@smithy/util-utf8": "^4.2.0", + "@smithy/uuid": "^1.1.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/credential-provider-imds": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/credential-provider-imds/-/credential-provider-imds-4.2.0.tgz", + "integrity": "sha512-SOhFVvFH4D5HJZytb0bLKxCrSnwcqPiNlrw+S4ZXjMnsC+o9JcUQzbZOEQcA8yv9wJFNhfsUiIUKiEnYL68Big==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/node-config-provider": "^4.3.0", + "@smithy/property-provider": "^4.2.0", + "@smithy/types": "^4.6.0", + "@smithy/url-parser": "^4.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/eventstream-codec": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/@smithy/eventstream-codec/-/eventstream-codec-4.1.1.tgz", + "integrity": "sha512-PwkQw1hZwHTQB6X5hSUWz2OSeuj5Z6enWuAqke7DgWoP3t6vg3ktPpqPz3Erkn6w+tmsl8Oss6nrgyezoea2Iw==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/crc32": "5.2.0", + "@smithy/types": "^4.5.0", + "@smithy/util-hex-encoding": "^4.1.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/eventstream-serde-browser": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/@smithy/eventstream-serde-browser/-/eventstream-serde-browser-4.1.1.tgz", + "integrity": "sha512-Q9QWdAzRaIuVkefupRPRFAasaG/droBqn1feiMnmLa+LLEUG45pqX1+FurHFmlqiCfobB3nUlgoJfeXZsr7MPA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/eventstream-serde-universal": "^4.1.1", + "@smithy/types": "^4.5.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/eventstream-serde-config-resolver": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@smithy/eventstream-serde-config-resolver/-/eventstream-serde-config-resolver-4.2.1.tgz", + "integrity": "sha512-oSUkF9zDN9zcOUBMtxp8RewJlh71E9NoHWU8jE3hU9JMYCsmW4assVTpgic/iS3/dM317j6hO5x18cc3XrfvEw==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.5.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/eventstream-serde-node": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/@smithy/eventstream-serde-node/-/eventstream-serde-node-4.1.1.tgz", + "integrity": "sha512-tn6vulwf/ScY0vjhzptSJuDJJqlhNtUjkxJ4wiv9E3SPoEqTEKbaq6bfqRO7nvhTG29ALICRcvfFheOUPl8KNA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/eventstream-serde-universal": "^4.1.1", + "@smithy/types": "^4.5.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/eventstream-serde-universal": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/@smithy/eventstream-serde-universal/-/eventstream-serde-universal-4.1.1.tgz", + "integrity": "sha512-uLOAiM/Dmgh2CbEXQx+6/ssK7fbzFhd+LjdyFxXid5ZBCbLHTFHLdD/QbXw5aEDsLxQhgzDxLLsZhsftAYwHJA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/eventstream-codec": "^4.1.1", + "@smithy/types": "^4.5.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/fetch-http-handler": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/@smithy/fetch-http-handler/-/fetch-http-handler-5.3.0.tgz", + "integrity": "sha512-BG3KSmsx9A//KyIfw+sqNmWFr1YBUr+TwpxFT7yPqAk0yyDh7oSNgzfNH7pS6OC099EGx2ltOULvumCFe8bcgw==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/protocol-http": "^5.3.0", + "@smithy/querystring-builder": "^4.2.0", + "@smithy/types": "^4.6.0", + "@smithy/util-base64": "^4.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/hash-blob-browser": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/@smithy/hash-blob-browser/-/hash-blob-browser-4.1.1.tgz", + "integrity": "sha512-avAtk++s1e/1VODf+rg7c9R2pB5G9y8yaJaGY4lPZI2+UIqVyuSDMikWjeWfBVmFZ3O7NpDxBbUCyGhThVUKWQ==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/chunked-blob-reader": "^5.1.0", + "@smithy/chunked-blob-reader-native": "^4.1.0", + "@smithy/types": "^4.5.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/hash-node": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/hash-node/-/hash-node-4.2.0.tgz", + "integrity": "sha512-ugv93gOhZGysTctZh9qdgng8B+xO0cj+zN0qAZ+Sgh7qTQGPOJbMdIuyP89KNfUyfAqFSNh5tMvC+h2uCpmTtA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.6.0", + "@smithy/util-buffer-from": "^4.2.0", + "@smithy/util-utf8": "^4.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/hash-stream-node": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/@smithy/hash-stream-node/-/hash-stream-node-4.1.1.tgz", + "integrity": "sha512-3ztT4pV0Moazs3JAYFdfKk11kYFDo4b/3R3+xVjIm6wY9YpJf+xfz+ocEnNKcWAdcmSMqi168i2EMaKmJHbJMA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.5.0", + "@smithy/util-utf8": "^4.1.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/invalid-dependency": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/invalid-dependency/-/invalid-dependency-4.2.0.tgz", + "integrity": "sha512-ZmK5X5fUPAbtvRcUPtk28aqIClVhbfcmfoS4M7UQBTnDdrNxhsrxYVv0ZEl5NaPSyExsPWqL4GsPlRvtlwg+2A==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/is-array-buffer": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/is-array-buffer/-/is-array-buffer-4.2.0.tgz", + "integrity": "sha512-DZZZBvC7sjcYh4MazJSGiWMI2L7E0oCiRHREDzIxi/M2LY79/21iXt6aPLHge82wi5LsuRF5A06Ds3+0mlh6CQ==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/md5-js": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/@smithy/md5-js/-/md5-js-4.1.1.tgz", + "integrity": "sha512-MvWXKK743BuHjr/hnWuT6uStdKEaoqxHAQUvbKJPPZM5ZojTNFI5D+47BoQfBE5RgGlRRty05EbWA+NXDv+hIA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.5.0", + "@smithy/util-utf8": "^4.1.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/middleware-content-length": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/middleware-content-length/-/middleware-content-length-4.2.0.tgz", + "integrity": "sha512-6ZAnwrXFecrA4kIDOcz6aLBhU5ih2is2NdcZtobBDSdSHtE9a+MThB5uqyK4XXesdOCvOcbCm2IGB95birTSOQ==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/protocol-http": "^5.3.0", + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/middleware-endpoint": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/@smithy/middleware-endpoint/-/middleware-endpoint-4.3.0.tgz", + "integrity": "sha512-jFVjuQeV8TkxaRlcCNg0GFVgg98tscsmIrIwRFeC74TIUyLE3jmY9xgc1WXrPQYRjQNK3aRoaIk6fhFRGOIoGw==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/core": "^3.14.0", + "@smithy/middleware-serde": "^4.2.0", + "@smithy/node-config-provider": "^4.3.0", + "@smithy/shared-ini-file-loader": "^4.3.0", + "@smithy/types": "^4.6.0", + "@smithy/url-parser": "^4.2.0", + "@smithy/util-middleware": "^4.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/middleware-retry": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/@smithy/middleware-retry/-/middleware-retry-4.4.0.tgz", + "integrity": "sha512-yaVBR0vQnOnzex45zZ8ZrPzUnX73eUC8kVFaAAbn04+6V7lPtxn56vZEBBAhgS/eqD6Zm86o6sJs6FuQVoX5qg==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/node-config-provider": "^4.3.0", + "@smithy/protocol-http": "^5.3.0", + "@smithy/service-error-classification": "^4.2.0", + "@smithy/smithy-client": "^4.7.0", + "@smithy/types": "^4.6.0", + "@smithy/util-middleware": "^4.2.0", + "@smithy/util-retry": "^4.2.0", + "@smithy/uuid": "^1.1.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/middleware-serde": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/middleware-serde/-/middleware-serde-4.2.0.tgz", + "integrity": "sha512-rpTQ7D65/EAbC6VydXlxjvbifTf4IH+sADKg6JmAvhkflJO2NvDeyU9qsWUNBelJiQFcXKejUHWRSdmpJmEmiw==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/protocol-http": "^5.3.0", + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/middleware-stack": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/middleware-stack/-/middleware-stack-4.2.0.tgz", + "integrity": "sha512-G5CJ//eqRd9OARrQu9MK1H8fNm2sMtqFh6j8/rPozhEL+Dokpvi1Og+aCixTuwDAGZUkJPk6hJT5jchbk/WCyg==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/node-config-provider": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/@smithy/node-config-provider/-/node-config-provider-4.3.0.tgz", + "integrity": "sha512-5QgHNuWdT9j9GwMPPJCKxy2KDxZ3E5l4M3/5TatSZrqYVoEiqQrDfAq8I6KWZw7RZOHtVtCzEPdYz7rHZixwcA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/property-provider": "^4.2.0", + "@smithy/shared-ini-file-loader": "^4.3.0", + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/node-http-handler": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/@smithy/node-http-handler/-/node-http-handler-4.3.0.tgz", + "integrity": "sha512-RHZ/uWCmSNZ8cneoWEVsVwMZBKy/8123hEpm57vgGXA3Irf/Ja4v9TVshHK2ML5/IqzAZn0WhINHOP9xl+Qy6Q==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/abort-controller": "^4.2.0", + "@smithy/protocol-http": "^5.3.0", + "@smithy/querystring-builder": "^4.2.0", + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/property-provider": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/property-provider/-/property-provider-4.2.0.tgz", + "integrity": "sha512-rV6wFre0BU6n/tx2Ztn5LdvEdNZ2FasQbPQmDOPfV9QQyDmsCkOAB0osQjotRCQg+nSKFmINhyda0D3AnjSBJw==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/protocol-http": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/@smithy/protocol-http/-/protocol-http-5.3.0.tgz", + "integrity": "sha512-6POSYlmDnsLKb7r1D3SVm7RaYW6H1vcNcTWGWrF7s9+2noNYvUsm7E4tz5ZQ9HXPmKn6Hb67pBDRIjrT4w/d7Q==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/querystring-builder": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/querystring-builder/-/querystring-builder-4.2.0.tgz", + "integrity": "sha512-Q4oFD0ZmI8yJkiPPeGUITZj++4HHYCW3pYBYfIobUCkYpI6mbkzmG1MAQQ3lJYYWj3iNqfzOenUZu+jqdPQ16A==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.6.0", + "@smithy/util-uri-escape": "^4.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/querystring-parser": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/querystring-parser/-/querystring-parser-4.2.0.tgz", + "integrity": "sha512-BjATSNNyvVbQxOOlKse0b0pSezTWGMvA87SvoFoFlkRsKXVsN3bEtjCxvsNXJXfnAzlWFPaT9DmhWy1vn0sNEA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/service-error-classification": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/service-error-classification/-/service-error-classification-4.2.0.tgz", + "integrity": "sha512-Ylv1ttUeKatpR0wEOMnHf1hXMktPUMObDClSWl2TpCVT4DwtJhCeighLzSLbgH3jr5pBNM0LDXT5yYxUvZ9WpA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.6.0" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/shared-ini-file-loader": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/@smithy/shared-ini-file-loader/-/shared-ini-file-loader-4.3.0.tgz", + "integrity": "sha512-VCUPPtNs+rKWlqqntX0CbVvWyjhmX30JCtzO+s5dlzzxrvSfRh5SY0yxnkirvc1c80vdKQttahL71a9EsdolSQ==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/signature-v4": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/@smithy/signature-v4/-/signature-v4-5.3.0.tgz", + "integrity": "sha512-MKNyhXEs99xAZaFhm88h+3/V+tCRDQ+PrDzRqL0xdDpq4gjxcMmf5rBA3YXgqZqMZ/XwemZEurCBQMfxZOWq/g==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/is-array-buffer": "^4.2.0", + "@smithy/protocol-http": "^5.3.0", + "@smithy/types": "^4.6.0", + "@smithy/util-hex-encoding": "^4.2.0", + "@smithy/util-middleware": "^4.2.0", + "@smithy/util-uri-escape": "^4.2.0", + "@smithy/util-utf8": "^4.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/smithy-client": { + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/@smithy/smithy-client/-/smithy-client-4.7.0.tgz", + "integrity": "sha512-3BDx/aCCPf+kkinYf5QQhdQ9UAGihgOVqI3QO5xQfSaIWvUE4KYLtiGRWsNe1SR7ijXC0QEPqofVp5Sb0zC8xQ==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/core": "^3.14.0", + "@smithy/middleware-endpoint": "^4.3.0", + "@smithy/middleware-stack": "^4.2.0", + "@smithy/protocol-http": "^5.3.0", + "@smithy/types": "^4.6.0", + "@smithy/util-stream": "^4.4.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/types": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.6.0.tgz", + "integrity": "sha512-4lI9C8NzRPOv66FaY1LL1O/0v0aLVrq/mXP/keUa9mJOApEeae43LsLd2kZRUJw91gxOQfLIrV3OvqPgWz1YsA==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/url-parser": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/url-parser/-/url-parser-4.2.0.tgz", + "integrity": "sha512-AlBmD6Idav2ugmoAL6UtR6ItS7jU5h5RNqLMZC7QrLCoITA9NzIN3nx9GWi8g4z1pfWh2r9r96SX/jHiNwPJ9A==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/querystring-parser": "^4.2.0", + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-base64": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-base64/-/util-base64-4.2.0.tgz", + "integrity": "sha512-+erInz8WDv5KPe7xCsJCp+1WCjSbah9gWcmUXc9NqmhyPx59tf7jqFz+za1tRG1Y5KM1Cy1rWCcGypylFp4mvA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/util-buffer-from": "^4.2.0", + "@smithy/util-utf8": "^4.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-body-length-browser": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-body-length-browser/-/util-body-length-browser-4.2.0.tgz", + "integrity": "sha512-Fkoh/I76szMKJnBXWPdFkQJl2r9SjPt3cMzLdOB6eJ4Pnpas8hVoWPYemX/peO0yrrvldgCUVJqOAjUrOLjbxg==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-body-length-node": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-body-length-node/-/util-body-length-node-4.2.0.tgz", + "integrity": "sha512-U8q1WsSZFjXijlD7a4wsDQOvOwV+72iHSfq1q7VD+V75xP/pdtm0WIGuaFJ3gcADDOKj2MIBn4+zisi140HEnQ==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-buffer-from": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-buffer-from/-/util-buffer-from-4.2.0.tgz", + "integrity": "sha512-kAY9hTKulTNevM2nlRtxAG2FQ3B2OR6QIrPY3zE5LqJy1oxzmgBGsHLWTcNhWXKchgA0WHW+mZkQrng/pgcCew==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/is-array-buffer": "^4.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-config-provider": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-config-provider/-/util-config-provider-4.2.0.tgz", + "integrity": "sha512-YEjpl6XJ36FTKmD+kRJJWYvrHeUvm5ykaUS5xK+6oXffQPHeEM4/nXlZPe+Wu0lsgRUcNZiliYNh/y7q9c2y6Q==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-defaults-mode-browser": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-defaults-mode-browser/-/util-defaults-mode-browser-4.2.0.tgz", + "integrity": "sha512-qzHp7ZDk1Ba4LDwQVCNp90xPGqSu7kmL7y5toBpccuhi3AH7dcVBIT/pUxYcInK4jOy6FikrcTGq5wxcka8UaQ==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/property-provider": "^4.2.0", + "@smithy/smithy-client": "^4.7.0", + "@smithy/types": "^4.6.0", + "bowser": "^2.11.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-defaults-mode-node": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-defaults-mode-node/-/util-defaults-mode-node-4.2.0.tgz", + "integrity": "sha512-FxUHS3WXgx3bTWR6yQHNHHkQHZm/XKIi/CchTnKvBulN6obWpcbzJ6lDToXn+Wp0QlVKd7uYAz2/CTw1j7m+Kg==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/config-resolver": "^4.3.0", + "@smithy/credential-provider-imds": "^4.2.0", + "@smithy/node-config-provider": "^4.3.0", + "@smithy/property-provider": "^4.2.0", + "@smithy/smithy-client": "^4.7.0", + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-endpoints": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-endpoints/-/util-endpoints-3.2.0.tgz", + "integrity": "sha512-TXeCn22D56vvWr/5xPqALc9oO+LN+QpFjrSM7peG/ckqEPoI3zaKZFp+bFwfmiHhn5MGWPaLCqDOJPPIixk9Wg==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/node-config-provider": "^4.3.0", + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-hex-encoding": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-hex-encoding/-/util-hex-encoding-4.2.0.tgz", + "integrity": "sha512-CCQBwJIvXMLKxVbO88IukazJD9a4kQ9ZN7/UMGBjBcJYvatpWk+9g870El4cB8/EJxfe+k+y0GmR9CAzkF+Nbw==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-middleware": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-middleware/-/util-middleware-4.2.0.tgz", + "integrity": "sha512-u9OOfDa43MjagtJZ8AapJcmimP+K2Z7szXn8xbty4aza+7P1wjFmy2ewjSbhEiYQoW1unTlOAIV165weYAaowA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-retry": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-retry/-/util-retry-4.2.0.tgz", + "integrity": "sha512-BWSiuGbwRnEE2SFfaAZEX0TqaxtvtSYPM/J73PFVm+A29Fg1HTPiYFb8TmX1DXp4hgcdyJcNQmprfd5foeORsg==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/service-error-classification": "^4.2.0", + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-stream": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/@smithy/util-stream/-/util-stream-4.4.0.tgz", + "integrity": "sha512-vtO7ktbixEcrVzMRmpQDnw/Ehr9UWjBvSJ9fyAbadKkC4w5Cm/4lMO8cHz8Ysb8uflvQUNRcuux/oNHKPXkffg==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/fetch-http-handler": "^5.3.0", + "@smithy/node-http-handler": "^4.3.0", + "@smithy/types": "^4.6.0", + "@smithy/util-base64": "^4.2.0", + "@smithy/util-buffer-from": "^4.2.0", + "@smithy/util-hex-encoding": "^4.2.0", + "@smithy/util-utf8": "^4.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-uri-escape": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-uri-escape/-/util-uri-escape-4.2.0.tgz", + "integrity": "sha512-igZpCKV9+E/Mzrpq6YacdTQ0qTiLm85gD6N/IrmyDvQFA4UnU3d5g3m8tMT/6zG/vVkWSU+VxeUyGonL62DuxA==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-utf8": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-4.2.0.tgz", + "integrity": "sha512-zBPfuzoI8xyBtR2P6WQj63Rz8i3AmfAaJLuNG8dWsfvPe8lO4aCPYLn879mEgHndZH1zQ2oXmG8O1GGzzaoZiw==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/util-buffer-from": "^4.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-waiter": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/@smithy/util-waiter/-/util-waiter-4.1.1.tgz", + "integrity": "sha512-PJBmyayrlfxM7nbqjomF4YcT1sApQwZio0NHSsT0EzhJqljRmvhzqZua43TyEs80nJk2Cn2FGPg/N8phH6KeCQ==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/abort-controller": "^4.1.1", + "@smithy/types": "^4.5.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/uuid": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@smithy/uuid/-/uuid-1.1.0.tgz", + "integrity": "sha512-4aUIteuyxtBUhVdiQqcDhKFitwfd9hqoSDYY2KRXiWtgoWJ9Bmise+KfEPDiVHWeJepvF8xJO9/9+WDIciMFFw==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@supabase/auth-js": { + "version": "2.87.1", + "resolved": "https://registry.npmjs.org/@supabase/auth-js/-/auth-js-2.87.1.tgz", + "integrity": "sha512-6RDeOf5TVoaXFtEstN188ykp3pXLZaU9qoAWfx8dc50FFAAqt+kcFJ96V0IvSmcpb4mDAWcpTJ7BegmVDn/WIw==", + "license": "MIT", + "dependencies": { + "tslib": "2.8.1" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@supabase/functions-js": { + "version": "2.87.1", + "resolved": "https://registry.npmjs.org/@supabase/functions-js/-/functions-js-2.87.1.tgz", + "integrity": "sha512-rWmYo4gRD0XAjMhYDlz7IH67bp4TIQ1UE4VqwIQtl1gGPwtLDq6wcRnu7jLKlXx0Gtrknw/eoiHYG9//XrCTzQ==", + "license": "MIT", + "dependencies": { + "tslib": "2.8.1" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@supabase/postgrest-js": { + "version": "2.87.1", + "resolved": "https://registry.npmjs.org/@supabase/postgrest-js/-/postgrest-js-2.87.1.tgz", + "integrity": "sha512-Yzu5eL3iGmZW0C/8x+vEojAOou63FI9oVw8HI8YOq63+5yM8g8aGh7Y1E2vbXFb7+gHGsPqLnaC6dPhrYt7qBA==", + "license": "MIT", + "dependencies": { + "tslib": "2.8.1" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@supabase/realtime-js": { + "version": "2.87.1", + "resolved": "https://registry.npmjs.org/@supabase/realtime-js/-/realtime-js-2.87.1.tgz", + "integrity": "sha512-XvLtEznxmYZXA7LYuy5zbSXpSYjDLJq2wQeRh3MzON2OR4U8Kq+RtPz2E2Wi8HEzvBfsc+nNu1TG8LQ9+3DRkA==", + "license": "MIT", + "dependencies": { + "@types/phoenix": "^1.6.6", + "@types/ws": "^8.18.1", + "tslib": "2.8.1", + "ws": "^8.18.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@supabase/storage-js": { + "version": "2.87.1", + "resolved": "https://registry.npmjs.org/@supabase/storage-js/-/storage-js-2.87.1.tgz", + "integrity": "sha512-0Uc8tNV4yzkNNmp1inpXru0RB4a7ECq05G2S6BDvSpMxTxJrDVJ4vVDwyhqB8ZZ+O9+8prHaQYoByQeuDnwpFQ==", + "license": "MIT", + "dependencies": { + "iceberg-js": "^0.8.1", + "tslib": "2.8.1" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@supabase/supabase-js": { + "version": "2.87.1", + "resolved": "https://registry.npmjs.org/@supabase/supabase-js/-/supabase-js-2.87.1.tgz", + "integrity": "sha512-tVgqZqnHZVum584KuUKSQZgcy6ZkhVd6gG8QWg2QfIXH9HmXdamauxdVsLXwaNPJxEdOyfAfwIyi5XUsiVYWtg==", + "license": "MIT", + "dependencies": { + "@supabase/auth-js": "2.87.1", + "@supabase/functions-js": "2.87.1", + "@supabase/postgrest-js": "2.87.1", + "@supabase/realtime-js": "2.87.1", + "@supabase/storage-js": "2.87.1" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@types/json-schema": { + "version": "7.0.15", + "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", + "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==", + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "25.0.0", + "resolved": "https://registry.npmjs.org/@types/node/-/node-25.0.0.tgz", + "integrity": "sha512-rl78HwuZlaDIUSeUKkmogkhebA+8K1Hy7tddZuJ3D0xV8pZSfsYGTsliGUol1JPzu9EKnTxPC4L1fiWouStRew==", + "license": "MIT", + "dependencies": { + "undici-types": "~7.16.0" + } + }, + "node_modules/@types/phoenix": { + "version": "1.6.7", + "resolved": "https://registry.npmjs.org/@types/phoenix/-/phoenix-1.6.7.tgz", + "integrity": "sha512-oN9ive//QSBkf19rfDv45M7eZPi0eEXylht2OLEXicu5b4KoQ1OzXIw+xDSGWxSxe1JmepRR/ZH283vsu518/Q==", + "license": "MIT" + }, + "node_modules/@types/retry": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/@types/retry/-/retry-0.12.0.tgz", + "integrity": "sha512-wWKOClTTiizcZhXnPY4wikVAwmdYHp8q6DmC+EJUzAMsycb7HB32Kh9RN4+0gExjmPmZSAQjgURXIGATPegAvA==", + "license": "MIT" + }, + "node_modules/@types/uuid": { + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-10.0.0.tgz", + "integrity": "sha512-7gqG38EyHgyP1S+7+xomFtL+ZNHcKv6DwNaCZmJmo1vgMugyF3TCnXVg4t1uk89mLNwnLtnY3TpOpCOyp1/xHQ==", + "license": "MIT" + }, + "node_modules/@types/ws": { + "version": "8.18.1", + "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz", + "integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/ansi-styles": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", + "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/bowser": { + "version": "2.12.1", + "resolved": "https://registry.npmjs.org/bowser/-/bowser-2.12.1.tgz", + "integrity": "sha512-z4rE2Gxh7tvshQ4hluIT7XcFrgLIQaw9X3A+kTTRdovCz5PMukm/0QC/BKSYPj3omF5Qfypn9O/c5kgpmvYUCw==", + "license": "MIT" + }, + "node_modules/camelcase": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.3.0.tgz", + "integrity": "sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/chalk/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "license": "MIT" + }, + "node_modules/console-table-printer": { + "version": "2.14.6", + "resolved": "https://registry.npmjs.org/console-table-printer/-/console-table-printer-2.14.6.tgz", + "integrity": "sha512-MCBl5HNVaFuuHW6FGbL/4fB7N/ormCy+tQ+sxTrF6QtSbSNETvPuOVbkJBhzDgYhvjWGrTma4eYJa37ZuoQsPw==", + "license": "MIT", + "dependencies": { + "simple-wcswidth": "^1.0.1" + } + }, + "node_modules/decamelize": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz", + "integrity": "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/dotenv": { + "version": "17.2.1", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.2.1.tgz", + "integrity": "sha512-kQhDYKZecqnM0fCnzI5eIv5L4cAe/iRI+HqMbO/hbRdTAeXDG+M9FjipUxNfbARuEg4iHIbhnhs78BCHNbSxEQ==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, + "node_modules/esbuild": { + "version": "0.25.9", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.9.tgz", + "integrity": "sha512-CRbODhYyQx3qp7ZEwzxOk4JBqmD/seJrzPa/cGjY1VtIn5E09Oi9/dB4JwctnfZ8Q8iT7rioVv5k/FNT/uf54g==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.25.9", + "@esbuild/android-arm": "0.25.9", + "@esbuild/android-arm64": "0.25.9", + "@esbuild/android-x64": "0.25.9", + "@esbuild/darwin-arm64": "0.25.9", + "@esbuild/darwin-x64": "0.25.9", + "@esbuild/freebsd-arm64": "0.25.9", + "@esbuild/freebsd-x64": "0.25.9", + "@esbuild/linux-arm": "0.25.9", + "@esbuild/linux-arm64": "0.25.9", + "@esbuild/linux-ia32": "0.25.9", + "@esbuild/linux-loong64": "0.25.9", + "@esbuild/linux-mips64el": "0.25.9", + "@esbuild/linux-ppc64": "0.25.9", + "@esbuild/linux-riscv64": "0.25.9", + "@esbuild/linux-s390x": "0.25.9", + "@esbuild/linux-x64": "0.25.9", + "@esbuild/netbsd-arm64": "0.25.9", + "@esbuild/netbsd-x64": "0.25.9", + "@esbuild/openbsd-arm64": "0.25.9", + "@esbuild/openbsd-x64": "0.25.9", + "@esbuild/openharmony-arm64": "0.25.9", + "@esbuild/sunos-x64": "0.25.9", + "@esbuild/win32-arm64": "0.25.9", + "@esbuild/win32-ia32": "0.25.9", + "@esbuild/win32-x64": "0.25.9" + } + }, + "node_modules/eventemitter3": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-4.0.7.tgz", + "integrity": "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==", + "license": "MIT" + }, + "node_modules/fast-xml-parser": { + "version": "5.2.5", + "resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-5.2.5.tgz", + "integrity": "sha512-pfX9uG9Ki0yekDHx2SiuRIyFdyAr1kMIMitPvb0YBo8SUfKvia7w7FIyd/l6av85pFYRhZscS75MwMnbvY+hcQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + } + ], + "license": "MIT", + "dependencies": { + "strnum": "^2.1.0" + }, + "bin": { + "fxparser": "src/cli/cli.js" + } + }, + "node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/iceberg-js": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/iceberg-js/-/iceberg-js-0.8.1.tgz", + "integrity": "sha512-1dhVQZXhcHje7798IVM+xoo/1ZdVfzOMIc8/rgVSijRK38EDqOJoGula9N/8ZI5RD8QTxNQtK/Gozpr+qUqRRA==", + "license": "MIT", + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/idb": { + "version": "8.0.3", + "resolved": "https://registry.npmjs.org/idb/-/idb-8.0.3.tgz", + "integrity": "sha512-LtwtVyVYO5BqRvcsKuB2iUMnHwPVByPCXFXOpuU96IZPPoPN6xjOGxZQ74pgSVVLQWtUOYgyeL4GE98BY5D3wg==", + "license": "ISC" + }, + "node_modules/js-tiktoken": { + "version": "1.0.21", + "resolved": "https://registry.npmjs.org/js-tiktoken/-/js-tiktoken-1.0.21.tgz", + "integrity": "sha512-biOj/6M5qdgx5TKjDnFT1ymSpM5tbd3ylwDtrQvFQSu0Z7bBYko2dF+W/aUkXUPuk6IVpRxk/3Q2sHOzGlS36g==", + "license": "MIT", + "dependencies": { + "base64-js": "^1.5.1" + } + }, + "node_modules/langsmith": { + "version": "0.3.62", + "resolved": "https://registry.npmjs.org/langsmith/-/langsmith-0.3.62.tgz", + "integrity": "sha512-ApoGLs28cJCxL91l1PDDkjsA4oLrbeNlE1pyTvyopqXq9bNJrP8JPUNWZm/tpU0DzZpvZFctRzru4gNAr/bkxg==", + "license": "MIT", + "dependencies": { + "@types/uuid": "^10.0.0", + "chalk": "^4.1.2", + "console-table-printer": "^2.12.1", + "p-queue": "^6.6.2", + "p-retry": "4", + "semver": "^7.6.3", + "uuid": "^10.0.0" + }, + "peerDependencies": { + "@opentelemetry/api": "*", + "@opentelemetry/exporter-trace-otlp-proto": "*", + "@opentelemetry/sdk-trace-base": "*", + "openai": "*" + }, + "peerDependenciesMeta": { + "@opentelemetry/api": { + "optional": true + }, + "@opentelemetry/exporter-trace-otlp-proto": { + "optional": true + }, + "@opentelemetry/sdk-trace-base": { + "optional": true + }, + "openai": { + "optional": true + } + } + }, + "node_modules/minisearch": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/minisearch/-/minisearch-7.2.0.tgz", + "integrity": "sha512-dqT2XBYUOZOiC5t2HRnwADjhNS2cecp9u+TJRiJ1Qp/f5qjkeT5APcGPjHw+bz89Ms8Jp+cG4AlE+QZ/QnDglg==", + "license": "MIT" + }, + "node_modules/mustache": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/mustache/-/mustache-4.2.0.tgz", + "integrity": "sha512-71ippSywq5Yb7/tVYyGbkBggbU8H3u5Rz56fH60jGFgr8uHwxs+aSKeqmluIVzM0m0kB7xQjKS6qPfd0b2ZoqQ==", + "license": "MIT", + "bin": { + "mustache": "bin/mustache" + } + }, + "node_modules/p-finally": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/p-finally/-/p-finally-1.0.0.tgz", + "integrity": "sha512-LICb2p9CB7FS+0eR1oqWnHhp0FljGLZCWBE9aix0Uye9W8LTQPwMTYVGWQWIw9RdQiDg4+epXQODwIYJtSJaow==", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/p-queue": { + "version": "6.6.2", + "resolved": "https://registry.npmjs.org/p-queue/-/p-queue-6.6.2.tgz", + "integrity": "sha512-RwFpb72c/BhQLEXIZ5K2e+AhgNVmIejGlTgiB9MzZ0e93GRvqZ7uSi0dvRF7/XIXDeNkra2fNHBxTyPDGySpjQ==", + "license": "MIT", + "dependencies": { + "eventemitter3": "^4.0.4", + "p-timeout": "^3.2.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-retry": { + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/p-retry/-/p-retry-4.6.2.tgz", + "integrity": "sha512-312Id396EbJdvRONlngUx0NydfrIQ5lsYu0znKVUzVvArzEIt08V1qhtyESbGVd1FGX7UKtiFp5uwKZdM8wIuQ==", + "license": "MIT", + "dependencies": { + "@types/retry": "0.12.0", + "retry": "^0.13.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/p-timeout": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/p-timeout/-/p-timeout-3.2.0.tgz", + "integrity": "sha512-rhIwUycgwwKcP9yTOOFK/AKsAopjjCakVqLHePO3CC6Mir1Z99xT+R63jZxAT5lFZLa2inS5h+ZS2GvR99/FBg==", + "license": "MIT", + "dependencies": { + "p-finally": "^1.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/retry": { + "version": "0.13.1", + "resolved": "https://registry.npmjs.org/retry/-/retry-0.13.1.tgz", + "integrity": "sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg==", + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/semver": { + "version": "7.7.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.2.tgz", + "integrity": "sha512-RF0Fw+rO5AMf9MAyaRXI4AV0Ulj5lMHqVxxdSgiVbixSCXoEmmX/jk0CuJw4+3SqroYO9VoUh+HcuJivvtJemA==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/simple-wcswidth": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/simple-wcswidth/-/simple-wcswidth-1.1.2.tgz", + "integrity": "sha512-j7piyCjAeTDSjzTSQ7DokZtMNwNlEAyxqSZeCS+CXH7fJ4jx3FuJ/mTW3mE+6JLs4VJBbcll0Kjn+KXI5t21Iw==", + "license": "MIT" + }, + "node_modules/strnum": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/strnum/-/strnum-2.1.1.tgz", + "integrity": "sha512-7ZvoFTiCnGxBtDqJ//Cu6fWtZtc7Y3x+QOirG15wztbdngGSkht27o2pyGWrVy0b4WAy3jbKmnoK6g5VlVNUUw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + } + ], + "license": "MIT" + }, + "node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "license": "0BSD" + }, + "node_modules/typescript": { + "version": "5.9.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.2.tgz", + "integrity": "sha512-CWBzXQrc/qOkhidw1OzBTQuYRbfyxDXJMVJ1XNwUHGROVmuaeiEm3OslpZ1RV96d7SKKjZKrSJu3+t/xlw3R9A==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "7.16.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.16.0.tgz", + "integrity": "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==", + "license": "MIT" + }, + "node_modules/uuid": { + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-10.0.0.tgz", + "integrity": "sha512-8XkAphELsDnEGrDxUOHB3RGvXz6TeuYSGEZBOjtTtPm2lwhGBjLgOzLHB63IUWfBpNucQjND6d3AOudO+H3RWQ==", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "license": "MIT", + "bin": { + "uuid": "dist/bin/uuid" + } + }, + "node_modules/ws": { + "version": "8.18.3", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.18.3.tgz", + "integrity": "sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/zod": { + "version": "3.25.76", + "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz", + "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==", + "license": "MIT", + "peer": true, + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + }, + "node_modules/zod-to-json-schema": { + "version": "3.24.6", + "resolved": "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.24.6.tgz", + "integrity": "sha512-h/z3PKvcTcTetyjl1fkj79MHNEjm+HpD6NXheWjzOekY7kV+lwDYnHw+ivHkijnCSMz1yJaWBD9vu/Fcmk+vEg==", + "license": "ISC", + "peerDependencies": { + "zod": "^3.24.1" + } + } + } +} diff --git a/browser/base/content/assistant/build/package.json b/browser/base/content/assistant/build/package.json new file mode 100644 index 0000000000000..1c5a63e5e2a8a --- /dev/null +++ b/browser/base/content/assistant/build/package.json @@ -0,0 +1,26 @@ +{ + "name": "assistant-bundle", + "private": true, + "type": "module", + "scripts": { + "build": "node esbuild.config.mjs" + }, + "devDependencies": { + "dotenv": "^17.2.1", + "esbuild": "^0.25.9", + "typescript": "^5.5.4" + }, + "dependencies": { + "@aws-crypto/sha256-js": "^5.2.0", + "@aws-sdk/client-s3": "^3.896.0", + "@aws-sdk/credential-provider-cognito-identity": "^3.901.0", + "@aws-sdk/protocol-http": "^3.370.0", + "@aws-sdk/signature-v4": "^3.370.0", + "@langchain/core": "^0.3.72", + "@langchain/langgraph": "^0.4.6", + "@supabase/supabase-js": "^2.45.4", + "idb": "^8.0.3", + "minisearch": "^7.2.0", + "zod": "^3.25.76" + } +} diff --git a/browser/base/content/assistant/build/src/assistant.ts b/browser/base/content/assistant/build/src/assistant.ts new file mode 100644 index 0000000000000..a6b78fc4500f8 --- /dev/null +++ b/browser/base/content/assistant/build/src/assistant.ts @@ -0,0 +1,358 @@ +import { Annotation, END, START, StateGraph } from "@langchain/langgraph/web"; +import { HumanMessage, AIMessage, BaseMessage } from "@langchain/core/messages"; +import { routeRemote, chatRemote } from "./proxyClient"; +import SupabaseAuth from "./services/supabase"; +import voiceInputService from "./services/voiceInput"; + +// Local command implementations (tabs / groups) +import { + ListTabsCommand, + OpenTabCommand, + CloseTabCommand, + MoveTabToNewWindowCommand, + CopyTabUrlsCommand, + SplitTabsCommand, + CreateHubCommand, + DeleteHubCommand, + ListHubsCommand, + RenameHubCommand, + AddTabToHubCommand, + OpenHubCommand, + NewWindowCommand, + OrganizeWindowsCommand, + ShowURLCommand, + SearchMemoryCommand, + Command, + CmdResult, +} from "./commands"; + +// Expose Supabase auth for UI +const supabaseAuth = SupabaseAuth.getInstance(); +(window as any).supabaseAuth = supabaseAuth; + +// Expose voice input service for UI +(window as any).voiceInputService = voiceInputService; + +/* ========= Ephemeral chat history per session ========= */ +// Automatically managed - one session per sidebar instance +let CURRENT_SESSION: BaseMessage[] = []; +const MAX_TURNS = 12; // keep last 12 user/assistant pairs + +function getCurrentSessionMessages(): BaseMessage[] { + return CURRENT_SESSION; +} + +function pushCurrentTurn(user: string, assistant: string) { + CURRENT_SESSION.push(new HumanMessage(user)); + CURRENT_SESSION.push(new AIMessage(assistant)); + const cap = MAX_TURNS * 2; + if (CURRENT_SESSION.length > cap) { + CURRENT_SESSION.splice(0, CURRENT_SESSION.length - cap); + } +} + +export function resetAssistantSession() { + CURRENT_SESSION = []; +} + +export function getAssistantHistory(): BaseMessage[] { + return [...CURRENT_SESSION]; +} + +/* ========= LangGraph state ========= */ +const GraphState = Annotation.Root({ + messages: Annotation({ + reducer: (x, y) => x.concat(y), + default: () => [], + }), + next: Annotation({ + reducer: (x, y) => y ?? x ?? END, + default: () => END, + }), + lastWorker: Annotation({ + reducer: (x, y) => y ?? x ?? "", + default: () => "", + }), + repeatCount: Annotation({ + reducer: (x, y) => (typeof y === "number" ? y : (x ?? 0)), + default: () => 0, + }), + args: Annotation>({ + reducer: (x, y) => (y ? { ...(x || {}), ...y } : x), + default: () => ({}), + }), +}); + +/* ========= Helpers ========= */ +function msgText(m: any): string { + if (!m) return ""; + const c = m.content; + if (typeof c === "string") return c; + if (Array.isArray(c)) return c.map(v => (typeof v === "string" ? v : v?.text || "")).join(""); + return String(c ?? ""); +} + +type WireMsg = { role: "user" | "model"; content: string }; +function toWire(messages: BaseMessage[]): WireMsg[] { + return messages.map(m => { + const role = m._getType() === "human" ? "user" : "model"; + return { role, content: msgText(m) }; + }); +} + +/* ========= Build the tool graph ========= */ +async function buildGraph(commands: Command[]) { + const toolAgents: Record = {}; + const memberNames: string[] = []; + + for (const command of commands) { + // Node: run the command and emit a message that clearly identifies the tool's output. + const node = async (state: typeof GraphState.State) => { + const result: CmdResult = await command.execute(state.args); + const content = `[Tool Output for ${command.commandName}]: ${result.message}`; + return { + messages: [new AIMessage({ content, name: command.commandName })], + // Clear state to prevent re-running the same tool + lastWorker: "", + repeatCount: 0, + args: {}, + }; + }; + + toolAgents[command.commandName] = node; + memberNames.push(command.commandName); + } + + // ---------- Supervisor with routing rules + few-shots ---------- + const systemTemplate = `You are a supervisor agent that manages a team of workers. +Your job is to intelligently route the user's request to the appropriate worker. +You will be given the user's request and the conversation history. + +**Workers** +You have the following workers available: +{members} + +**Worker Arguments** +- **list_tabs**: No arguments needed +- **open_tab**: { url: string } - the website URL to open +- **close_tab**: { index?: number } - OPTIONAL 1-based tab number (e.g., "close tab 2" = { index: 2 }). If no index, closes active tab. +- **move_tab_to_new_window**: { index?: number } - OPTIONAL 1-based tab number +- **copy_tab_urls**: No arguments needed +- **split_tabs**: { indices: [number, number, ...] } - split tabs into side-by-side windows (e.g., "split tab 1 and 2" = { indices: [1, 2] }) +- **create_hub**: { name: string, include?: "none"|"current"|"all" } +- **delete_hub**: { name: string, closeTabs?: boolean } +- **list_hubs**: No arguments needed +- **rename_hub**: { from: string, to: string } +- **add_tab_to_hub**: { name: string } +- **open_hub**: { name: string, where?: "tabs"|"window" } +- **new_window**: No arguments needed +- **organize_windows**: No arguments needed +- **show_url**: { url: string } +- **search_memory**: { query: string, hub?: string } - search for keywords in bookmarks/hubs. Use this when user asks to "search" a hub or "find" something in memory. + +**Rules** +1. **Analyze History:** Review the conversation history. Messages starting with \`[Tool Output for ...]\` are the results of a worker's action. +2. **Extract Arguments:** When the user mentions tab numbers (e.g., "tab 2", "the first tab", "second one"), convert to { index: N } where N is 1-based. +3. **Check for Completion:** If the last message is a \`[Tool Output for ...]\` and it seems to fulfill the user's last request, choose the "FINISH" worker. +4. **Handle Multi-Step:** If the user's request requires another step (e.g., "open X *and then* do Y"), and you see the \`[Tool Output for ...]\` from the first step, choose the worker for the second step. +5. **Chat:** If the user is making casual conversation (e.g., "hello", "thank you"), choose the "chat" worker. +6. **Handle Failures:** If a tool returns "No matches found" or an error, DO NOT retry the same action. Choose "chat" to inform the user. +7. **Default Action:** Otherwise, choose the worker that best addresses the user's most recent unfulfilled request. + +**Output Format** +You MUST respond with a JSON object that follows this schema: +\`\`\`json +{ + "next": "", + "args": { + "": "" + } +} +\`\`\` + +**Examples** +User: "Open a new tab to google.com" +→ { "next": "open_tab", "args": { "url": "google.com" } } + +User: "Close tab 3" +→ { "next": "close_tab", "args": { "index": 3 } } + +User: "Close the second tab" +→ { "next": "close_tab", "args": { "index": 2 } } + +User: "Split tab 1 and 2" +→ { "next": "split_tabs", "args": { "indices": [1, 2] } } + +User: "Split tabs 1, 2, and 3" +→ { "next": "split_tabs", "args": { "indices": [1, 2, 3] } } + +User: "List all tabs" then "close the first one" +→ First: { "next": "list_tabs", "args": {} } +→ Then: { "next": "close_tab", "args": { "index": 1 } } + +The available workers are: {options}`.trim(); + + const chatNode = async (state: typeof GraphState.State) => { + const CHAT_PROMPT = `You are a helpful Firefox browser assistant with full conversation memory. + +**Important:** You have access to the complete conversation history, including: +- All previous user requests +- Commands that were executed (marked as [Tool Output for ...]) +- Results from those commands + +**When answering questions:** +1. If asked to summarize or recall: Review the conversation history and list what happened +2. If asked general questions: Answer helpfully based on what you know +3. You can see everything that happened in this conversation - use that context! + +**Example:** +If the history shows: + - User: "list tabs" + - Tool Output: "1. Google, 2. CNN" + - User: "close the first tab" + - Tool Output: "Closed: Google" + +And user asks "what have we done?", you should respond: +"We listed the tabs (found Google and CNN), then closed the first tab (Google)." + +Remember: You ARE stateful within this conversation. The history is right there in your context!`; + + // Debug: Log what messages the chat node receives + console.log(`💬 Chat node received ${state.messages.length} messages:`, + state.messages.map((m: any) => `${m._getType()}: ${msgText(m).substring(0, 50)}...`)); + + const res = await chatRemote(CHAT_PROMPT, toWire(state.messages)); + return { messages: [new AIMessage(res.content)] }; + }; + + const supervisorNode = async (s: typeof GraphState.State) => { + const options = [END, ...memberNames, "chat"]; + const systemPrompt = systemTemplate + .replace("{members}", memberNames.join(", ")) + .replace("{options}", options.join(", ")); + + // Use only the messages from the current graph execution for routing decisions. + const messages = s.messages; + const out = await routeRemote(systemPrompt, toWire(messages), options); + const nextTool = out?.next; + const nextArgs = out?.args || {}; + + // The supervisor can return "FINISH" to end the conversation. + if (nextTool === "FINISH") { + return { next: END }; + } + + // If the supervisor selected a valid tool, use it. + if (nextTool && memberNames.includes(nextTool)) { + return { next: nextTool, args: nextArgs }; + } + + // Otherwise, fall back to chat. This handles conversational replies. + return { next: "chat", args: {} }; + }; + + const workflow = new StateGraph(GraphState); + for (const name of memberNames) { + workflow.addNode(name, toolAgents[name]); + workflow.addEdge(name as any, "supervisor" as any); + } + workflow.addNode("chat", chatNode); + workflow.addEdge("chat" as any, END as any); + workflow.addNode("supervisor", supervisorNode); + workflow.addConditionalEdges("supervisor" as any, (x: typeof GraphState.State) => x.next); + workflow.addEdge(START, "supervisor" as any); + + return workflow.compile(); +} + +// ---------- Public APIs ---------- + +// Streaming variant used by the UI for live updates +export async function runAssistantStream( + prompt: string, + onChunk: (text: string) => void +): Promise { + const isAuthenticated = await supabaseAuth. isAuthenticated(); + if (!isAuthenticated) { + const msg = "Please sign in to use the assistant."; + onChunk(msg); + return msg; + } + + const commands: Command[] = [ + // Tabs + new ListTabsCommand(), + new OpenTabCommand(), + new CloseTabCommand(), + new MoveTabToNewWindowCommand(), + new CopyTabUrlsCommand(), + new SplitTabsCommand(), + // Hubs + new CreateHubCommand(), + new DeleteHubCommand(), + new ListHubsCommand(), + new RenameHubCommand(), + new AddTabToHubCommand(), + new OpenHubCommand(), + new NewWindowCommand(), + new OrganizeWindowsCommand(), + new ShowURLCommand(), + new SearchMemoryCommand(), + ]; + const graph = await buildGraph(commands); + + // Get conversation history for context - automatically managed + const sessionHistory = getCurrentSessionMessages(); + + // Debug: Log how many messages are in context + console.log(`📚 Session context: ${sessionHistory.length} messages in history`); + + const stream = await graph.stream( + { messages: [...sessionHistory, new HumanMessage({ content: prompt })] }, + { recursionLimit: 16 } + ); + + let lastFull = ""; + let stepCount = 0; + for await (const state of stream as any) { + stepCount++; + console.log(`🔄 Stream step ${stepCount}, keys:`, Object.keys(state)); + + if ("__end__" in state) { + // Save conversation turn automatically + console.log(`🔚 Stream ended. lastFull length: ${lastFull.length}`); + if (lastFull) { + console.log(`✅ Saving turn to session: "${prompt}" -> "${lastFull.substring(0, 50)}..."`); + pushCurrentTurn(prompt, lastFull); + } else { + console.log(`⚠️ NOT saving turn - lastFull is empty!`); + } + break; + } + const step = Object.entries(state).find(([k]) => k !== "__end"); + if (step?.[1] && "messages" in (step[1] as any)) { + const lastMsg = (step[1] as any).messages.at(-1); + let text = ""; + if (typeof lastMsg?.content === "string") text = lastMsg.content; + else if (Array.isArray(lastMsg?.content)) + text = lastMsg.content.map((c: any) => (typeof c === "string" ? c : c?.text || "")).join(""); + else if (lastMsg?.content != null) text = String(lastMsg.content); + + if (text && text !== lastFull) { + const delta = text.startsWith(lastFull) ? text.slice(lastFull.length) : text; + onChunk(delta); + lastFull = text; + console.log(`📝 Updated lastFull, length now: ${lastFull.length}`); + } + } + } + console.log(`🏁 Stream finished. Final lastFull length: ${lastFull.length}`); + + // SAFETY: Always save the turn even if we didn't hit __end__ + if (lastFull) { + console.log(`✅ Saving turn to session (post-stream): "${prompt}" -> "${lastFull.substring(0, 50)}..."`); + pushCurrentTurn(prompt, lastFull); + } + + return lastFull || "(no output)"; +} diff --git a/browser/base/content/assistant/build/src/awsSignedFetch.ts b/browser/base/content/assistant/build/src/awsSignedFetch.ts new file mode 100644 index 0000000000000..5d4d4e374249d --- /dev/null +++ b/browser/base/content/assistant/build/src/awsSignedFetch.ts @@ -0,0 +1,46 @@ +// Signs POSTs to a Lambda Function URL with Supabase JWT +import SupabaseAuth from "./services/supabase"; + +const functionUrl = process.env.OASIS_API_BASE!.replace(/\/+$/, "/"); +const transcribeUrl = process.env.OASIS_TRANSCRIBE_URL || functionUrl; // Separate endpoint for transcription (optional) +const supabaseAuth = SupabaseAuth.getInstance(); + +export async function postSigned(op: "route" | "chat" | "transcribe" | "tts", payload: Record) { + // Use separate transcription endpoint if configured, otherwise use main endpoint + const endpoint = (op === "transcribe" || op === "tts") ? transcribeUrl : functionUrl; + + const url = new URL(endpoint); + const body = JSON.stringify({ op, ...payload }); + + const session = await supabaseAuth.getSession(); + const token = session?.access_token; + + if (!token) { + throw new Error("Authentication required: No JWT found"); + } + + const headers: Record = { + "content-type": "application/json", + }; + + // Only add auth header for chat/route operations + // Transcription lambda doesn't verify JWT + if (op === "route" || op === "chat") { + headers.Authorization = `Bearer ${token}`; + } + + console.log(`[postSigned] Calling ${op} at ${endpoint}`); + console.log(`[postSigned] Headers:`, headers); + console.log(`[postSigned] Body length:`, body.length); + + const res = await fetch(endpoint, { method: "POST", headers, body }); + + console.log(`[postSigned] Response status:`, res.status); + + if (!res.ok) { + const errorBody = await res.text(); + console.error("Lambda Error:", errorBody); + throw new Error(`Lambda ${res.status} ${errorBody}`); + } + return res.json(); +} diff --git a/browser/base/content/assistant/build/src/commands.ts b/browser/base/content/assistant/build/src/commands.ts new file mode 100644 index 0000000000000..ba7c16d40583b --- /dev/null +++ b/browser/base/content/assistant/build/src/commands.ts @@ -0,0 +1,359 @@ +import { hubs, CreateHubOpts, DeleteHubOpts } from "./hubs"; +import { localMemory } from "./services/localMemory"; + +export type CmdResult = { message: string }; + +export interface Command { + commandName: string; + description: string; + execute(args: any): Promise; +} + +/** Get the privileged top-level browser window/objects */ +function getChrome() { + const topWin = (window.top as any); + const gBrowser = topWin?.gBrowser; + return { topWin, gBrowser }; +} + +/* =========================== + * Tab Commands + * =========================== */ + +export class ListTabsCommand implements Command { + commandName = "list_tabs"; + description = "List titles of tabs in the current window. Accepts no arguments."; + async execute(_args: any): Promise { + const { gBrowser } = getChrome(); + if (!gBrowser) return { message: "Browser UI (gBrowser) not available." }; + const titles = Array.from(gBrowser.tabs).map((t: any) => + t.label || t.linkedBrowser?.contentTitle || t.linkedBrowser?.currentURI?.spec || "(untitled)" + ); + const out = titles.length + ? titles.slice(0, 50).map((t, i) => `${i + 1}. ${t}`).join("\n") + : "No tabs."; + return { message: out }; + } +} + +export class NewWindowCommand implements Command { + commandName = "new_window"; + description = "Open a new browser window."; + async execute(args: any): Promise { + const { topWin } = getChrome(); + if (!topWin) return { message: "Browser UI not available." }; + + topWin.OpenBrowserWindow(); + return { message: "Opened a new window." }; + } +} + +export class OrganizeWindowsCommand implements Command { + commandName = "organize_windows"; + description = "Arrange two or more windows side-by-side."; + async execute(args: any): Promise { + const { topWin } = getChrome(); + if (!topWin) return { message: "Browser UI not available." }; + + // Access Services.jsm via ChromeUtils + const { ChromeUtils } = topWin; + if (!ChromeUtils) return { message: "ChromeUtils not available." }; + const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); + + const windowManager = Services.wm; + const windows = windowManager.getEnumerator("navigator:browser"); + const browserWindows = []; + + while (windows.hasMoreElements()) { + browserWindows.push(windows.getNext()); + } + + if (browserWindows.length < 2) { + return { message: "You need at least two windows to organize." }; + } + + const screen = topWin.screen; + const availWidth = screen.availWidth; + const availHeight = screen.availHeight; + const availLeft = screen.availLeft || 0; + const availTop = screen.availTop || 0; + const numWindows = browserWindows.length; + const windowWidth = Math.floor(availWidth / numWindows); + + for (let i = 0; i < numWindows; i++) { + const win = browserWindows[i]; + const xPos = availLeft + (windowWidth * i); + win.resizeTo(windowWidth, availHeight); + win.moveTo(xPos, availTop); + } + + return { message: `Organized ${numWindows} windows.` }; + } +} + +export class ShowURLCommand implements Command { + commandName = "show_url"; + description = "Open a URL in a new tab."; + async execute(args: any): Promise { + const { topWin } = getChrome(); + if (!topWin) return { message: "Browser UI not available." }; + + const url = args?.url; + if (!url) return { message: "Missing 'url' argument." }; + + topWin.openTrustedLinkIn(url, "tab"); + return { message: `Opened ${url}` }; + } +} + +export class OpenTabCommand implements Command { + commandName = "open_tab"; + description = "Open a new tab with a given URL. Accepts arguments: { url: string }."; + async execute(args: any): Promise { + const { topWin } = getChrome(); + const url = args?.url; + if (!url) return { message: "Missing 'url' argument." }; + if (!topWin?.openTrustedLinkIn) return { message: "Cannot open tab (openTrustedLinkIn not found)." }; + topWin.openTrustedLinkIn(url, "tab"); + return { message: `Opened ${url}` }; + } +} + +export class CloseTabCommand implements Command { + commandName = "close_tab"; + description = "Close the active tab (or a tab by index). Accepts arguments: { index?: number } (1-based)."; + async execute(args: any): Promise { + const { gBrowser } = getChrome(); + if (!gBrowser) return { message: "Browser UI (gBrowser) not available." }; + let tab = gBrowser.selectedTab; + const idx = args?.index; + if (idx != null) { + const i = Math.max(1, Math.floor(idx)); + if (i > gBrowser.tabs.length) return { message: `No tab ${i}.` }; + tab = gBrowser.tabs[i - 1]; + } + const title = tab?.label || "(untitled)"; + gBrowser.removeTab(tab); + return { message: `Closed: ${title}` }; + } +} + +export class MoveTabToNewWindowCommand implements Command { + commandName = "move_tab_to_new_window"; + description = "Move the active tab (or a tab by index) to a new window. Accepts arguments: { index?: number } (1-based)."; + async execute(args: any): Promise { + const { topWin, gBrowser } = getChrome(); + if (!gBrowser || !topWin) return { message: "Browser UI not available." }; + + let tab = gBrowser.selectedTab; + const idx = args?.index; + if (idx != null) { + const i = Math.max(1, Math.floor(idx)); + if (i > gBrowser.tabs.length) return { message: `No tab ${i}.` }; + tab = gBrowser.tabs[i - 1]; + } + const title = tab?.label || tab?.linkedBrowser?.currentURI?.spec || "(untitled)"; + const newWin = topWin.OpenBrowserWindow(); + await new Promise(r => setTimeout(r, 250)); // give it a tick + (newWin as any).gBrowser.adoptTab(tab, 0); + return { message: `Moved: ${title}` }; + } +} + +export class CopyTabUrlsCommand implements Command { + commandName = "copy_tab_urls"; + description = "Copy all tab URLs in the current window to the clipboard (one per line). Accepts no arguments."; + async execute(_args: any): Promise { + const { gBrowser } = getChrome(); + if (!gBrowser) return { message: "Browser UI (gBrowser) not available." }; + const urls = Array.from(gBrowser.tabs) + .map((t: any) => t.linkedBrowser?.currentURI?.spec) + .filter(Boolean); + const text = urls.join("\n"); + try { + await navigator.clipboard.writeText(text); + return { message: `Copied ${urls.length} URLs to clipboard.` }; + } catch { + return { message: `Copied fallback. URLs:\n${text}` }; + } + } +} + +/* =========================== + * Hub Commands + * =========================== */ + +export class CreateHubCommand implements Command { + commandName = "create_hub"; + description = "Create a bookmark folder hub. Accepts arguments: { name: string, include?: 'none'|'current'|'all' }."; + async execute(args: any): Promise { + const name = args?.name || ""; + const include = args?.include || "none"; + const res = await hubs.create(name, { include }); + return { message: `Created bookmark folder "${res.name}" (${res.count} items).` }; + } +} + +export class DeleteHubCommand implements Command { + commandName = "delete_hub"; + description = "Delete a bookmark folder hub by name. Accepts arguments: { name: string, closeTabs?: boolean }."; + async execute(args: any): Promise { + const name = args?.name; + if (!name) return { message: "Which hub should I delete?" }; + const closeTabs = args?.closeTabs || false; + const res = await hubs.delete(name, { closeTabs }); + if (res.removed === 0) return { message: `No hub named "${name}".` }; + return { message: `Deleted bookmark folder "${res.name}" (${res.removed} items${closeTabs ? "; tabs closed" : ""}).` }; + } +} + +export class ListHubsCommand implements Command { + commandName = "list_hubs"; + description = "List all bookmark folder hubs. Accepts no arguments."; + async execute(_args: any): Promise { + const items = await hubs.list(); + if (!items.length) return { message: "No bookmark folder hubs yet." }; + return { message: items.map(h => `• ${h.name} (${h.count})`).join("\n") }; + } +} + +export class RenameHubCommand implements Command { + commandName = "rename_hub"; + description = "Rename a bookmark folder hub. Accepts arguments: { from: string, to: string }."; + async execute(args: any): Promise { + const from = args?.from; + const to = args?.to; + if (!from || !to) return { message: "Please provide old and new hub names." }; + const r = await hubs.rename(from, to); + return { message: r.ok ? `Renamed bookmark folder "${from}" → "${to}".` : `Could not rename "${from}". ${r.msg || ""}` }; + } +} + +export class AddTabToHubCommand implements Command { + commandName = "add_tab_to_hub"; + description = "Add the current tab to a bookmark folder hub. Accepts arguments: { name: string }."; + async execute(args: any): Promise { + const name = args?.name; + if (!name) return { message: "Which hub should I add this tab to?" }; + const r = await hubs.addCurrentTab(name); + return { message: r.ok ? `Added current tab to bookmark folder "${name}".` : "Failed to add tab." }; + } +} + +export class OpenHubCommand implements Command { + commandName = "open_hub"; + description = "Open all bookmarks from a hub folder in tabs or a new window. Accepts arguments: { name: string, where?: 'tabs'|'window' }."; + async execute(args: any): Promise { + const name = args?.name; + if (!name) return { message: "Which hub should I open?" }; + const where = args?.where || "tabs"; + const r = await hubs.openHub(name, where); + return { message: r.ok ? `Opened bookmark folder "${name}" in ${where}.` : `Failed to open "${name}".` }; + } +} + +export class SplitTabsCommand implements Command { + commandName = "split_tabs"; + description = "Split specified tabs into side-by-side windows. Accepts arguments: { indices: number[] }."; + async execute(args: any): Promise { + const { topWin, gBrowser } = getChrome(); + if (!gBrowser || !topWin) return { message: "Browser UI not available." }; + + const indices = args?.indices; + if (!indices || !Array.isArray(indices) || indices.length < 2) { + return { message: "Please provide at least 2 tab indices to split (e.g., { indices: [1, 2] })." }; + } + + // Validate all indices first + const tabs: any[] = []; + for (const idx of indices) { + const i = Math.max(1, Math.floor(idx)); + if (i > gBrowser.tabs.length) { + return { message: `No tab ${i}.` }; + } + tabs.push(gBrowser.tabs[i - 1]); + } + + // Get screen dimensions + const screen = topWin.screen; + const availWidth = screen.availWidth; + const availHeight = screen.availHeight; + const availLeft = screen.availLeft || 0; + const availTop = screen.availTop || 0; + + const numTabs = tabs.length; + const windows: any[] = []; + + // Create windows for each tab + for (let i = 0; i < numTabs; i++) { + const tab = tabs[i]; + const title = tab?.label || tab?.linkedBrowser?.currentURI?.spec || "(untitled)"; + + // Create new window + const newWin = topWin.OpenBrowserWindow(); + windows.push({ win: newWin, tab, title }); + + // Small delay to ensure window is created + await new Promise(r => setTimeout(r, 100)); + } + + // Give windows time to fully initialize + await new Promise(r => setTimeout(r, 300)); + + // Position and resize windows, then move tabs + for (let i = 0; i < numTabs; i++) { + const { win, tab, title } = windows[i]; + + // Horizontal layout (side-by-side, left to right) + const windowWidth = Math.floor(availWidth / numTabs); + const windowHeight = availHeight; + const xPos = availLeft + (windowWidth * i); + const yPos = availTop; + + win.resizeTo(windowWidth, windowHeight); + win.moveTo(xPos, yPos); + + // Close the sidebar if it's open (since session storage isn't implemented yet) + try { + const sidebar = win.document.getElementById("sidebar-box"); + if (sidebar && !sidebar.hidden) { + win.SidebarController?.hide(); + } + } catch (e) { + console.warn("Failed to close sidebar:", e); + } + + // Move the tab to the new window + win.gBrowser.adoptTab(tab, 0); + } + + const tabTitles = windows.map(w => w.title).join(", "); + return { message: `Split ${numTabs} tabs side-by-side: ${tabTitles}` }; + } +} + +export class SearchMemoryCommand implements Command { + commandName = "search_memory"; + description = "Search stored memory (bookmarks/hubs) for a query. Arguments: { query: string, hub?: string }."; + async execute(args: any): Promise { + const query = args?.query; + const hub = args?.hub; + if (!query) return { message: "Missing 'query' argument." }; + + const results = await localMemory.search(query, 5, hub ? { hub } : undefined); + + if (results.length === 0) { + return { message: `No matches found for "${query}"${hub ? ` in hub "${hub}"` : ""}.` }; + } + + const out = results.map((r, i) => { + const title = r.metadata?.title || "(no title)"; + const url = r.metadata?.url || ""; + // Show a snippet of the text + const snippet = r.text.length > 100 ? r.text.substring(0, 100) + "..." : r.text; + return `${i + 1}. ${title} (${url})\n "${snippet}"`; + }).join("\n\n"); + + return { message: `Found ${results.length} matches:\n${out}` }; + } +} diff --git a/browser/base/content/assistant/build/src/config/env.ts b/browser/base/content/assistant/build/src/config/env.ts new file mode 100644 index 0000000000000..3abd36c90b064 --- /dev/null +++ b/browser/base/content/assistant/build/src/config/env.ts @@ -0,0 +1,21 @@ +// Environment configuration for Supabase +export const ENV = { + // Supabase configuration - using build-time environment variables + SUPABASE_URL: process.env.SUPABASE_URL || 'https://wvclepquxxczgrukfqyr.supabase.co', + SUPABASE_ANON_KEY: process.env.SUPABASE_ANON_KEY || 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Ind2Y2xlcHF1eHhjemdydWtmcXlyIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTUwODU5OTksImV4cCI6MjA3MDY2MTk5OX0.T-hZ_8QxtVnOt0mtCY_Zch87SYEcsyQZwnvvFAtZiNY', + + // Application configuration + APP_VERSION: '1.0.0', + LOG_LEVEL: 'info', + + // Validate environment variables + validate(): void { + if (!this.SUPABASE_URL) { + throw new Error('SUPABASE_URL is required'); + } + if (!this.SUPABASE_ANON_KEY) { + throw new Error('SUPABASE_ANON_KEY is required'); + } + } +}; + diff --git a/browser/base/content/assistant/build/src/hubs.ts b/browser/base/content/assistant/build/src/hubs.ts new file mode 100644 index 0000000000000..b6b6788063623 --- /dev/null +++ b/browser/base/content/assistant/build/src/hubs.ts @@ -0,0 +1,489 @@ +// Persistent (per-profile) "hub" manager using Firefox Bookmarks. +// - A "hub" is a bookmark folder under "Oasis Hubs" root folder. +// - We badge open tabs whose host matches any bookmark in a hub. +// - Assistant commands call into this manager. + +import { localMemory } from "./services/localMemory"; + +type FxTab = any; + +function getChrome() { + const topWin = (window.top as any); + const gBrowser = topWin?.gBrowser; + const PlacesUtils = topWin?.PlacesUtils; + const PlacesTransactions = topWin?.PlacesTransactions; + const browser = topWin?.browser; + return { topWin, gBrowser, PlacesUtils, PlacesTransactions, browser }; +} + +type HubItem = { url: string; title?: string; host: string; id: string }; + +const ROOT_FOLDER_NAME = "Oasis Hubs"; + +// Get or create the root "Oasis Hubs" folder using Firefox Places API +async function getRootFolder(): Promise { + try { + const { PlacesUtils } = getChrome(); + if (!PlacesUtils) throw new Error("PlacesUtils not available"); + + // Search for existing "Oasis Hubs" folder that's under "Other Bookmarks" + const bookmarks = await PlacesUtils.bookmarks.search({ title: ROOT_FOLDER_NAME }); + const existing = bookmarks.find((b: any) => + b.type === PlacesUtils.bookmarks.TYPE_FOLDER && + b.parentGuid === PlacesUtils.bookmarks.unfiledGuid + ); + if (existing) { + console.log("Found existing Oasis Hubs folder:", existing.guid); + return existing.guid; + } + + // Create root folder under "Other Bookmarks" + const root = await PlacesUtils.bookmarks.insert({ + title: ROOT_FOLDER_NAME, + type: PlacesUtils.bookmarks.TYPE_FOLDER, + parentGuid: PlacesUtils.bookmarks.unfiledGuid, + }); + console.log("Created new Oasis Hubs folder:", root.guid); + return root.guid; + } catch (e) { + console.error("Failed to get/create root folder:", e); + throw e; + } +} + +function hostOf(u: string): string { + try { return new URL(u).host.toLowerCase(); } catch { return ""; } +} + +// Helper functions to wrap PlacesUtils API +async function getBookmarkChildren(guid: string): Promise { + const { PlacesUtils } = getChrome(); + if (!PlacesUtils) return []; + try { + // Fetch bookmarks using PlacesUtils.bookmarks.fetch + const parent = await PlacesUtils.bookmarks.fetch(guid); + if (!parent) return []; + + // Search for children + const children: any[] = []; + await PlacesUtils.bookmarks.fetch({ parentGuid: guid }, (bookmark: any) => { + children.push({ + guid: bookmark.guid, + title: bookmark.title, + type: bookmark.type, + uri: bookmark.url, + }); + }); + + return children; + } catch (e) { + console.error("Failed to get bookmark children:", e); + return []; + } +} + +async function createBookmark(details: { parentGuid: string; title: string; url?: string; type?: number }): Promise { + const { PlacesUtils } = getChrome(); + if (!PlacesUtils) throw new Error("PlacesUtils not available"); + return await PlacesUtils.bookmarks.insert({ + parentGuid: details.parentGuid, + title: details.title, + url: details.url, + type: details.type || (details.url ? PlacesUtils.bookmarks.TYPE_BOOKMARK : PlacesUtils.bookmarks.TYPE_FOLDER), + }); +} + +async function removeBookmark(guid: string): Promise { + const { PlacesUtils } = getChrome(); + if (!PlacesUtils) return; + await PlacesUtils.bookmarks.remove(guid); +} + +async function updateBookmark(guid: string, changes: { title?: string }): Promise { + const { PlacesUtils } = getChrome(); + if (!PlacesUtils) throw new Error("PlacesUtils not available"); + return await PlacesUtils.bookmarks.update(guid, changes); +} + +export type CreateHubOpts = { include?: "none" | "current" | "all" }; +export type DeleteHubOpts = { closeTabs?: boolean }; + +class HubManager { + private wired = false; + private rootFolderId: string | null = null; + + private async ensureRootFolder(): Promise { + if (this.rootFolderId) return this.rootFolderId; + this.rootFolderId = await getRootFolder(); + return this.rootFolderId; + } + + async list(): Promise> { + try { + const rootId = await this.ensureRootFolder(); + console.log("Listing hubs under root folder:", rootId); + + const children = await getBookmarkChildren(rootId); + console.log("Found children:", children.length, children.map((c: any) => ({ title: c.title, type: c.type, guid: c.guid }))); + + const { PlacesUtils } = getChrome(); + const folders = children.filter((c: any) => c.type === PlacesUtils?.bookmarks.TYPE_FOLDER); + console.log("Filtered folders:", folders.length, folders.map((f: any) => f.title)); + + const result = []; + for (const folder of folders) { + const items = await getBookmarkChildren(folder.guid); + result.push({ name: folder.title || "Untitled", count: items.length }); + } + return result; + } catch (e) { + console.error("Failed to list hubs:", e); + return []; + } + } + + async getAll(): Promise> { + try { + const rootId = await this.ensureRootFolder(); + const children = await getBookmarkChildren(rootId); + const { PlacesUtils } = getChrome(); + const folders = children.filter((c: any) => c.type === PlacesUtils?.bookmarks.TYPE_FOLDER); + + const result = []; + for (const folder of folders) { + const bookmarks = await getBookmarkChildren(folder.guid); + const items: HubItem[] = bookmarks + .filter((b: any) => b.uri) + .map((b: any) => ({ + id: b.guid, + url: b.uri, + title: b.title, + host: hostOf(b.uri), + })); + result.push({ name: folder.title || "Untitled", items }); + } + return result; + } catch (e) { + console.error("Failed to get all hubs:", e); + return []; + } + } + + async create(name: string, opts?: CreateHubOpts) { + try { + name = (name || "").trim() || this.suggestName(); + const rootId = await this.ensureRootFolder(); + + // Create the hub folder + const folder = await createBookmark({ + parentGuid: rootId, + title: name, + }); + + const include = opts?.include || "none"; + const { gBrowser } = getChrome(); + let count = 0; + + if (gBrowser) { + if (include === "current") { + const tab = gBrowser.selectedTab; + await this.addTabToFolder(folder.guid, tab); + count = 1; + } else if (include === "all") { + for (const t of Array.from(gBrowser.tabs)) { + await this.addTabToFolder(folder.guid, t as any); + } + const items = await getBookmarkChildren(folder.guid); + count = items.length; + } + } + + this.updateAllTabMarkers(); + return { name, count }; + } catch (e) { + console.error("Failed to create hub:", e); + throw e; + } + } + + async delete(name: string, opts?: DeleteHubOpts) { + try { + name = (name || "").trim(); + const rootId = await this.ensureRootFolder(); + const children = await getBookmarkChildren(rootId); + const { PlacesUtils } = getChrome(); + const folder = children.find((c: any) => c.type === PlacesUtils?.bookmarks.TYPE_FOLDER && c.title === name); + + if (!folder) { + return { name, removed: 0 }; + } + + const items = await getBookmarkChildren(folder.guid); + const bookmarks = items.filter((b: any) => b.uri); + + if (opts?.closeTabs) { + const { gBrowser } = getChrome(); + if (gBrowser) { + const hostSet = new Set(bookmarks.map((b: any) => hostOf(b.uri))); + for (const t of Array.from(gBrowser.tabs) as any[]) { + const u = t?.linkedBrowser?.currentURI?.spec || ""; + if (hostSet.has(hostOf(u))) { + try { gBrowser.removeTab(t); } catch {} + } + } + } + } + + // Delete the entire folder + await removeBookmark(folder.guid); + this.updateAllTabMarkers(); + return { name, removed: bookmarks.length }; + } catch (e) { + console.error("Failed to delete hub:", e); + return { name, removed: 0 }; + } + } + + async rename(oldName: string, newName: string) { + try { + oldName = (oldName || "").trim(); + newName = (newName || "").trim(); + if (!oldName || !newName) return { ok: false }; + + const rootId = await this.ensureRootFolder(); + const children = await getBookmarkChildren(rootId); + const { PlacesUtils } = getChrome(); + const folder = children.find((c: any) => c.type === PlacesUtils?.bookmarks.TYPE_FOLDER && c.title === oldName); + + if (!folder) return { ok: false }; + + // Check if target name already exists + const existing = children.find((c: any) => c.type === PlacesUtils?.bookmarks.TYPE_FOLDER && c.title === newName); + if (existing) return { ok: false, msg: "Target exists" }; + + await updateBookmark(folder.guid, { title: newName }); + this.updateAllTabMarkers(); + return { ok: true }; + } catch (e) { + console.error("Failed to rename hub:", e); + return { ok: false }; + } + } + + async addCurrentTab(name: string) { + try { + const { gBrowser, PlacesUtils } = getChrome(); + if (!gBrowser) return { ok: false, msg: "Browser UI unavailable" }; + + const rootId = await this.ensureRootFolder(); + const children = await getBookmarkChildren(rootId); + // Case-insensitive match for hub folder + const folder = children.find((c: any) => + c.type === PlacesUtils?.bookmarks.TYPE_FOLDER && + (c.title || "").toLowerCase() === name.toLowerCase() + ); + + if (!folder) return { ok: false, msg: "Hub not found" }; + + // Pass the actual folder title (correct case) as the hub name + await this.addTabToFolder(folder.guid, gBrowser.selectedTab, folder.title); + this.updateAllTabMarkers(); + return { ok: true }; + } catch (e) { + console.error("Failed to add tab to hub:", e); + return { ok: false }; + } + } + + async removeUrl(name: string, url: string) { + try { + name = (name || "").trim(); + const rootId = await this.ensureRootFolder(); + const children = await getBookmarkChildren(rootId); + const { PlacesUtils } = getChrome(); + const folder = children.find((c: any) => c.type === PlacesUtils?.bookmarks.TYPE_FOLDER && c.title === name); + + if (!folder) return { ok: false }; + + const bookmarks = await getBookmarkChildren(folder.guid); + const toRemove = bookmarks.filter((b: any) => b.uri === url); + + for (const bookmark of toRemove) { + await removeBookmark(bookmark.guid); + } + + this.updateAllTabMarkers(); + return { ok: toRemove.length > 0 }; + } catch (e) { + console.error("Failed to remove URL from hub:", e); + return { ok: false }; + } + } + + async openHub(name: string, where: "tabs" | "window" = "tabs") { + try { + name = (name || "").trim(); + const rootId = await this.ensureRootFolder(); + const children = await getBookmarkChildren(rootId); + const { PlacesUtils, topWin, gBrowser, browser } = getChrome(); + const folder = children.find((c: any) => c.type === PlacesUtils?.bookmarks.TYPE_FOLDER && c.title === name); + + if (!folder) return { ok: false }; + + const bookmarks = await getBookmarkChildren(folder.guid); + const items = bookmarks.filter((b: any) => b.uri); + const urls = items.map((it: any) => it.uri); + + if (urls.length === 0) return { ok: true }; + + let targetBrowser = gBrowser; + if (where === "window") { + const w = topWin.OpenBrowserWindow(); + // A bit of a wait for the new window to be ready + await new Promise(resolve => setTimeout(resolve, 250)); + targetBrowser = w.gBrowser; + } + + if (!targetBrowser) return { ok: false }; + + const openedTabs: FxTab[] = []; + for (const url of urls) { + const tab = await targetBrowser.addTab(url, { triggerPrimaryAction: false }); + openedTabs.push(tab); + } + + // Focus the first tab of the new group + if (openedTabs.length > 0) { + targetBrowser.selectedTab = openedTabs[0]; + } + + // We need tab IDs for the grouping API, but gBrowser tabs are not WebExtension tabs. + // So we'll find the corresponding WebExtension tabs by URL. This is hacky. + // A better implementation would be to have this logic in a background script. + if (browser?.tabs && openedTabs.length > 0) { + setTimeout(async () => { + try { + const allTabs = await browser.tabs.query({}); + const tabIdsToGroup = []; + for (const openedTab of openedTabs) { + const url = openedTab.linkedBrowser.currentURI.spec; + const foundTab = allTabs.find((t: any) => t.url === url && !t.discarded); + if (foundTab) tabIdsToGroup.push(foundTab.id); + } + + if (tabIdsToGroup.length > 0) { + const groupId = await browser.tabs.group({ tabIds: tabIdsToGroup }); + await browser.tabGroups.update(groupId, { title: name }); + } + } catch (e) { + console.error("Failed to group tabs", e); + } + }, 500); // Wait a bit for tabs to be registered in the WebExtension API + } + + return { ok: true }; + } catch (e) { + console.error("Failed to open hub:", e); + return { ok: false }; + } + } + + // ---- badges on tabs (first matched hub name; count if >1 hubs match) ---- + wireTabObservers() { + if (this.wired) return; + const { gBrowser } = getChrome(); + if (!gBrowser) return; + const tb = gBrowser.tabContainer; + const upd = () => this.updateAllTabMarkers(); + tb.addEventListener("TabOpen", upd); + tb.addEventListener("TabAttrModified", upd); + tb.addEventListener("TabSelect", upd); + gBrowser.addTabsProgressListener({ + onLocationChange: (_b: any) => this.updateAllTabMarkers(), + }); + this.wired = true; + } + + updateAllTabMarkers() { + const { gBrowser } = getChrome(); + if (!gBrowser) return; + for (const t of Array.from(gBrowser.tabs)) this.updateMarkerForTab(t); + } + + private async updateMarkerForTab(tab: FxTab) { + try { + const u = tab?.linkedBrowser?.currentURI?.spec || ""; + const h = hostOf(u); + if (!h) { + tab.removeAttribute("oasis-hub"); + tab.removeAttribute("oasis-hub-count"); + return; + } + + const all = await this.getAll(); + const names: string[] = []; + for (const hub of all) { + if (hub.items.some((it: HubItem) => it.host === h)) names.push(hub.name); + } + + if (names.length) { + tab.setAttribute("oasis-hub", names[0]); + tab.setAttribute("oasis-hub-count", String(names.length)); + } else { + tab.removeAttribute("oasis-hub"); + tab.removeAttribute("oasis-hub-count"); + } + } catch {} + } + + private async addTabToFolder(folderGuid: string, tab: FxTab, hubName?: string) { + const url = tab?.linkedBrowser?.currentURI?.spec || ""; + if (!url) return; + + const title = + tab?.label || tab?.linkedBrowser?.contentTitle || tab?.linkedBrowser?.currentURI?.spec || ""; + + // Check if URL already exists in this folder + const existing = await getBookmarkChildren(folderGuid); + const alreadyExists = existing.some((b: any) => b.uri === url); + if (alreadyExists) return; + + await createBookmark({ + parentGuid: folderGuid, + title, + url, + }); + + // Index in local memory + try { + // Best-effort content extraction + let content = ""; + try { + // Note: This only works if the tab is in the same process or via CPOW (not recommended but might work for now) + // For full Fission support, we'd need a JSWindowActor. + const doc = tab.linkedBrowser?.contentDocument; + if (doc && doc.body) { + content = doc.body.innerText.substring(0, 5000); // Limit to 5k chars + } + } catch (e) { + console.warn("Failed to extract tab content:", e); + } + + const text = `Title: ${title}\nURL: ${url}\nContent: ${content}`; + await localMemory.addDocument(text, { title, type: "hub_item", hub: folderGuid, hubName, description: content.substring(0, 200) }, url); + } catch (e) { + console.error("Failed to index hub item:", e); + } + } + + private suggestName(): string { + const base = "Hub"; + let i = 1; + // Note: This is a simple implementation. For better UX, we'd check existing hub names. + return `${base} ${i}`; + } +} + +export const hubs = new HubManager(); +// Make sure observers are live +hubs.wireTabObservers(); \ No newline at end of file diff --git a/browser/base/content/assistant/build/src/proxyClient.ts b/browser/base/content/assistant/build/src/proxyClient.ts new file mode 100644 index 0000000000000..c379637240027 --- /dev/null +++ b/browser/base/content/assistant/build/src/proxyClient.ts @@ -0,0 +1,55 @@ +import { postSigned } from "./awsSignedFetch"; +import SupabaseAuth from "./services/supabase"; + +export type WireMsg = { role: "user" | "model"; content: string }; + +const supabaseAuth = SupabaseAuth.getInstance(); + +async function checkAuthentication(): Promise { + const isAuthenticated = await supabaseAuth.isAuthenticated(); + if (!isAuthenticated) { + throw new Error("Authentication required: Please sign in to use the AI assistant"); + } + return true; +} + +export async function routeRemote(system: string, messages: WireMsg[], options: string[]) { + await checkAuthentication(); + return postSigned("route", { system, messages, options }); +} + +export async function chatRemote(system: string, messages: WireMsg[]) { + await checkAuthentication(); + return postSigned("chat", { system, messages }); +} + +export async function transcribeAudio(audioBlob: Blob): Promise<{ transcript: string }> { + await checkAuthentication(); + + // Convert blob to base64 + const arrayBuffer = await audioBlob.arrayBuffer(); + const base64Audio = btoa( + new Uint8Array(arrayBuffer).reduce((data, byte) => data + String.fromCharCode(byte), '') + ); + + // Call lambda with op: "transcribe" + const result = await postSigned("transcribe", { audio: base64Audio, mimeType: audioBlob.type }); + + // Backend returns { transcript: "..." } + return result; +} + +export async function textToSpeech(text: string): Promise { + await checkAuthentication(); + + const result = await postSigned("tts", { text }); + + // The lambda should return base64 encoded audio + const audioData = atob(result.audio); + const arrayBuffer = new Uint8Array(audioData.length); + for (let i = 0; i < audioData.length; i++) { + arrayBuffer[i] = audioData.charCodeAt(i); + } + + return new Blob([arrayBuffer], { type: result.mimeType || 'audio/mpeg' }); +} diff --git a/browser/base/content/assistant/build/src/services/localMemory.ts b/browser/base/content/assistant/build/src/services/localMemory.ts new file mode 100644 index 0000000000000..6d810b5f64546 --- /dev/null +++ b/browser/base/content/assistant/build/src/services/localMemory.ts @@ -0,0 +1,164 @@ +import { openDB, DBSchema, IDBPDatabase } from "idb"; +import MiniSearch from "minisearch"; + +// Full-text search using MiniSearch +// Provides better fuzzy matching and prefix search than Fuse.js for documents. + +interface MemoryDoc { + id?: number; + text: string; + tokens: string[]; // Kept for compatibility + metadata: any; + timestamp: number; + url?: string; +} + +interface MemoryDB extends DBSchema { + documents: { + key: number; + value: MemoryDoc; + indexes: { "by-timestamp": number; "by-url": string }; + }; +} + +class LocalMemoryService { + private dbPromise: Promise>; + private miniSearch: MiniSearch; + private isIndexDirty: boolean = true; + + constructor() { + this.dbPromise = openDB("oasis-memory", 1, { + upgrade(db) { + const store = db.createObjectStore("documents", { + keyPath: "id", + autoIncrement: true, + }); + store.createIndex("by-timestamp", "timestamp"); + store.createIndex("by-url", "url", { unique: false }); + }, + }); + + this.miniSearch = new MiniSearch({ + fields: ["text", "title", "description"], // fields to index for full-text search + storeFields: ["text", "metadata", "url", "timestamp"], // fields to return with results + extractField: (doc, fieldName) => { + if (fieldName === "title") return doc.metadata?.title; + if (fieldName === "description") return doc.metadata?.description; + return doc[fieldName]; + }, + tokenize: (text) => this.tokenize(text), // Use consistent tokenizer + searchOptions: { + boost: { title: 2 }, + fuzzy: 0.2, + prefix: true, + tokenize: (text) => this.tokenize(text) // Use consistent tokenizer for queries too + } + }); + + // Initialize index immediately + this.ensureIndex().catch(console.error); + } + + // Simple tokenizer: lowercase, replace punctuation with spaces, split by whitespace + private tokenize(text: string): string[] { + return text + .toLowerCase() + .replace(/[^\w\s]/g, " ") // Replace punctuation with space to preserve words + .split(/\s+/) + .filter((t) => t.length > 2); // Ignore tiny words + } + + private async ensureIndex() { + if (!this.isIndexDirty) return; + + const db = await this.dbPromise; + const docs = await db.getAll("documents"); + + this.miniSearch.removeAll(); + if (docs.length > 0) { + this.miniSearch.addAll(docs.map(d => ({ + id: d.id!, + text: d.text, + metadata: d.metadata, + url: d.url, + timestamp: d.timestamp + }))); + } + + this.isIndexDirty = false; + console.log(`[LocalMemory] Index rebuilt with ${docs.length} documents`); + } + + async addDocument(text: string, metadata: any = {}, url?: string) { + // Deduplicate by URL + if (url) { + await this.removeDocumentByUrl(url); + } + + const tokens = this.tokenize(text); + + const doc: MemoryDoc = { + text, + tokens, + metadata, + timestamp: Date.now(), + url + }; + const db = await this.dbPromise; + await db.add("documents", doc); + this.isIndexDirty = true; + console.log(`Added document to memory: "${text.substring(0, 20)}..."`); + } + + async removeDocumentByUrl(url: string) { + const db = await this.dbPromise; + const tx = db.transaction("documents", "readwrite"); + const index = tx.store.index("by-url"); + let cursor = await index.openCursor(url); + + while (cursor) { + await cursor.delete(); + cursor = await cursor.continue(); + } + await tx.done; + this.isIndexDirty = true; + console.log(`Removed documents for URL: ${url}`); + } + + async search(query: string, limit = 5, filter?: { hub?: string }): Promise<{ text: string; score: number; metadata: any }[]> { + await this.ensureIndex(); + + const results = this.miniSearch.search(query, { + filter: (result) => { + if (filter?.hub) { + // Case-insensitive hub matching + return (result.metadata?.hubName || "").toLowerCase() === filter.hub.toLowerCase(); + } + return true; + } + }); + + // Deduplicate results by URL + const seenUrls = new Set(); + const uniqueResults = []; + + for (const r of results) { + const url = r.url || r.metadata?.url; + if (url) { + if (seenUrls.has(url)) continue; + seenUrls.add(url); + } + uniqueResults.push(r); + if (uniqueResults.length >= limit) break; + } + + return uniqueResults.map((r) => ({ + text: r.text, + score: r.score, + metadata: r.metadata, + })); + } +} + +export const localMemory = new LocalMemoryService(); + diff --git a/browser/base/content/assistant/build/src/services/supabase.ts b/browser/base/content/assistant/build/src/services/supabase.ts new file mode 100644 index 0000000000000..9f795490f166f --- /dev/null +++ b/browser/base/content/assistant/build/src/services/supabase.ts @@ -0,0 +1,438 @@ +// Supabase Authentication Service for Browser Assistant +import { createClient, SupabaseClient, User, Session, AuthError } from '@supabase/supabase-js'; +import { ENV } from '../config/env'; +import { UserProfile, UserSession, AuthState } from '../types/auth'; + +export default class SupabaseAuth { + private static instance: SupabaseAuth; + private supabase: SupabaseClient; + private currentSession: UserSession | null = null; + private authStateCallbacks: Array<(state: AuthState) => void> = []; + + private constructor() { + // Initialize Supabase client + this.supabase = createClient(ENV.SUPABASE_URL, ENV.SUPABASE_ANON_KEY); + + // Set up auth state change listener + this.supabase.auth.onAuthStateChange((event, session) => { + console.log('Auth state changed:', event); + this.handleAuthStateChange(event, session); + }); + } + + public static getInstance(): SupabaseAuth { + if (!SupabaseAuth.instance) { + SupabaseAuth.instance = new SupabaseAuth(); + } + return SupabaseAuth.instance; + } + + // Google OAuth Authentication + public async signInWithGoogle(): Promise<{ user: User | null; error: AuthError | null }> { + try { + console.log('Attempting Google sign in with manual URL approach'); + + // Check if user is already authenticated + const currentUser = await this.getCurrentUser(); + if (currentUser) { + console.log('User already authenticated:', currentUser.id); + return { user: currentUser, error: null }; + } + + // Generate OAuth URL with Supabase + const { data, error } = await this.supabase.auth.signInWithOAuth({ + provider: 'google', + options: { + skipBrowserRedirect: true, + // Use Kahana's official domain for OAuth callback + redirectTo: 'https://kahana.co/oauth-callback', + // Request consent prompt and offline access for refresh token + queryParams: { + prompt: 'select_account', + access_type: 'offline', + include_granted_scopes: 'true', + response_type: 'code' + } + } + }); + + if (error || !data.url) { + console.error('Failed to generate OAuth URL:', error); + return { user: null, error: error || { message: 'Failed to generate OAuth URL', status: 500 } as AuthError }; + } + + console.log('Generated OAuth URL:', data.url); + + // Since window.open() is blocked from chrome://, we'll show a modal with the URL + // and let the user manually open it in a new tab + return { + user: null, + error: new Error(`GOOGLE_OAUTH_URL:${data.url}`) as AuthError + }; + + } catch (error) { + console.error('Google sign in error:', error); + return { user: null, error: error as AuthError }; + } + } + + // Email/Password Authentication + public async signInWithEmail(email: string, password: string): Promise<{ user: User | null; error: AuthError | null }> { + try { + console.log('Attempting email sign in for:', email); + + const { data, error } = await this.supabase.auth.signInWithPassword({ + email, + password + }); + + if (error) { + console.error('Email sign in error:', error.message); + return { user: null, error }; + } + + if (data.user) { + await this.updateLastLogin(data.user.id); + await this.createSession(data.user.id); + console.log('Email sign in successful for user:', data.user.id); + } + + return { user: data.user, error: null }; + } catch (error) { + console.error('Sign in error:', error); + return { user: null, error: error as AuthError }; + } + } + + public async signUp(email: string, password: string, name?: string): Promise<{ user: User | null; error: AuthError | null }> { + try { + console.log('Attempting sign up for:', email); + + const { data, error } = await this.supabase.auth.signUp({ + email, + password, + options: { + data: { + name: name || email.split('@')[0] + } + } + }); + + if (error) { + console.error('Sign up error:', error.message); + return { user: null, error }; + } + + if (data.user) { + // Create user profile in our custom users table + await this.createUserProfile(data.user, name); + console.log('Sign up successful for user:', data.user.id); + } + + return { user: data.user, error: null }; + } catch (error) { + console.error('Sign up error:', error); + return { user: null, error: error as AuthError }; + } + } + + public async signOut(): Promise<{ error: AuthError | null }> { + try { + console.log('Attempting sign out'); + + // End current session if exists + if (this.currentSession) { + await this.endSession(this.currentSession.session_id); + } + + const { error } = await this.supabase.auth.signOut(); + + if (error) { + console.error('Sign out error:', error.message); + return { error }; + } + + this.currentSession = null; + console.log('Sign out successful'); + return { error: null }; + } catch (error) { + console.error('Sign out error:', error); + return { error: error as AuthError }; + } + } + + // Session Management + public async getCurrentUser(): Promise { + const { data: { user } } = await this.supabase.auth.getUser(); + return user; + } + + public async getSession(): Promise { + const { data: { session } } = await this.supabase.auth.getSession(); + return session; + } + + public async isAuthenticated(): Promise { + const user = await this.getCurrentUser(); + return user !== null; + } + + /** + * Handle OAuth callback data (similar to Electron's handleOAuthRedirectCallback) + * Processes auth data from manual input and exchanges it for a session + */ + public async handleOAuthCallbackData(authData: any): Promise<{ success: boolean; error?: string }> { + try { + console.log('Handling OAuth callback data:', authData); + + // Handle auth code exchange (preferred method) + if (authData.code) { + console.log('Exchanging auth code for session...'); + const { data, error } = await this.supabase.auth.exchangeCodeForSession(authData.code); + if (error) { + console.error('Failed to exchange code for session:', error.message); + return { success: false, error: error.message }; + } else { + console.log('Exchanged code for session for user:', data.user?.id); + + // Ensure user profile exists + if (data.user) { + const existingProfile = await this.getUserProfile(); + if (!existingProfile) { + await this.createUserProfile(data.user, data.user.user_metadata?.name); + console.log('Created user profile from OAuth callback'); + } + + // Update last login and create session + await this.updateLastLogin(data.user.id); + await this.createSession(data.user.id); + } + + return { success: true }; + } + } + + // Handle direct token setting (fallback) + if (authData.access_token && authData.refresh_token) { + console.log('Setting session from tokens...'); + const { data, error } = await this.supabase.auth.setSession({ + access_token: authData.access_token, + refresh_token: authData.refresh_token + }); + if (error) { + console.error('Failed to set session from tokens:', error.message); + return { success: false, error: error.message }; + } else { + console.log('Set session from tokens for user:', data.user?.id); + + // Ensure user profile exists + if (data.user) { + const existingProfile = await this.getUserProfile(); + if (!existingProfile) { + await this.createUserProfile(data.user, data.user.user_metadata?.name); + console.log('Created user profile from tokens'); + } + + // Update last login and create session + await this.updateLastLogin(data.user.id); + await this.createSession(data.user.id); + } + + return { success: true }; + } + } + + console.warn('No valid OAuth data found'); + return { success: false, error: 'No valid OAuth data' }; + + } catch (error) { + console.error('Error handling OAuth callback data:', error); + return { success: false, error: error instanceof Error ? error.message : 'Unknown error' }; + } + } + + // User Profile Management + public async getUserProfile(): Promise { + try { + const user = await this.getCurrentUser(); + if (!user) return null; + + const { data, error } = await this.supabase + .from('users') + .select('*') + .eq('user_id', user.id) + .single(); + + if (error) { + console.error('Error fetching user profile:', error.message); + return null; + } + + return data as UserProfile; + } catch (error) { + console.error('Error fetching user profile:', error); + return null; + } + } + + // Auth State Management + public onAuthStateChange(callback: (state: AuthState) => void): void { + this.authStateCallbacks.push(callback); + } + + private async handleAuthStateChange(event: string, session: Session | null): Promise { + const user = session?.user || null; + const authState: AuthState = { + user, + session, + isAuthenticated: user !== null + }; + + // Notify all callbacks + this.authStateCallbacks.forEach(callback => { + try { + callback(authState); + } catch (error) { + console.error('Error in auth state callback:', error); + } + }); + + // Handle session creation/destruction + if (event === 'SIGNED_IN' && user) { + await this.createSession(user.id); + } else if (event === 'SIGNED_OUT' && this.currentSession) { + await this.endSession(this.currentSession.session_id); + this.currentSession = null; + } + } + + // Database Operations + private async createUserProfile(user: User, name?: string): Promise { + try { + const { error } = await this.supabase + .from('users') + .insert({ + user_id: user.id, + email: user.email!, + name: name || user.user_metadata?.name || user.email!.split('@')[0], + password_hash: '', // Supabase handles this + status: 'active' + }); + + if (error) { + console.error('Error creating user profile:', error.message); + } else { + console.log('User profile created successfully'); + } + } catch (error) { + console.error('Error creating user profile:', error); + } + } + + private async updateLastLogin(userId: string): Promise { + try { + const { error } = await this.supabase + .from('users') + .update({ last_login: new Date().toISOString() }) + .eq('user_id', userId); + + if (error) { + console.error('Error updating last login:', error.message); + } + } catch (error) { + console.error('Error updating last login:', error); + } + } + + private async createSession(userId: string): Promise { + try { + const deviceInfo = { + platform: 'browser', + version: ENV.APP_VERSION, + userAgent: window.navigator.userAgent + }; + + const { data, error } = await this.supabase + .from('sessions') + .insert({ + user_id: userId, + device_info: deviceInfo + }) + .select() + .single(); + + if (error) { + // Ignore RLS errors as they might happen if the user is not fully synced yet + if (error.message.includes('row-level security policy')) { + console.warn('Session tracking skipped due to RLS policy (non-critical):', error.message); + } else { + console.error('Error creating session:', error.message); + } + } else if (data) { + this.currentSession = data as UserSession; + console.log('Session created:', data.session_id); + } + } catch (error) { + console.error('Error creating session:', error); + } + } + + private async endSession(sessionId: string): Promise { + try { + const { error } = await this.supabase + .from('sessions') + .update({ ended_at: new Date().toISOString() }) + .eq('session_id', sessionId); + + if (error) { + console.error('Error ending session:', error.message); + } else { + console.log('Session ended:', sessionId); + } + } catch (error) { + console.error('Error ending session:', error); + } + } + + // Utility Methods + public handleAuthError(error: AuthError): string { + // Handle special OAuth URL case + if (error.message && error.message.startsWith('GOOGLE_OAUTH_URL:')) { + return error.message; // Return the full message with URL + } + + switch (error.message) { + case 'Invalid login credentials': + return 'Invalid email or password. Please try again.'; + case 'Email not confirmed': + return 'Please check your email and click the confirmation link.'; + case 'User already registered': + return 'An account with this email already exists.'; + case 'Password should be at least 6 characters': + return 'Password must be at least 6 characters long.'; + case 'Unable to validate email address: invalid format': + return 'Please enter a valid email address.'; + case 'OAuth provider not found': + return 'Google sign-in is not configured. Please contact support.'; + case 'OAuth account not linked': + return 'This Google account is not linked to an existing account.'; + case 'Google sign-in is blocked by browser security. Please use email/password authentication instead.': + return 'Google sign-in is blocked by browser security. Please use email/password authentication instead.'; + case 'Popup blocked. Please allow popups for this site and try again.': + return 'Popup blocked. Please allow popups for this site and try again.'; + case 'Google sign-in was cancelled or failed. Please try again.': + return 'Google sign-in was cancelled or failed. Please try again.'; + case 'Google sign-in timed out. Please try again.': + return 'Google sign-in timed out. Please try again.'; + case 'Failed to generate OAuth URL': + return 'Failed to generate OAuth URL. Please try again.'; + case 'Failed to open OAuth URL. Please allow popups and try again.': + return 'Failed to open OAuth URL. Please allow popups and try again.'; + default: + return error.message || 'An unexpected error occurred. Please try again.'; + } + } +} + +// Export singleton instance +export const supabaseAuth = SupabaseAuth.getInstance(); diff --git a/browser/base/content/assistant/build/src/services/voiceInput.ts b/browser/base/content/assistant/build/src/services/voiceInput.ts new file mode 100644 index 0000000000000..c8a237d53aef8 --- /dev/null +++ b/browser/base/content/assistant/build/src/services/voiceInput.ts @@ -0,0 +1,103 @@ +import { transcribeAudio } from "../proxyClient"; + +export class VoiceInputService { + private mediaRecorder: MediaRecorder | null = null; + private audioChunks: Blob[] = []; + private stream: MediaStream | null = null; + + async startRecording(): Promise { + try { + // Request microphone access + this.stream = await navigator.mediaDevices.getUserMedia({ audio: true }); + + // Create MediaRecorder with appropriate MIME type + const mimeType = this.getSupportedMimeType(); + this.mediaRecorder = new MediaRecorder(this.stream, { mimeType }); + + this.audioChunks = []; + + this.mediaRecorder.ondataavailable = (event) => { + if (event.data.size > 0) { + this.audioChunks.push(event.data); + } + }; + + this.mediaRecorder.start(); + } catch (error) { + console.error("Error starting recording:", error); + throw new Error("Failed to access microphone. Please check permissions."); + } + } + + async stopRecording(): Promise { + return new Promise((resolve, reject) => { + if (!this.mediaRecorder) { + reject(new Error("No active recording")); + return; + } + + this.mediaRecorder.onstop = async () => { + try { + // Stop all tracks in the stream + if (this.stream) { + this.stream.getTracks().forEach(track => track.stop()); + } + + // Create audio blob from chunks + const mimeType = this.mediaRecorder?.mimeType || 'audio/webm'; + const audioBlob = new Blob(this.audioChunks, { type: mimeType }); + + // Send to Deepgram via lambda + const result = await transcribeAudio(audioBlob); + + // Lambda returns { transcript: "..." } + resolve(result.transcript || ''); + } catch (error) { + console.error("Error transcribing audio:", error); + reject(error); + } finally { + this.mediaRecorder = null; + this.audioChunks = []; + this.stream = null; + } + }; + + this.mediaRecorder.stop(); + }); + } + + isRecording(): boolean { + return this.mediaRecorder?.state === "recording"; + } + + cancelRecording(): void { + if (this.mediaRecorder && this.mediaRecorder.state !== "inactive") { + this.mediaRecorder.stop(); + } + if (this.stream) { + this.stream.getTracks().forEach(track => track.stop()); + } + this.mediaRecorder = null; + this.audioChunks = []; + this.stream = null; + } + + private getSupportedMimeType(): string { + const types = [ + 'audio/webm;codecs=opus', + 'audio/webm', + 'audio/ogg;codecs=opus', + 'audio/mp4', + ]; + + for (const type of types) { + if (MediaRecorder.isTypeSupported(type)) { + return type; + } + } + + return ''; // Let browser choose default + } +} + +export default new VoiceInputService(); diff --git a/browser/base/content/assistant/build/src/types/auth.ts b/browser/base/content/assistant/build/src/types/auth.ts new file mode 100644 index 0000000000000..57cfb7bac65a2 --- /dev/null +++ b/browser/base/content/assistant/build/src/types/auth.ts @@ -0,0 +1,30 @@ +// TypeScript interfaces for authentication +import { User, Session, AuthError } from '@supabase/supabase-js'; + +export interface UserProfile { + user_id: string; + name?: string; + email: string; + created_at: string; + last_login?: string; + status: 'active' | 'suspended'; +} + +export interface UserSession { + session_id: string; + user_id: string; + started_at: string; + ended_at?: string; + device_info?: { + platform: string; + version: string; + userAgent?: string; + }; +} + +export interface AuthState { + user: User | null; + session: Session | null; + isAuthenticated: boolean; +} + diff --git a/browser/base/content/assistant/build/tsconfig.json b/browser/base/content/assistant/build/tsconfig.json new file mode 100644 index 0000000000000..d2c1b0913c32d --- /dev/null +++ b/browser/base/content/assistant/build/tsconfig.json @@ -0,0 +1,10 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "Bundler", + "strict": true, + "skipLibCheck": true + }, + "include": ["src/**/*.ts"] +} diff --git a/browser/base/content/assistant/images/empty-state-bg.png b/browser/base/content/assistant/images/empty-state-bg.png new file mode 100644 index 0000000000000..4527fdcf5e5ce Binary files /dev/null and b/browser/base/content/assistant/images/empty-state-bg.png differ diff --git a/browser/base/content/assistant/kahana-interceptor.html b/browser/base/content/assistant/kahana-interceptor.html new file mode 100644 index 0000000000000..d3338b79b830a --- /dev/null +++ b/browser/base/content/assistant/kahana-interceptor.html @@ -0,0 +1,149 @@ + + + + + + Oasis Browser - Authentication Handler + + + +
+
+
Processing authentication...
+
+
+ + + + diff --git a/browser/base/content/assistant/logos/logo.svg b/browser/base/content/assistant/logos/logo.svg new file mode 100644 index 0000000000000..a80b3ed9f7b09 --- /dev/null +++ b/browser/base/content/assistant/logos/logo.svg @@ -0,0 +1,3 @@ + + + diff --git a/browser/base/content/assistant/oauth-callback.html b/browser/base/content/assistant/oauth-callback.html new file mode 100644 index 0000000000000..ecd9ac6535d02 --- /dev/null +++ b/browser/base/content/assistant/oauth-callback.html @@ -0,0 +1,151 @@ + + + + + + Oasis Browser - Authentication + + + +
+
+
Processing authentication...
+
+
+ + + + diff --git a/browser/base/content/assistant/oauth-handler.html b/browser/base/content/assistant/oauth-handler.html new file mode 100644 index 0000000000000..07f62ead5c2f7 --- /dev/null +++ b/browser/base/content/assistant/oauth-handler.html @@ -0,0 +1,164 @@ + + + + + + Oasis Browser - OAuth Handler + + + +
+
+
Processing OAuth callback...
+
+
+
+ + + + diff --git a/browser/base/content/assistant/public-oauth-callback.html b/browser/base/content/assistant/public-oauth-callback.html new file mode 100644 index 0000000000000..f0e49d2f9dd5b --- /dev/null +++ b/browser/base/content/assistant/public-oauth-callback.html @@ -0,0 +1,162 @@ + + + + + + Oasis Browser - Authentication + + + +
+
+

Processing Authentication...

+

Please wait while we securely process your login.

+
+
+ + + + diff --git a/browser/base/content/browser-box.inc.xhtml b/browser/base/content/browser-box.inc.xhtml index 2faed30e09511..05973cc32e2bb 100644 --- a/browser/base/content/browser-box.inc.xhtml +++ b/browser/base/content/browser-box.inc.xhtml @@ -33,4 +33,22 @@ + + + diff --git a/browser/base/content/browser.js b/browser/base/content/browser.js index de69507d4f450..44e869e8925bc 100644 --- a/browser/base/content/browser.js +++ b/browser/base/content/browser.js @@ -771,6 +771,32 @@ var gNavigatorBundle = { }, }; +function toggleAssistantSidebar() { + const assistantSidebar = document.getElementById("assistant-sidebar"); + const browserElement = document.getElementById("browser"); + + if (!assistantSidebar || !browserElement) { + return; + } + + if (assistantSidebar.hidden) { + // It's closed, so open it + assistantSidebar.hidden = false; + browserElement.setAttribute("sidebar-open", "true"); + } else { + // It's open, so close it + assistantSidebar.hidden = true; + browserElement.removeAttribute("sidebar-open"); + } +} + +window.addEventListener("load", function() { + const assistantSidebarButton = document.getElementById("assistant-button"); + if (assistantSidebarButton) { + assistantSidebarButton.addEventListener("click", toggleAssistantSidebar); + } +}, { once: true }); + function updateFxaToolbarMenu(enable, isInitialUpdate = false) { // We only show the Firefox Account toolbar menu if the feature is enabled and // if sync is enabled. diff --git a/browser/base/content/browser.xhtml b/browser/base/content/browser.xhtml index 832d98f911e0b..8491aaa04b95d 100644 --- a/browser/base/content/browser.xhtml +++ b/browser/base/content/browser.xhtml @@ -102,6 +102,7 @@ + # All sets except for popupsets (commands, keys, and stringbundles) diff --git a/browser/base/content/default-bookmarks.html b/browser/base/content/default-bookmarks.html index 2f764caf6f473..9bac420bc6517 100644 --- a/browser/base/content/default-bookmarks.html +++ b/browser/base/content/default-bookmarks.html @@ -27,7 +27,7 @@

default-bookmarks-heading

-

+ diff --git a/browser/base/content/navigator-toolbox.inc.xhtml b/browser/base/content/navigator-toolbox.inc.xhtml index 68c24f730d56f..0735e90d8b031 100644 --- a/browser/base/content/navigator-toolbox.inc.xhtml +++ b/browser/base/content/navigator-toolbox.inc.xhtml @@ -143,6 +143,7 @@ command="Browser:ForwardOrForwardDuplicate" tooltip="forward-button-tooltip" context="backForwardMenu"/> + @@ -458,6 +459,15 @@ + + + + + diff --git a/browser/base/jar.mn b/browser/base/jar.mn index b1f7121a1f392..1ee4332697dc3 100644 --- a/browser/base/jar.mn +++ b/browser/base/jar.mn @@ -13,6 +13,11 @@ browser.jar: content/browser/aboutRobots.xhtml (content/aboutRobots.xhtml) content/browser/aboutRobots.js (content/aboutRobots.js) content/browser/aboutRobots.css (content/aboutRobots.css) + content/browser/assistant/assistant.bundle.js (content/assistant/assistant.bundle.js) + content/browser/assistant/assistant.ui.js (content/assistant/assistant.ui.js) + content/browser/assistant/assistant.xhtml (content/assistant/assistant.xhtml) + content/browser/assistant/auth-guard.js (content/assistant/auth-guard.js) + content/browser/assistant/bootstrap.js (content/assistant/bootstrap.js) content/browser/logos/etp-mobile.svg (content/logos/etp-mobile.svg) content/browser/logos/fxa-logo.svg (content/logos/fxa-logo.svg) content/browser/logos/ipprotection-error.svg (content/logos/ipprotection-error.svg) diff --git a/browser/branding/custom/Assets.car b/browser/branding/custom/Assets.car new file mode 100644 index 0000000000000..01e64e7c92a0c Binary files /dev/null and b/browser/branding/custom/Assets.car differ diff --git a/browser/branding/custom/PrivateBrowsing_150.png b/browser/branding/custom/PrivateBrowsing_150.png new file mode 100644 index 0000000000000..e95485e1371ed Binary files /dev/null and b/browser/branding/custom/PrivateBrowsing_150.png differ diff --git a/browser/branding/custom/PrivateBrowsing_70.png b/browser/branding/custom/PrivateBrowsing_70.png new file mode 100644 index 0000000000000..b6fb4a11de18c Binary files /dev/null and b/browser/branding/custom/PrivateBrowsing_70.png differ diff --git a/browser/branding/custom/VisualElements_150.png b/browser/branding/custom/VisualElements_150.png new file mode 100644 index 0000000000000..f764a48966cae Binary files /dev/null and b/browser/branding/custom/VisualElements_150.png differ diff --git a/browser/branding/custom/VisualElements_70.png b/browser/branding/custom/VisualElements_70.png new file mode 100644 index 0000000000000..197a645b4236e Binary files /dev/null and b/browser/branding/custom/VisualElements_70.png differ diff --git a/browser/branding/custom/background.png b/browser/branding/custom/background.png new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/browser/branding/custom/branding.nsi b/browser/branding/custom/branding.nsi new file mode 100644 index 0000000000000..94ffbaa98f12b --- /dev/null +++ b/browser/branding/custom/branding.nsi @@ -0,0 +1,76 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +# NSIS branding defines for official release builds. +# The nightly build branding.nsi is located in browser/installer/windows/nsis/ +# The unofficial build branding.nsi is located in browser/branding/unofficial/ + +# BrandFullNameInternal is used for some registry and file system values +# instead of BrandFullName and typically should not be modified. +!define BrandFullNameInternal "Mozilla Firefox" +!define BrandFullName "Mozilla Firefox" +!define CompanyName "Mozilla Corporation" +!define URLInfoAbout "https://www.mozilla.org" +!define URLUpdateInfo "https://www.mozilla.org/firefox/${AppVersion}/releasenotes" +!define HelpLink "https://support.mozilla.org" + +; The OFFICIAL define is a workaround to support different urls for Release and +; Beta since they share the same branding when building with other branches that +; set the update channel to beta. +!define OFFICIAL +!define URLStubDownloadX86 "https://download.mozilla.org/?os=win&lang=${AB_CD}&product=firefox-latest" +!define URLStubDownloadAMD64 "https://download.mozilla.org/?os=win64&lang=${AB_CD}&product=firefox-latest" +!define URLStubDownloadAArch64 "https://download.mozilla.org/?os=win64-aarch64&lang=${AB_CD}&product=firefox-latest" +!define URLManualDownload "https://www.mozilla.org/${AB_CD}/firefox/installer-help/?channel=release&installer_lang=${AB_CD}" +!define URLSystemRequirements "https://www.mozilla.org/firefox/system-requirements/" +!define Channel "release" + +# The installer's certificate name and issuer expected by the stub installer +!define CertNameDownload "Mozilla Corporation" +!define CertIssuerDownload "DigiCert Trusted G4 Code Signing RSA4096 SHA384 2021 CA1" + +# Dialog units are used so the UI displays correctly with the system's DPI +# settings. These are tweaked to look good with the en-US strings; ideally +# we would customize them for each locale but we don't really have a way to +# implement that and it would be a ton of work for the localizers. +!define PROFILE_CLEANUP_LABEL_TOP "50u" +!define PROFILE_CLEANUP_LABEL_LEFT "22u" +!define PROFILE_CLEANUP_LABEL_WIDTH "175u" +!define PROFILE_CLEANUP_LABEL_HEIGHT "100u" +!define PROFILE_CLEANUP_LABEL_ALIGN "left" +!define PROFILE_CLEANUP_CHECKBOX_LEFT "22u" +!define PROFILE_CLEANUP_CHECKBOX_WIDTH "175u" +!define PROFILE_CLEANUP_BUTTON_LEFT "22u" +!define INSTALL_HEADER_TOP "70u" +!define INSTALL_HEADER_LEFT "22u" +!define INSTALL_HEADER_WIDTH "180u" +!define INSTALL_HEADER_HEIGHT "100u" +!define INSTALL_BODY_LEFT "22u" +!define INSTALL_BODY_WIDTH "180u" +!define INSTALL_INSTALLING_TOP "115u" +!define INSTALL_INSTALLING_LEFT "270u" +!define INSTALL_INSTALLING_WIDTH "150u" +!define INSTALL_PROGRESS_BAR_TOP "100u" +!define INSTALL_PROGRESS_BAR_LEFT "270u" +!define INSTALL_PROGRESS_BAR_WIDTH "150u" +!define INSTALL_PROGRESS_BAR_HEIGHT "12u" + +!define PROFILE_CLEANUP_CHECKBOX_TOP_MARGIN "12u" +!define PROFILE_CLEANUP_BUTTON_TOP_MARGIN "12u" +!define PROFILE_CLEANUP_BUTTON_X_PADDING "80u" +!define PROFILE_CLEANUP_BUTTON_Y_PADDING "8u" +!define INSTALL_BODY_TOP_MARGIN "20u" + +# Font settings that can be customized for each channel +!define INSTALL_HEADER_FONT_SIZE 20 +!define INSTALL_HEADER_FONT_WEIGHT 600 +!define INSTALL_INSTALLING_FONT_SIZE 15 +!define INSTALL_INSTALLING_FONT_WEIGHT 600 + +# UI Colors that can be customized for each channel +!define COMMON_TEXT_COLOR 0x000000 +!define COMMON_BACKGROUND_COLOR 0xFFFFFF +!define INSTALL_INSTALLING_TEXT_COLOR 0xFFFFFF +# This color is written as 0x00BBGGRR because it's actually a COLORREF value. +!define PROGRESS_BAR_BACKGROUND_COLOR 0xFFAA00 diff --git a/browser/branding/custom/configure.sh b/browser/branding/custom/configure.sh new file mode 100644 index 0000000000000..d0437a8360e11 --- /dev/null +++ b/browser/branding/custom/configure.sh @@ -0,0 +1,6 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +MOZ_APP_DISPLAYNAME="Oasis" +MOZ_MACBUNDLE_ID=com.oasis.browser diff --git a/browser/branding/custom/content/about-logo-private.png b/browser/branding/custom/content/about-logo-private.png new file mode 100644 index 0000000000000..83c8b1fd1ce91 Binary files /dev/null and b/browser/branding/custom/content/about-logo-private.png differ diff --git a/browser/branding/custom/content/about-logo-private@2x.png b/browser/branding/custom/content/about-logo-private@2x.png new file mode 100644 index 0000000000000..301a453499492 Binary files /dev/null and b/browser/branding/custom/content/about-logo-private@2x.png differ diff --git a/browser/branding/custom/content/about-logo.png b/browser/branding/custom/content/about-logo.png new file mode 100644 index 0000000000000..dbabdd6b1b9c2 Binary files /dev/null and b/browser/branding/custom/content/about-logo.png differ diff --git a/browser/branding/custom/content/about-logo.svg b/browser/branding/custom/content/about-logo.svg new file mode 100644 index 0000000000000..18d9366357722 --- /dev/null +++ b/browser/branding/custom/content/about-logo.svg @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/browser/branding/custom/content/about-logo@2x.png b/browser/branding/custom/content/about-logo@2x.png new file mode 100644 index 0000000000000..301a453499492 Binary files /dev/null and b/browser/branding/custom/content/about-logo@2x.png differ diff --git a/browser/branding/custom/content/about-wordmark.svg b/browser/branding/custom/content/about-wordmark.svg new file mode 100644 index 0000000000000..04aab70fdab5d --- /dev/null +++ b/browser/branding/custom/content/about-wordmark.svg @@ -0,0 +1,3 @@ + + Oasis + diff --git a/browser/branding/custom/content/about.png b/browser/branding/custom/content/about.png new file mode 100644 index 0000000000000..61f72c971eb5f Binary files /dev/null and b/browser/branding/custom/content/about.png differ diff --git a/browser/branding/custom/content/aboutDialog.css b/browser/branding/custom/content/aboutDialog.css new file mode 100644 index 0000000000000..6c66cf20eca4c --- /dev/null +++ b/browser/branding/custom/content/aboutDialog.css @@ -0,0 +1,20 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#aboutDialogContainer { + background-color: #130829; + color: #fff; + color-scheme: dark; +} + +#rightBox { + background-size: auto 64px; + margin-inline: 30px; + padding-top: 64px; +} + +#bottomBox { + background-color: hsla(235, 43%, 10%, 0.5); + padding: 15px 10px 15px; +} diff --git a/browser/branding/custom/content/document_pdf.svg b/browser/branding/custom/content/document_pdf.svg new file mode 100644 index 0000000000000..dbdf71a9b7804 --- /dev/null +++ b/browser/branding/custom/content/document_pdf.svg @@ -0,0 +1,11 @@ + + + + + + + + + diff --git a/browser/branding/custom/content/firefox-wordmark.svg b/browser/branding/custom/content/firefox-wordmark.svg new file mode 100644 index 0000000000000..04aab70fdab5d --- /dev/null +++ b/browser/branding/custom/content/firefox-wordmark.svg @@ -0,0 +1,3 @@ + + Oasis + diff --git a/browser/branding/custom/content/jar.mn b/browser/branding/custom/content/jar.mn new file mode 100644 index 0000000000000..490670db04e78 --- /dev/null +++ b/browser/branding/custom/content/jar.mn @@ -0,0 +1,22 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +browser.jar: +% content branding %content/branding/ contentaccessible=yes + content/branding/about.png + content/branding/about-logo.png + content/branding/about-logo.svg + content/branding/about-logo@2x.png + content/branding/about-wordmark.svg + content/branding/about-logo-private.png + content/branding/about-logo-private@2x.png + content/branding/document.ico (../document.ico) + content/branding/document_pdf.svg + content/branding/firefox-wordmark.svg + content/branding/icon16.png (../default16.png) + content/branding/icon32.png (../default32.png) + content/branding/icon48.png (../default48.png) + content/branding/icon64.png (../default64.png) + content/branding/icon128.png (../default128.png) + content/branding/aboutDialog.css diff --git a/browser/branding/custom/content/moz.build b/browser/branding/custom/content/moz.build new file mode 100644 index 0000000000000..d988c0ff9b162 --- /dev/null +++ b/browser/branding/custom/content/moz.build @@ -0,0 +1,7 @@ +# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*- +# vim: set filetype=python: +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +JAR_MANIFESTS += ["jar.mn"] diff --git a/browser/branding/custom/convert_logo.sh b/browser/branding/custom/convert_logo.sh new file mode 100755 index 0000000000000..034436e4473c3 --- /dev/null +++ b/browser/branding/custom/convert_logo.sh @@ -0,0 +1,105 @@ +#!/bin/bash + +# Script to convert kahana_logo.svg to all required icon formats +# This script generates: +# - New tab page logos (about-logo.png, about-logo@2x.png) +# - Tab icons (default16.png, default32.png, default48.png, default64.png, default128.png) +# - macOS dock icon (firefox.icns) + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +SVG_FILE="$SCRIPT_DIR/kahana_logo.svg" +OUTPUT_DIR="$SCRIPT_DIR" + +# Check if SVG file exists +if [ ! -f "$SVG_FILE" ]; then + echo "Error: $SVG_FILE not found!" + exit 1 +fi + +# Check for required tools +if command -v rsvg-convert &> /dev/null; then + CONVERT_CMD="rsvg-convert" +elif command -v magick &> /dev/null; then + CONVERT_CMD="magick" +elif command -v convert &> /dev/null; then + CONVERT_CMD="convert" +else + echo "Error: Neither rsvg-convert nor ImageMagick found!" + echo "Install with: brew install librsvg (for rsvg-convert) or brew install imagemagick (for magick)" + exit 1 +fi + +echo "Converting kahana_logo.svg to required formats..." +echo "Using: $CONVERT_CMD" + +# Function to convert SVG to PNG +convert_svg_to_png() { + local size=$1 + local output=$2 + + if [ "$CONVERT_CMD" = "rsvg-convert" ]; then + rsvg-convert -w $size -h $size "$SVG_FILE" -o "$output" + elif [ "$CONVERT_CMD" = "magick" ]; then + magick "$SVG_FILE" -background none -resize "${size}x${size}" "$output" + else + convert "$SVG_FILE" -background none -resize "${size}x${size}" "$output" + fi +} + +# 1. New tab page logos +echo "Creating new tab page logos..." +convert_svg_to_png 64 "$OUTPUT_DIR/content/about-logo.png" +convert_svg_to_png 128 "$OUTPUT_DIR/content/about-logo@2x.png" +# Also create SVG version for new tab page +cp "$SVG_FILE" "$OUTPUT_DIR/content/about-logo.svg" + +# 2. Tab icons (favicons) +echo "Creating tab icons..." +convert_svg_to_png 16 "$OUTPUT_DIR/default16.png" +convert_svg_to_png 32 "$OUTPUT_DIR/default32.png" +convert_svg_to_png 48 "$OUTPUT_DIR/default48.png" +convert_svg_to_png 64 "$OUTPUT_DIR/default64.png" +convert_svg_to_png 128 "$OUTPUT_DIR/default128.png" + +# 3. macOS dock icon (.icns) +echo "Creating macOS dock icon..." +ICONSET_DIR="$OUTPUT_DIR/firefox.iconset" +rm -rf "$ICONSET_DIR" +mkdir -p "$ICONSET_DIR" + +# Create all required icon sizes for .icns +convert_svg_to_png 16 "$ICONSET_DIR/icon_16x16.png" +convert_svg_to_png 32 "$ICONSET_DIR/icon_16x16@2x.png" +convert_svg_to_png 32 "$ICONSET_DIR/icon_32x32.png" +convert_svg_to_png 64 "$ICONSET_DIR/icon_32x32@2x.png" +convert_svg_to_png 128 "$ICONSET_DIR/icon_128x128.png" +convert_svg_to_png 256 "$ICONSET_DIR/icon_128x128@2x.png" +convert_svg_to_png 256 "$ICONSET_DIR/icon_256x256.png" +convert_svg_to_png 512 "$ICONSET_DIR/icon_256x256@2x.png" +convert_svg_to_png 512 "$ICONSET_DIR/icon_512x512.png" +convert_svg_to_png 1024 "$ICONSET_DIR/icon_512x512@2x.png" + +# Convert iconset to .icns +if command -v iconutil &> /dev/null; then + iconutil -c icns "$ICONSET_DIR" -o "$OUTPUT_DIR/firefox.icns" + rm -rf "$ICONSET_DIR" + echo "Created firefox.icns successfully!" +else + echo "Warning: iconutil not found. .icns file not created." + echo "You can create it manually with: iconutil -c icns $ICONSET_DIR" +fi + +# Also create private browsing logo variants +echo "Creating private browsing logos..." +convert_svg_to_png 64 "$OUTPUT_DIR/content/about-logo-private.png" +convert_svg_to_png 128 "$OUTPUT_DIR/content/about-logo-private@2x.png" + +echo "" +echo "✓ All logo conversions complete!" +echo "" +echo "Generated files:" +echo " - New tab page: content/about-logo.png, content/about-logo@2x.png, content/about-logo.svg" +echo " - Tab icons: default16.png, default32.png, default48.png, default64.png, default128.png" +echo " - Dock icon: firefox.icns" +echo " - Private browsing: content/about-logo-private.png, content/about-logo-private@2x.png" + diff --git a/browser/branding/custom/default128.png b/browser/branding/custom/default128.png new file mode 100644 index 0000000000000..3871975ddd239 Binary files /dev/null and b/browser/branding/custom/default128.png differ diff --git a/browser/branding/custom/default16.png b/browser/branding/custom/default16.png new file mode 100644 index 0000000000000..b650bb17547dd Binary files /dev/null and b/browser/branding/custom/default16.png differ diff --git a/browser/branding/custom/default22.png b/browser/branding/custom/default22.png new file mode 100644 index 0000000000000..960b1837227ae Binary files /dev/null and b/browser/branding/custom/default22.png differ diff --git a/browser/branding/custom/default24.png b/browser/branding/custom/default24.png new file mode 100644 index 0000000000000..30f573549ef8e Binary files /dev/null and b/browser/branding/custom/default24.png differ diff --git a/browser/branding/custom/default256.png b/browser/branding/custom/default256.png new file mode 100644 index 0000000000000..37b5a4d2fe26f Binary files /dev/null and b/browser/branding/custom/default256.png differ diff --git a/browser/branding/custom/default32.png b/browser/branding/custom/default32.png new file mode 100644 index 0000000000000..5e508cdd7864b Binary files /dev/null and b/browser/branding/custom/default32.png differ diff --git a/browser/branding/custom/default48.png b/browser/branding/custom/default48.png new file mode 100644 index 0000000000000..44baadaa5ef54 Binary files /dev/null and b/browser/branding/custom/default48.png differ diff --git a/browser/branding/custom/default64.png b/browser/branding/custom/default64.png new file mode 100644 index 0000000000000..3366fbc863268 Binary files /dev/null and b/browser/branding/custom/default64.png differ diff --git a/browser/branding/custom/disk.icns b/browser/branding/custom/disk.icns new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/browser/branding/custom/document.icns b/browser/branding/custom/document.icns new file mode 100644 index 0000000000000..6733b9ff3e946 Binary files /dev/null and b/browser/branding/custom/document.icns differ diff --git a/browser/branding/custom/document.ico b/browser/branding/custom/document.ico new file mode 100644 index 0000000000000..2f4cdd6a070a5 Binary files /dev/null and b/browser/branding/custom/document.ico differ diff --git a/browser/branding/custom/document_pdf.ico b/browser/branding/custom/document_pdf.ico new file mode 100644 index 0000000000000..fc76b0740cf19 Binary files /dev/null and b/browser/branding/custom/document_pdf.ico differ diff --git a/browser/branding/custom/dsstore b/browser/branding/custom/dsstore new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/browser/branding/custom/firefox.VisualElementsManifest.xml b/browser/branding/custom/firefox.VisualElementsManifest.xml new file mode 100644 index 0000000000000..85e09dd7a910f --- /dev/null +++ b/browser/branding/custom/firefox.VisualElementsManifest.xml @@ -0,0 +1,12 @@ + + + + + diff --git a/browser/branding/custom/firefox.icns b/browser/branding/custom/firefox.icns new file mode 100644 index 0000000000000..34d82e11526fd Binary files /dev/null and b/browser/branding/custom/firefox.icns differ diff --git a/browser/branding/custom/firefox.ico b/browser/branding/custom/firefox.ico new file mode 100644 index 0000000000000..27bd9980f6f79 Binary files /dev/null and b/browser/branding/custom/firefox.ico differ diff --git a/browser/branding/custom/firefox64.ico b/browser/branding/custom/firefox64.ico new file mode 100644 index 0000000000000..4b53ac29dba9e Binary files /dev/null and b/browser/branding/custom/firefox64.ico differ diff --git a/browser/branding/custom/kahana_logo.svg b/browser/branding/custom/kahana_logo.svg new file mode 100644 index 0000000000000..18d9366357722 --- /dev/null +++ b/browser/branding/custom/kahana_logo.svg @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/browser/branding/custom/locales/en-US/brand.ftl b/browser/branding/custom/locales/en-US/brand.ftl new file mode 100644 index 0000000000000..4c6ac206a81b3 --- /dev/null +++ b/browser/branding/custom/locales/en-US/brand.ftl @@ -0,0 +1,27 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +## Firefox and Mozilla Brand +## +## Firefox and Mozilla must be treated as a brand. +## +## They cannot be: +## - Transliterated. +## - Translated. +## +## Declension should be avoided where possible, leaving the original +## brand unaltered in prominent UI positions. +## +## For further details, consult: +## https://mozilla-l10n.github.io/styleguides/mozilla_general/#brands-copyright-and-trademark + +-brand-shorter-name = Oasis +-brand-short-name = Oasis +-brand-shortcut-name = Oasis +-brand-full-name = Oasis +# This brand name can be used in messages where the product name needs to +# remain unchanged across different versions (Nightly, Beta, etc.). +-brand-product-name = Oasis +-vendor-short-name = Mozilla +trademarkInfo = { " " } diff --git a/browser/branding/custom/locales/en-US/brand.properties b/browser/branding/custom/locales/en-US/brand.properties new file mode 100644 index 0000000000000..d36b478d075d4 --- /dev/null +++ b/browser/branding/custom/locales/en-US/brand.properties @@ -0,0 +1,7 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +brandShorterName=Oasis +brandShortName=Oasis +brandFullName=Oasis diff --git a/browser/branding/custom/locales/jar.mn b/browser/branding/custom/locales/jar.mn new file mode 100644 index 0000000000000..e67add60f582a --- /dev/null +++ b/browser/branding/custom/locales/jar.mn @@ -0,0 +1,12 @@ +#filter substitution +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +[localization] @AB_CD@.jar: + branding (en-US/**/*.ftl) + +@AB_CD@.jar: +% locale branding @AB_CD@ %locale/branding/ +# Unofficial branding only exists in en-US + locale/branding/brand.properties (en-US/brand.properties) diff --git a/browser/branding/custom/locales/moz.build b/browser/branding/custom/locales/moz.build new file mode 100644 index 0000000000000..d988c0ff9b162 --- /dev/null +++ b/browser/branding/custom/locales/moz.build @@ -0,0 +1,7 @@ +# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*- +# vim: set filetype=python: +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +JAR_MANIFESTS += ["jar.mn"] diff --git a/browser/branding/custom/moz.build b/browser/branding/custom/moz.build new file mode 100644 index 0000000000000..560b698c3355f --- /dev/null +++ b/browser/branding/custom/moz.build @@ -0,0 +1,22 @@ +# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*- +# vim: set filetype=python: +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +with Files("**"): + BUG_COMPONENT = ("Firefox", "General") + +with Files("moz.build"): + BUG_COMPONENT = ("Firefox Build System", "General") + +with Files("configure.sh"): + BUG_COMPONENT = ("Firefox Build System", "General") + +# Custom branding for Kahana Browser +DIRS += ["content", "locales"] + +DIST_SUBDIR = "browser" + +include("../branding-common.mozbuild") +FirefoxBranding() diff --git a/browser/branding/custom/newtab.ico b/browser/branding/custom/newtab.ico new file mode 100644 index 0000000000000..a9b37c08c6e18 Binary files /dev/null and b/browser/branding/custom/newtab.ico differ diff --git a/browser/branding/custom/newwindow.ico b/browser/branding/custom/newwindow.ico new file mode 100644 index 0000000000000..55372077102c4 Binary files /dev/null and b/browser/branding/custom/newwindow.ico differ diff --git a/browser/branding/custom/pbmode.ico b/browser/branding/custom/pbmode.ico new file mode 100644 index 0000000000000..6462477dbab77 Binary files /dev/null and b/browser/branding/custom/pbmode.ico differ diff --git a/browser/branding/custom/pref/firefox-branding.js b/browser/branding/custom/pref/firefox-branding.js new file mode 100644 index 0000000000000..f22dd0a51ccb3 --- /dev/null +++ b/browser/branding/custom/pref/firefox-branding.js @@ -0,0 +1,32 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +// This file contains branding-specific prefs. + +pref("startup.homepage_override_url", ""); +pref("startup.homepage_welcome_url", ""); +pref("startup.homepage_welcome_url.additional", ""); +// The time interval between checks for a new version (in seconds) +pref("app.update.interval", 86400); // 24 hours +// Give the user x seconds to react before showing the big UI. default=24 hours +pref("app.update.promptWaitTime", 86400); +// URL user can browse to manually if for some reason all update installation +// attempts fail. +pref("app.update.url.manual", "https://nightly.mozilla.org"); +// A default value for the "More information about this update" link +// supplied in the "An update is available" page of the update wizard. +pref("app.update.url.details", "https://nightly.mozilla.org"); + +// The number of days a binary is permitted to be old +// without checking for an update. This assumes that +// app.update.checkInstallTime is true. +pref("app.update.checkInstallTime.days", 2); + +// Give the user x seconds to reboot before showing a badge on the hamburger +// button. default=immediately +pref("app.update.badgeWaitTime", 0); + +// Number of usages of the web console. +// If this is less than 5, then pasting code into the web console is disabled +pref("devtools.selfxss.count", 5); diff --git a/browser/branding/custom/private_browsing.VisualElementsManifest.xml b/browser/branding/custom/private_browsing.VisualElementsManifest.xml new file mode 100644 index 0000000000000..fdff8c55ffe3b --- /dev/null +++ b/browser/branding/custom/private_browsing.VisualElementsManifest.xml @@ -0,0 +1,12 @@ + + + + + diff --git a/browser/branding/custom/stubinstaller/bgstub.jpg b/browser/branding/custom/stubinstaller/bgstub.jpg new file mode 100644 index 0000000000000..4d6240399c627 Binary files /dev/null and b/browser/branding/custom/stubinstaller/bgstub.jpg differ diff --git a/browser/branding/custom/stubinstaller/installing_page.css b/browser/branding/custom/stubinstaller/installing_page.css new file mode 100644 index 0000000000000..b9ddbd7a9bad8 --- /dev/null +++ b/browser/branding/custom/stubinstaller/installing_page.css @@ -0,0 +1,87 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +body { + color: black; +} + +/* + * We want to treat the two pieces of text in the left column as one unit and + center that unit vertically in the window. In order to make IE8 do that, + we have to wrap the two bits of text in a container and make that a + table-cell (which means we need an outer container that's display: table). + So that's what this mess is doing. + */ +#text_column { + position: fixed; + height: 100%; + margin-left: 30px; + width: 40%; + display: table; +} + +#text_column_container { + display: table-cell; + vertical-align: middle; + padding-top: 60px; +} + +#header { + font-size: 24px; + font-weight: 700; + margin-top: 0; +} + +#content { + font-size: 22px; +} + +#installing { + position: fixed; + right: 30px; + bottom: 55%; + margin-top: auto; + margin-bottom: auto; + width: 35%; +} + +#label { + color: white; + + position: relative; + top: 50px; + + text-align: center; + font-size: 20px; +} + +#progress_background { + width: 100%; + height: 20px; + background-color: white; +} + +body.high-contrast #progress_background { + outline: solid; +} + +#progress_bar { + margin: 0; + width: 0%; + height: 100%; + background-color: #00aaff; +} + +/* In high contrast mode, fill the entire progress bar with its border. */ +body.high-contrast #progress_bar { + /* This border should be the height of progress_background. */ + border-top: 20px solid; + box-sizing: border-box; +} + +/* No blurb or footer for this layout. */ +#blurb, +#footer { + visibility: hidden; +} diff --git a/browser/branding/custom/stubinstaller/profile_cleanup_page.css b/browser/branding/custom/stubinstaller/profile_cleanup_page.css new file mode 100644 index 0000000000000..a8dbad0e110e0 --- /dev/null +++ b/browser/branding/custom/stubinstaller/profile_cleanup_page.css @@ -0,0 +1,75 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +body { + color: black; +} + +/* + * We want to treat the two pieces of text in the left column as one unit and + center that unit vertically in the window. In order to make IE8 do that, + we have to wrap the two bits of text in a container and make that a + table-cell (which means we need an outer container that's display: table). + So that's what this mess is doing. + */ +#profileRefreshForm { + position: fixed; + height: 100%; + margin-left: 30px; + width: 40%; + display: table; +} + +#profileRefreshContainer { + display: table-cell; + vertical-align: middle; +} + +#refreshCheckboxContainer, +#refreshButtonContainer { + margin-top: 20px; +} + +#header { + font-size: 25px; + font-weight: 600; +} + +#refreshCheckboxContainer { + position: relative; +} + +#refreshCheckbox { + position: absolute; + top: 1px; +} + +#checkboxLabel { + font-size: 14px; + display: block; +} + +.checkboxLabel-ltr { + margin-left: 25px; +} + +.checkboxLabel-rtl { + margin-right: 25px; +} + +#refreshButton { + padding: 8px 70px; + font-size: 16px; + background: #005ccc; + color: white; +} + +body.normal-contrast #refreshButton { + border: none; +} + +/* No footer for this layout. */ +#footer { + visibility: hidden; +} diff --git a/browser/branding/custom/wizHeader.bmp b/browser/branding/custom/wizHeader.bmp new file mode 100644 index 0000000000000..420824226dfe8 Binary files /dev/null and b/browser/branding/custom/wizHeader.bmp differ diff --git a/browser/branding/custom/wizHeaderRTL.bmp b/browser/branding/custom/wizHeaderRTL.bmp new file mode 100644 index 0000000000000..7f74929910bdb Binary files /dev/null and b/browser/branding/custom/wizHeaderRTL.bmp differ diff --git a/browser/branding/custom/wizWatermark.bmp b/browser/branding/custom/wizWatermark.bmp new file mode 100644 index 0000000000000..b3b3c91d327c9 Binary files /dev/null and b/browser/branding/custom/wizWatermark.bmp differ diff --git a/browser/branding/official/locales/en-US/brand.ftl b/browser/branding/official/locales/en-US/brand.ftl index 8496cb22ffb1f..573550ac0dff1 100644 --- a/browser/branding/official/locales/en-US/brand.ftl +++ b/browser/branding/official/locales/en-US/brand.ftl @@ -16,12 +16,12 @@ ## For further details, consult: ## https://mozilla-l10n.github.io/styleguides/mozilla_general/#brands-copyright-and-trademark --brand-shorter-name = Firefox --brand-short-name = Firefox --brand-shortcut-name = Firefox --brand-full-name = Mozilla Firefox +-brand-shorter-name = Oasis +-brand-short-name = Oasis +-brand-shortcut-name = Oasis +-brand-full-name = Oasis # This brand name can be used in messages where the product name needs to # remain unchanged across different versions (Nightly, Beta, etc.). --brand-product-name = Firefox --vendor-short-name = Mozilla +-brand-product-name = Oasis +-vendor-short-name = Oasis trademarkInfo = Firefox and the Firefox logos are trademarks of the Mozilla Foundation. diff --git a/browser/components/customizableui/content/panelUI.inc.xhtml b/browser/components/customizableui/content/panelUI.inc.xhtml index 6cb22be6526b1..ebed24d29e3c2 100644 --- a/browser/components/customizableui/content/panelUI.inc.xhtml +++ b/browser/components/customizableui/content/panelUI.inc.xhtml @@ -100,7 +100,7 @@ - + diff --git a/browser/components/preferences/home.inc.xhtml b/browser/components/preferences/home.inc.xhtml index d2edd16fc3854..33a5d62b4e6d3 100644 --- a/browser/components/preferences/home.inc.xhtml +++ b/browser/components/preferences/home.inc.xhtml @@ -107,8 +107,8 @@ - diff --git a/browser/components/preferences/main.inc.xhtml b/browser/components/preferences/main.inc.xhtml index 171021979f478..826fc7c1eec2d 100644 --- a/browser/components/preferences/main.inc.xhtml +++ b/browser/components/preferences/main.inc.xhtml @@ -42,8 +42,75 @@ -